oxicuda_driver/module.rs
1//! PTX module loading and kernel function management.
2//!
3//! Modules are created from PTX source code and contain one or more
4//! kernel functions that can be launched on the GPU.
5//!
6//! # Example
7//!
8//! ```rust,no_run
9//! # use oxicuda_driver::module::{Module, JitOptions};
10//! # fn main() -> Result<(), oxicuda_driver::error::CudaError> {
11//! let ptx = r#"
12//! .version 7.0
13//! .target sm_70
14//! .address_size 64
15//! .visible .entry my_kernel() { ret; }
16//! "#;
17//!
18//! let module = Module::from_ptx(ptx)?;
19//! let func = module.get_function("my_kernel")?;
20//!
21//! // Or with JIT options and compilation logs:
22//! let opts = JitOptions { optimization_level: 4, ..Default::default() };
23//! let (module2, log) = Module::from_ptx_with_options(ptx, &opts)?;
24//! if !log.info.is_empty() {
25//! println!("JIT info: {}", log.info);
26//! }
27//! # Ok(())
28//! # }
29//! ```
30
31use std::ffi::{CString, c_void};
32
33use crate::error::{CudaError, CudaResult};
34use crate::ffi::{CUfunction, CUjit_option, CUmodule};
35use crate::loader::try_driver;
36
37// ---------------------------------------------------------------------------
38// JitOptions
39// ---------------------------------------------------------------------------
40
41/// Options for JIT compilation of PTX to GPU binary.
42///
43/// These options control the behaviour of the CUDA JIT compiler when
44/// loading PTX source via [`Module::from_ptx_with_options`].
45#[derive(Debug, Clone)]
46pub struct JitOptions {
47 /// Maximum number of registers per thread (0 = no limit).
48 ///
49 /// Limiting register usage can increase occupancy at the cost of
50 /// potential register spilling to local memory.
51 pub max_registers: u32,
52 /// Optimisation level (0--4, default 4).
53 ///
54 /// Higher levels produce faster code but take longer to compile.
55 pub optimization_level: u32,
56 /// Whether to generate debug information in the compiled binary.
57 pub generate_debug_info: bool,
58 /// If `true`, the JIT compiler determines the target compute
59 /// capability from the current CUDA context.
60 pub target_from_context: bool,
61}
62
63impl Default for JitOptions {
64 /// Returns sensible defaults: no register limit, maximum
65 /// optimisation, no debug info, target derived from context.
66 fn default() -> Self {
67 Self {
68 max_registers: 0,
69 optimization_level: 4,
70 generate_debug_info: false,
71 target_from_context: true,
72 }
73 }
74}
75
76// ---------------------------------------------------------------------------
77// JitLog
78// ---------------------------------------------------------------------------
79
80/// Severity of a JIT compiler diagnostic message.
81#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
82pub enum JitSeverity {
83 /// A fatal error that prevents PTX compilation.
84 Fatal,
85 /// A non-fatal error.
86 Error,
87 /// A compiler warning (compilation may still succeed).
88 Warning,
89 /// An informational message (e.g. register usage).
90 Info,
91}
92
93impl std::fmt::Display for JitSeverity {
94 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
95 match self {
96 Self::Fatal => f.write_str("fatal"),
97 Self::Error => f.write_str("error"),
98 Self::Warning => f.write_str("warning"),
99 Self::Info => f.write_str("info"),
100 }
101 }
102}
103
104/// A single structured diagnostic emitted by the JIT compiler.
105///
106/// Parsed from the raw `ptxas` log lines that look like:
107///
108/// ```text
109/// ptxas error : 'kernel', line 10; error : Unknown instruction 'xyz'
110/// ptxas warning : 'kernel', line 15; warning : double-precision is slow
111/// ptxas info : 'kernel' used 16 registers, 0 bytes smem
112/// ```
113#[derive(Debug, Clone, PartialEq, Eq, Hash)]
114pub struct JitDiagnostic {
115 /// Severity level.
116 pub severity: JitSeverity,
117 /// Kernel function name, if the message is function-scoped.
118 pub kernel: Option<String>,
119 /// Source line number, if present.
120 pub line: Option<u32>,
121 /// Human-readable message text.
122 pub message: String,
123}
124
125/// Log output from JIT compilation.
126///
127/// After calling [`Module::from_ptx_with_options`], this struct
128/// contains any informational or error messages emitted by the
129/// JIT compiler.
130///
131/// Use [`JitLog::parse_diagnostics`] to obtain structured
132/// [`JitDiagnostic`] entries instead of parsing the raw strings.
133#[derive(Debug, Clone, Default, PartialEq, Eq, Hash)]
134pub struct JitLog {
135 /// Informational messages from the JIT compiler.
136 pub info: String,
137 /// Error messages from the JIT compiler.
138 pub error: String,
139}
140
141impl JitLog {
142 /// Returns `true` if there are no messages in either buffer.
143 #[must_use]
144 pub fn is_empty(&self) -> bool {
145 self.info.is_empty() && self.error.is_empty()
146 }
147
148 /// Returns `true` if the error buffer is non-empty.
149 #[must_use]
150 pub fn has_errors(&self) -> bool {
151 !self.error.is_empty()
152 }
153
154 /// Parse both log buffers into a `Vec` of structured [`JitDiagnostic`]
155 /// entries.
156 ///
157 /// Lines that do not match the `ptxas` diagnostic format are included as
158 /// [`JitSeverity::Info`] diagnostics with no kernel or line information,
159 /// unless they are entirely blank.
160 ///
161 /// # Message format
162 ///
163 /// The CUDA JIT compiler emits lines in one of these formats:
164 ///
165 /// ```text
166 /// ptxas {severity} : '{kernel}', line {n}; {type} : {message}
167 /// ptxas {severity} : '{kernel}' {message}
168 /// ptxas {severity} : {message}
169 /// ```
170 ///
171 /// This method normalises all of those into [`JitDiagnostic`] values.
172 #[must_use]
173 pub fn parse_diagnostics(&self) -> Vec<JitDiagnostic> {
174 let mut out = Vec::new();
175 for line in self.error.lines().chain(self.info.lines()) {
176 if let Some(d) = parse_ptxas_line(line) {
177 out.push(d);
178 }
179 }
180 out
181 }
182
183 /// Return only the [`JitDiagnostic`] entries whose severity is
184 /// [`JitSeverity::Error`] or [`JitSeverity::Fatal`].
185 #[must_use]
186 pub fn errors(&self) -> Vec<JitDiagnostic> {
187 self.parse_diagnostics()
188 .into_iter()
189 .filter(|d| matches!(d.severity, JitSeverity::Error | JitSeverity::Fatal))
190 .collect()
191 }
192
193 /// Return only the [`JitDiagnostic`] entries whose severity is
194 /// [`JitSeverity::Warning`].
195 #[must_use]
196 pub fn warnings(&self) -> Vec<JitDiagnostic> {
197 self.parse_diagnostics()
198 .into_iter()
199 .filter(|d| matches!(d.severity, JitSeverity::Warning))
200 .collect()
201 }
202}
203
204// ── ptxas log line parser ─────────────────────────────────────────────────────
205
206/// Parse a single `ptxas` log line into a [`JitDiagnostic`], returning
207/// `None` for blank lines.
208///
209/// Handles these representative patterns:
210///
211/// ```text
212/// ptxas error : 'vec_add', line 10; error : Unknown instruction 'xyz'
213/// ptxas warning : 'vec_add', line 15; warning : slow double-precision
214/// ptxas info : 'vec_add' used 16 registers, 0 bytes smem, 0 bytes cmem[0]
215/// ptxas fatal : Unresolved extern function 'foo'
216/// ```
217fn parse_ptxas_line(line: &str) -> Option<JitDiagnostic> {
218 let line = line.trim();
219 if line.is_empty() {
220 return None;
221 }
222
223 // Must start with "ptxas " (case-insensitive is not needed — ptxas always
224 // uses lower-case).
225 let rest = line.strip_prefix("ptxas ")?;
226
227 // Extract severity word (first whitespace-delimited token).
228 let (sev_str, after_sev) = split_first_word(rest.trim_start());
229 let severity = match sev_str.to_ascii_lowercase().trim_end_matches(':') {
230 "fatal" => JitSeverity::Fatal,
231 "error" => JitSeverity::Error,
232 "warning" => JitSeverity::Warning,
233 "info" => JitSeverity::Info,
234 _ => JitSeverity::Info,
235 };
236
237 // Skip past `: ` after the severity keyword.
238 let body = skip_colon(after_sev.trim_start());
239
240 // Try to extract kernel name from `'kernel_name'` at the start.
241 let (kernel, after_kernel) = extract_kernel_name(body);
242
243 // Try to extract line number: `, line N;` or `, line N,`.
244 let (line_no, after_line) = extract_line_number(after_kernel);
245
246 // The remaining text — skip a leading type word if present (e.g. `error : `).
247 let message = extract_message(after_line.trim());
248
249 Some(JitDiagnostic {
250 severity,
251 kernel,
252 line: line_no,
253 message: message.to_string(),
254 })
255}
256
257/// Split a `&str` at the first whitespace boundary; returns `("", s)` if
258/// there is no whitespace.
259fn split_first_word(s: &str) -> (&str, &str) {
260 match s.find(|c: char| c.is_whitespace()) {
261 Some(pos) => (&s[..pos], &s[pos..]),
262 None => (s, ""),
263 }
264}
265
266/// Skip past the first `: ` (colon + optional spaces) in `s`.
267fn skip_colon(s: &str) -> &str {
268 if let Some(pos) = s.find(':') {
269 s[pos + 1..].trim_start()
270 } else {
271 s
272 }
273}
274
275/// Attempt to extract `'kernel_name'` from the beginning of `s`.
276/// Returns `(Some(name), rest_after_name)` or `(None, s)`.
277fn extract_kernel_name(s: &str) -> (Option<String>, &str) {
278 let s = s.trim_start();
279 if !s.starts_with('\'') {
280 return (None, s);
281 }
282 let inner = &s[1..];
283 if let Some(end) = inner.find('\'') {
284 let name = inner[..end].to_string();
285 let after = &inner[end + 1..];
286 (Some(name), after)
287 } else {
288 (None, s)
289 }
290}
291
292/// Attempt to extract `, line N;` or `, line N,` from the start of `s`.
293/// Returns `(Some(n), rest)` or `(None, s)`.
294fn extract_line_number(s: &str) -> (Option<u32>, &str) {
295 // Accept `, line N` (with optional trailing `;` or `,`)
296 let s_trim = s.trim_start_matches([',', ' ', ';']);
297 let lower = s_trim.to_ascii_lowercase();
298 if !lower.starts_with("line ") {
299 return (None, s);
300 }
301 let after_line = &s_trim[5..]; // skip "line "
302 let (num_str, rest) = split_first_word(after_line.trim_start());
303 let num_clean: String = num_str.chars().filter(|c| c.is_ascii_digit()).collect();
304 if let Ok(n) = num_clean.parse::<u32>() {
305 (Some(n), rest)
306 } else {
307 (None, s)
308 }
309}
310
311/// Strip a leading `type : ` prefix (e.g. `error : ` or `warning : `)
312/// from a message if present; return the remaining text.
313fn extract_message(s: &str) -> &str {
314 // Pattern: word followed by optional spaces and `:`.
315 let (word, rest) = split_first_word(s);
316 let word_clean = word.trim_end_matches(':');
317 if matches!(
318 word_clean.to_ascii_lowercase().as_str(),
319 "error" | "warning" | "info" | "fatal"
320 ) {
321 skip_colon(rest.trim_start())
322 } else {
323 s
324 }
325}
326
327// ---------------------------------------------------------------------------
328// jit_failure — build a JitFailed error from raw log buffers
329// ---------------------------------------------------------------------------
330
331/// Build a [`CudaError::JitFailed`] by combining the raw JIT log buffers
332/// with the underlying CUDA error.
333///
334/// Both `info_buf` and `error_buf` are interpreted as UTF-8 (with lossy
335/// conversion), parsed for structured diagnostics, and wrapped together
336/// with `source` into a [`CudaError::JitFailed`] variant.
337///
338/// This is `pub(crate)` so that both `module.rs` and `link.rs` can call
339/// it without exposing it as part of the public API.
340///
341/// Only compiled on non-macOS platforms because `link.rs`'s GPU path
342/// is the sole caller.
343#[cfg(not(target_os = "macos"))]
344pub(crate) fn jit_failure(source: CudaError, info_buf: &[u8], error_buf: &[u8]) -> CudaError {
345 let info = String::from_utf8_lossy(info_buf).into_owned();
346 let error = String::from_utf8_lossy(error_buf).into_owned();
347
348 let log = JitLog { info, error };
349 let diagnostic_count = log.parse_diagnostics().len();
350
351 CudaError::JitFailed {
352 log: Box::new(log),
353 diagnostic_count,
354 source: Box::new(source),
355 }
356}
357
358/// Variant of [`jit_failure`] that accepts a pre-built [`JitLog`].
359///
360/// Used when the log has already been assembled (e.g. in
361/// [`Module::from_ptx_with_options`] where the log was extracted
362/// before checking for a compilation error).
363pub(crate) fn jit_failure_from_log(source: CudaError, log: JitLog) -> CudaError {
364 let diagnostic_count = log.parse_diagnostics().len();
365 CudaError::JitFailed {
366 log: Box::new(log),
367 diagnostic_count,
368 source: Box::new(source),
369 }
370}
371
372// ---------------------------------------------------------------------------
373// Module
374// ---------------------------------------------------------------------------
375
376/// A loaded CUDA module containing one or more kernel functions.
377///
378/// Modules are typically created from PTX source via [`Module::from_ptx`]
379/// or [`Module::from_ptx_with_options`]. Individual kernel functions
380/// are retrieved by name with [`Module::get_function`].
381///
382/// The module is unloaded when this struct is dropped.
383pub struct Module {
384 /// Raw CUDA module handle.
385 raw: CUmodule,
386 /// The context that owned this module at load time, used to skip the driver
387 /// unload if that context was torn down first (avoids a use-after-free).
388 /// `None` when no tracked context was current — see
389 /// [`crate::context::current_ctx_owner`].
390 owner: crate::context::CtxOwner,
391}
392
393// `Module` is `Send + Sync` by auto-derivation: its only field is a `CUmodule`
394// handle (a plain driver-side identifier). The CUDA Driver API is thread-safe,
395// so no manual `unsafe impl` is required.
396
397/// Size of the JIT log buffers in bytes.
398const JIT_LOG_BUFFER_SIZE: usize = 4096;
399
400impl Module {
401 /// Loads a module from PTX source with default JIT options.
402 ///
403 /// The PTX string is automatically null-terminated before being
404 /// passed to the driver.
405 ///
406 /// # Errors
407 ///
408 /// Returns [`CudaError::InvalidImage`] if
409 /// the PTX is malformed, or another [`CudaError`] if the driver
410 /// call fails (e.g. no current context).
411 pub fn from_ptx(ptx: &str) -> CudaResult<Self> {
412 let api = try_driver()?;
413 let c_ptx = CString::new(ptx).map_err(|_| CudaError::InvalidValue)?;
414 let mut raw = CUmodule::default();
415 crate::cuda_call!((api.cu_module_load_data)(
416 &mut raw,
417 c_ptx.as_ptr().cast::<c_void>()
418 ))?;
419 Ok(Self {
420 raw,
421 owner: crate::context::current_ctx_owner(),
422 })
423 }
424
425 /// Loads a module from PTX source with explicit JIT compiler options.
426 ///
427 /// Returns the loaded module together with a [`JitLog`] containing
428 /// any informational or error messages from the JIT compiler.
429 ///
430 /// # Errors
431 ///
432 /// Returns a [`CudaError`] if JIT compilation fails or the driver
433 /// call otherwise errors.
434 pub fn from_ptx_with_options(ptx: &str, options: &JitOptions) -> CudaResult<(Self, JitLog)> {
435 let api = try_driver()?;
436 let c_ptx = CString::new(ptx).map_err(|_| CudaError::InvalidValue)?;
437
438 // Allocate log buffers on the heap.
439 let mut info_buf: Vec<u8> = vec![0u8; JIT_LOG_BUFFER_SIZE];
440 let mut error_buf: Vec<u8> = vec![0u8; JIT_LOG_BUFFER_SIZE];
441
442 // Build the parallel option-key and option-value arrays.
443 //
444 // Each option is a (CUjit_option, *mut c_void) pair. The value
445 // pointer is reinterpreted according to the option key — scalar
446 // values are cast directly to pointer-width integers.
447 let mut opt_keys: Vec<CUjit_option> = Vec::with_capacity(8);
448 let mut opt_vals: Vec<*mut c_void> = Vec::with_capacity(8);
449
450 // Info log buffer.
451 opt_keys.push(CUjit_option::InfoLogBuffer);
452 opt_vals.push(info_buf.as_mut_ptr().cast::<c_void>());
453
454 opt_keys.push(CUjit_option::InfoLogBufferSizeBytes);
455 opt_vals.push(JIT_LOG_BUFFER_SIZE as *mut c_void);
456
457 // Error log buffer.
458 opt_keys.push(CUjit_option::ErrorLogBuffer);
459 opt_vals.push(error_buf.as_mut_ptr().cast::<c_void>());
460
461 opt_keys.push(CUjit_option::ErrorLogBufferSizeBytes);
462 opt_vals.push(JIT_LOG_BUFFER_SIZE as *mut c_void);
463
464 // Optimisation level.
465 opt_keys.push(CUjit_option::OptimizationLevel);
466 opt_vals.push(options.optimization_level as *mut c_void);
467
468 // Max registers (only if non-zero to avoid overriding defaults).
469 if options.max_registers > 0 {
470 opt_keys.push(CUjit_option::MaxRegisters);
471 opt_vals.push(options.max_registers as *mut c_void);
472 }
473
474 // Generate debug info.
475 if options.generate_debug_info {
476 opt_keys.push(CUjit_option::GenerateDebugInfo);
477 opt_vals.push(core::ptr::without_provenance_mut::<c_void>(1));
478 }
479
480 // Target from context.
481 if options.target_from_context {
482 opt_keys.push(CUjit_option::TargetFromCuContext);
483 opt_vals.push(core::ptr::without_provenance_mut::<c_void>(1));
484 }
485
486 let num_options = opt_keys.len() as u32;
487
488 let mut raw = CUmodule::default();
489 let result = crate::cuda_call!((api.cu_module_load_data_ex)(
490 &mut raw,
491 c_ptx.as_ptr().cast::<c_void>(),
492 num_options,
493 opt_keys.as_mut_ptr(),
494 opt_vals.as_mut_ptr(),
495 ));
496
497 // Extract log strings regardless of success or failure.
498 let log = JitLog {
499 info: buf_to_string(&info_buf),
500 error: buf_to_string(&error_buf),
501 };
502
503 // On failure, surface the full JIT diagnostic log in the error so
504 // callers can inspect exactly what went wrong.
505 if let Err(e) = result {
506 return Err(jit_failure_from_log(e, log));
507 }
508 Ok((
509 Self {
510 raw,
511 owner: crate::context::current_ctx_owner(),
512 },
513 log,
514 ))
515 }
516
517 /// Retrieves a kernel function by name from this module.
518 ///
519 /// The returned [`Function`] is a lightweight handle. The caller
520 /// must ensure that this `Module` outlives any `Function` handles
521 /// obtained from it.
522 ///
523 /// # Errors
524 ///
525 /// Returns [`CudaError::NotFound`] if no
526 /// function with the given name exists in the module, or another
527 /// [`CudaError`] on driver failure.
528 pub fn get_function(&self, name: &str) -> CudaResult<Function> {
529 let api = try_driver()?;
530 let c_name = CString::new(name).map_err(|_| CudaError::InvalidValue)?;
531 let mut raw = CUfunction::default();
532 crate::cuda_call!((api.cu_module_get_function)(
533 &mut raw,
534 self.raw,
535 c_name.as_ptr()
536 ))?;
537 Ok(Function { raw })
538 }
539
540 /// Returns the raw [`CUmodule`] handle.
541 ///
542 /// # Safety (caller)
543 ///
544 /// The caller must not unload or otherwise invalidate the handle
545 /// while this `Module` is still alive.
546 #[inline]
547 pub fn raw(&self) -> CUmodule {
548 self.raw
549 }
550}
551
552impl Drop for Module {
553 fn drop(&mut self) {
554 // Hold the registry lock across the unload, and skip it entirely if the
555 // owning context was already torn down (its `cuCtxDestroy` already
556 // unloaded this module — calling `cuModuleUnload` again would be a
557 // use-after-free).
558 let map = crate::context::lock_live_ctxs();
559 if !crate::context::owner_is_live(&map, self.owner) {
560 return;
561 }
562 if let Ok(api) = try_driver() {
563 let rc = unsafe { (api.cu_module_unload)(self.raw) };
564 if rc != 0 {
565 tracing::warn!(
566 cuda_error = rc,
567 module = ?self.raw,
568 "cuModuleUnload failed during drop"
569 );
570 }
571 }
572 }
573}
574
575// ---------------------------------------------------------------------------
576// Function
577// ---------------------------------------------------------------------------
578
579/// A kernel function handle within a loaded module.
580///
581/// Functions are lightweight handles (a single pointer) — the lifetime
582/// is tied to the parent [`Module`]. The caller is responsible for
583/// ensuring the `Module` outlives any `Function` handles obtained
584/// from it.
585///
586/// Occupancy query methods are provided in the [`crate::occupancy`]
587/// module via an `impl Function` block.
588#[derive(Debug, Clone, Copy)]
589pub struct Function {
590 /// Raw CUDA function handle.
591 raw: CUfunction,
592}
593
594impl Function {
595 /// Returns the raw [`CUfunction`] handle.
596 ///
597 /// This is needed for kernel launches and occupancy queries
598 /// at the FFI level.
599 #[inline]
600 pub fn raw(&self) -> CUfunction {
601 self.raw
602 }
603}
604
605// ---------------------------------------------------------------------------
606// Helpers
607// ---------------------------------------------------------------------------
608
609/// Converts a null-terminated C buffer to a Rust [`String`], trimming
610/// trailing null bytes and whitespace.
611fn buf_to_string(buf: &[u8]) -> String {
612 // Find the first null byte (or use the whole buffer).
613 let len = buf.iter().position(|&b| b == 0).unwrap_or(buf.len());
614 String::from_utf8_lossy(&buf[..len]).trim().to_string()
615}
616
617// ---------------------------------------------------------------------------
618// Tests
619// ---------------------------------------------------------------------------
620
621#[cfg(test)]
622mod tests {
623 use super::*;
624
625 // ── parse_ptxas_line ──────────────────────────────────────────────────────
626
627 #[test]
628 fn parse_blank_line_returns_none() {
629 assert!(parse_ptxas_line("").is_none());
630 assert!(parse_ptxas_line(" ").is_none());
631 }
632
633 #[test]
634 fn parse_non_ptxas_line_returns_none() {
635 // Lines not starting with "ptxas " are ignored.
636 assert!(parse_ptxas_line("nvcc error: something").is_none());
637 assert!(parse_ptxas_line(" error: foo").is_none());
638 }
639
640 #[test]
641 fn parse_standard_error_with_kernel_and_line() {
642 let line = "ptxas error : 'vec_add', line 42; error : Unknown instruction 'xyz.f32'";
643 let d = parse_ptxas_line(line).expect("should parse");
644 assert_eq!(d.severity, JitSeverity::Error);
645 assert_eq!(d.kernel.as_deref(), Some("vec_add"));
646 assert_eq!(d.line, Some(42));
647 assert!(
648 d.message.contains("Unknown instruction"),
649 "msg: {}",
650 d.message
651 );
652 }
653
654 #[test]
655 fn parse_warning_with_kernel_and_line() {
656 let line = "ptxas warning : 'my_kernel', line 7; warning : Double-precision instructions will be slow";
657 let d = parse_ptxas_line(line).expect("should parse");
658 assert_eq!(d.severity, JitSeverity::Warning);
659 assert_eq!(d.kernel.as_deref(), Some("my_kernel"));
660 assert_eq!(d.line, Some(7));
661 assert!(d.message.contains("Double-precision"), "msg: {}", d.message);
662 }
663
664 #[test]
665 fn parse_info_register_usage() {
666 let line =
667 "ptxas info : 'reduce_kernel' used 32 registers, 0 bytes smem, 0 bytes cmem[0]";
668 let d = parse_ptxas_line(line).expect("should parse");
669 assert_eq!(d.severity, JitSeverity::Info);
670 assert_eq!(d.kernel.as_deref(), Some("reduce_kernel"));
671 assert!(d.message.contains("32 registers"), "msg: {}", d.message);
672 assert!(d.line.is_none());
673 }
674
675 #[test]
676 fn parse_fatal_no_kernel() {
677 let line = "ptxas fatal : Unresolved extern function 'missing_func'";
678 let d = parse_ptxas_line(line).expect("should parse");
679 assert_eq!(d.severity, JitSeverity::Fatal);
680 assert!(d.kernel.is_none());
681 assert!(d.message.contains("Unresolved"), "msg: {}", d.message);
682 }
683
684 #[test]
685 fn parse_error_no_kernel_no_line() {
686 let line = "ptxas error : syntax error near token ';'";
687 let d = parse_ptxas_line(line).expect("should parse");
688 assert_eq!(d.severity, JitSeverity::Error);
689 assert!(d.kernel.is_none());
690 assert!(d.line.is_none());
691 assert!(d.message.contains("syntax error"), "msg: {}", d.message);
692 }
693
694 // ── JitLog helpers ────────────────────────────────────────────────────────
695
696 #[test]
697 fn jitlog_is_empty_for_default() {
698 let log = JitLog::default();
699 assert!(log.is_empty());
700 assert!(!log.has_errors());
701 }
702
703 #[test]
704 fn jitlog_has_errors_when_error_buf_nonempty() {
705 let log = JitLog {
706 info: String::new(),
707 error: "ptxas error : something went wrong".to_string(),
708 };
709 assert!(log.has_errors());
710 assert!(!log.is_empty());
711 }
712
713 #[test]
714 fn jitlog_parse_diagnostics_multiline() {
715 let log = JitLog {
716 error: concat!(
717 "ptxas error : 'k1', line 5; error : bad opcode\n",
718 "ptxas warning : 'k1', line 8; warning : slow path\n",
719 )
720 .to_string(),
721 info: "ptxas info : 'k1' used 8 registers, 0 bytes smem\n".to_string(),
722 };
723 let diags = log.parse_diagnostics();
724 assert_eq!(diags.len(), 3);
725 assert_eq!(diags[0].severity, JitSeverity::Error);
726 assert_eq!(diags[1].severity, JitSeverity::Warning);
727 assert_eq!(diags[2].severity, JitSeverity::Info);
728 }
729
730 #[test]
731 fn jitlog_errors_filter() {
732 let log = JitLog {
733 error: concat!(
734 "ptxas error : 'k', line 1; error : bad\n",
735 "ptxas warning : 'k', line 2; warning : slow\n",
736 )
737 .to_string(),
738 info: "ptxas info : 'k' used 4 registers\n".to_string(),
739 };
740 let errs = log.errors();
741 assert_eq!(errs.len(), 1);
742 assert_eq!(errs[0].severity, JitSeverity::Error);
743 }
744
745 #[test]
746 fn jitlog_warnings_filter() {
747 let log = JitLog {
748 error: "ptxas warning : 'k', line 3; warning : something slow\n".to_string(),
749 info: String::new(),
750 };
751 let warns = log.warnings();
752 assert_eq!(warns.len(), 1);
753 assert_eq!(warns[0].severity, JitSeverity::Warning);
754 assert_eq!(warns[0].line, Some(3));
755 }
756
757 // ── buf_to_string ─────────────────────────────────────────────────────────
758
759 #[test]
760 fn buf_to_string_null_terminated() {
761 let mut buf = b"hello\0\0\0".to_vec();
762 buf.extend_from_slice(&[0u8; 100]);
763 assert_eq!(buf_to_string(&buf), "hello");
764 }
765
766 #[test]
767 fn buf_to_string_empty() {
768 assert_eq!(buf_to_string(&[0u8; 10]), "");
769 }
770
771 #[test]
772 fn buf_to_string_no_null() {
773 let buf = b"abc".to_vec();
774 assert_eq!(buf_to_string(&buf), "abc");
775 }
776
777 // ── JitSeverity Display ───────────────────────────────────────────────────
778
779 #[test]
780 fn jit_severity_display() {
781 assert_eq!(JitSeverity::Fatal.to_string(), "fatal");
782 assert_eq!(JitSeverity::Error.to_string(), "error");
783 assert_eq!(JitSeverity::Warning.to_string(), "warning");
784 assert_eq!(JitSeverity::Info.to_string(), "info");
785 }
786}