xref: /qemu/rust/qemu-api/src/log.rs (revision ab81002252af101068fca94bc82b31ba59ff154b)
1 // Copyright 2025 Bernhard Beschow <shentey@gmail.com>
2 // SPDX-License-Identifier: GPL-2.0-or-later
3 
4 //! Bindings for QEMU's logging infrastructure
5 
6 #[repr(u32)]
7 /// Represents specific error categories within QEMU's logging system.
8 ///
9 /// The `Log` enum provides a Rust abstraction for logging errors, corresponding
10 /// to a subset of the error categories defined in the C implementation.
11 pub enum Log {
12     /// Log invalid access caused by the guest.
13     /// Corresponds to `LOG_GUEST_ERROR` in the C implementation.
14     GuestError = crate::bindings::LOG_GUEST_ERROR,
15 
16     /// Log guest access of unimplemented functionality.
17     /// Corresponds to `LOG_UNIMP` in the C implementation.
18     Unimp = crate::bindings::LOG_UNIMP,
19 }
20 
21 /// A macro to log messages conditionally based on a provided mask.
22 ///
23 /// The `log_mask_ln` macro checks whether the given mask matches the current
24 /// log level and, if so, formats and logs the message. It is the Rust
25 /// counterpart of the `qemu_log_mask()` macro in the C implementation.
26 ///
27 /// # Parameters
28 ///
29 /// - `$mask`: A log level mask. This should be a variant of the `Log` enum.
30 /// - `$fmt`: A format string following the syntax and rules of the `format!`
31 ///   macro. It specifies the structure of the log message.
32 /// - `$args`: Optional arguments to be interpolated into the format string.
33 ///
34 /// # Example
35 ///
36 /// ```
37 /// use qemu_api::{log::Log, log_mask_ln};
38 ///
39 /// let error_address = 0xbad;
40 /// log_mask_ln!(Log::GuestError, "Address 0x{error_address:x} out of range");
41 /// ```
42 ///
43 /// It is also possible to use printf-style formatting, as well as having a
44 /// trailing `,`:
45 ///
46 /// ```
47 /// use qemu_api::{log::Log, log_mask_ln};
48 ///
49 /// let error_address = 0xbad;
50 /// log_mask_ln!(
51 ///     Log::GuestError,
52 ///     "Address 0x{:x} out of range",
53 ///     error_address,
54 /// );
55 /// ```
56 #[macro_export]
57 macro_rules! log_mask_ln {
58     ($mask:expr, $fmt:tt $($args:tt)*) => {{
59         // Type assertion to enforce type `Log` for $mask
60         let _: Log = $mask;
61 
62         if unsafe {
63             (::qemu_api::bindings::qemu_loglevel & ($mask as std::os::raw::c_int)) != 0
64         } {
65             let formatted_string = format!("{}\n", format_args!($fmt $($args)*));
66             let c_string = std::ffi::CString::new(formatted_string).unwrap();
67 
68             unsafe {
69                 ::qemu_api::bindings::qemu_log(c_string.as_ptr());
70             }
71         }
72     }};
73 }
74