xref: /openbmc/qemu/rust/qemu-api/src/log.rs (revision b92b39af4219df4250f121f64d215506909c7404)
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 use std::{
7     io::{self, Write},
8     ptr::NonNull,
9 };
10 
11 use crate::{bindings, errno};
12 
13 #[repr(u32)]
14 /// Represents specific error categories within QEMU's logging system.
15 ///
16 /// The `Log` enum provides a Rust abstraction for logging errors, corresponding
17 /// to a subset of the error categories defined in the C implementation.
18 pub enum Log {
19     /// Log invalid access caused by the guest.
20     /// Corresponds to `LOG_GUEST_ERROR` in the C implementation.
21     GuestError = bindings::LOG_GUEST_ERROR,
22 
23     /// Log guest access of unimplemented functionality.
24     /// Corresponds to `LOG_UNIMP` in the C implementation.
25     Unimp = bindings::LOG_UNIMP,
26 }
27 
28 /// A RAII guard for QEMU's logging infrastructure.  Creating the guard
29 /// locks the log file, and dropping it (letting it go out of scope) unlocks
30 /// the file.
31 ///
32 /// As long as the guard lives, it can be written to using [`std::io::Write`].
33 ///
34 /// The locking is recursive, therefore owning a guard does not prevent
35 /// using [`log_mask_ln!()`](crate::log_mask_ln).
36 pub struct LogGuard(NonNull<bindings::FILE>);
37 
38 impl LogGuard {
39     /// Return a RAII guard that writes to QEMU's logging infrastructure.
40     /// The log file is locked while the guard exists, ensuring that there
41     /// is no tearing of the messages.
42     ///
43     /// Return `None` if the log file is closed and could not be opened.
44     /// Do *not* use `unwrap()` on the result; failure can be handled simply
45     /// by not logging anything.
46     ///
47     /// # Examples
48     ///
49     /// ```
50     /// # use qemu_api::log::LogGuard;
51     /// # use std::io::Write;
52     /// if let Some(mut log) = LogGuard::new() {
53     ///     writeln!(log, "test");
54     /// }
55     /// ```
new() -> Option<Self>56     pub fn new() -> Option<Self> {
57         let f = unsafe { bindings::qemu_log_trylock() }.cast();
58         NonNull::new(f).map(Self)
59     }
60 
61     /// Writes a formatted string into the log, returning any error encountered.
62     ///
63     /// This method is primarily used by the
64     /// [`log_mask_ln!()`](crate::log_mask_ln) macro, and it is rare for it
65     /// to be called explicitly.  It is public because it is the only way to
66     /// examine the error, which `log_mask_ln!()` ignores
67     ///
68     /// Unlike `log_mask_ln!()`, it does *not* append a newline at the end.
log_fmt(args: std::fmt::Arguments) -> io::Result<()>69     pub fn log_fmt(args: std::fmt::Arguments) -> io::Result<()> {
70         if let Some(mut log) = Self::new() {
71             log.write_fmt(args)?;
72         }
73         Ok(())
74     }
75 }
76 
77 impl Write for LogGuard {
write(&mut self, bytes: &[u8]) -> io::Result<usize>78     fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
79         let ret = unsafe {
80             bindings::rust_fwrite(bytes.as_ptr().cast(), 1, bytes.len(), self.0.as_ptr())
81         };
82         errno::into_io_result(ret)
83     }
84 
flush(&mut self) -> io::Result<()>85     fn flush(&mut self) -> io::Result<()> {
86         // Do nothing, dropping the guard takes care of flushing
87         Ok(())
88     }
89 }
90 
91 impl Drop for LogGuard {
drop(&mut self)92     fn drop(&mut self) {
93         unsafe {
94             bindings::qemu_log_unlock(self.0.as_ptr());
95         }
96     }
97 }
98 
99 /// A macro to log messages conditionally based on a provided mask.
100 ///
101 /// The `log_mask_ln` macro checks whether the given mask matches the current
102 /// log level and, if so, formats and logs the message. It is the Rust
103 /// counterpart of the `qemu_log_mask()` macro in the C implementation.
104 ///
105 /// Errors from writing to the log are ignored.
106 ///
107 /// # Parameters
108 ///
109 /// - `$mask`: A log level mask. This should be a variant of the `Log` enum.
110 /// - `$fmt`: A format string following the syntax and rules of the `format!`
111 ///   macro. It specifies the structure of the log message.
112 /// - `$args`: Optional arguments to be interpolated into the format string.
113 ///
114 /// # Example
115 ///
116 /// ```
117 /// use qemu_api::{log::Log, log_mask_ln};
118 ///
119 /// let error_address = 0xbad;
120 /// log_mask_ln!(Log::GuestError, "Address 0x{error_address:x} out of range");
121 /// ```
122 ///
123 /// It is also possible to use printf-style formatting, as well as having a
124 /// trailing `,`:
125 ///
126 /// ```
127 /// use qemu_api::{log::Log, log_mask_ln};
128 ///
129 /// let error_address = 0xbad;
130 /// log_mask_ln!(
131 ///     Log::GuestError,
132 ///     "Address 0x{:x} out of range",
133 ///     error_address,
134 /// );
135 /// ```
136 #[macro_export]
137 macro_rules! log_mask_ln {
138     ($mask:expr, $fmt:tt $($args:tt)*) => {{
139         // Type assertion to enforce type `Log` for $mask
140         let _: Log = $mask;
141 
142         if unsafe {
143             (::qemu_api::bindings::qemu_loglevel & ($mask as std::os::raw::c_int)) != 0
144         } {
145             _ = ::qemu_api::log::LogGuard::log_fmt(
146                 format_args!("{}\n", format_args!($fmt $($args)*)));
147         }
148     }};
149 }
150