kernel/print.rs
1// SPDX-License-Identifier: GPL-2.0
2
3//! Printing facilities.
4//!
5//! C header: [`include/linux/printk.h`](srctree/include/linux/printk.h)
6//!
7//! Reference: <https://docs.kernel.org/core-api/printk-basics.html>
8
9use crate::{
10 ffi::{c_char, c_void},
11 fmt,
12 prelude::*,
13 str::RawFormatter,
14};
15use safety_macro::safety;
16// Called from `vsprintf` with format specifier `%pA`.
17#[expect(clippy::missing_safety_doc)]
18#[export]
19unsafe extern "C" fn rust_fmt_argument(
20 buf: *mut c_char,
21 end: *mut c_char,
22 ptr: *const c_void,
23) -> *mut c_char {
24 use fmt::Write;
25 // SAFETY: The C contract guarantees that `buf` is valid if it's less than `end`.
26 let mut w = unsafe { RawFormatter::from_ptrs(buf.cast(), end.cast()) };
27 // SAFETY: TODO.
28 let _ = w.write_fmt(unsafe { *ptr.cast::<fmt::Arguments<'_>>() });
29 w.pos().cast()
30}
31
32/// Format strings.
33///
34/// Public but hidden since it should only be used from public macros.
35#[doc(hidden)]
36pub mod format_strings {
37 /// The length we copy from the `KERN_*` kernel prefixes.
38 const LENGTH_PREFIX: usize = 2;
39
40 /// The length of the fixed format strings.
41 pub const LENGTH: usize = 10;
42
43 /// Generates a fixed format string for the kernel's [`_printk`].
44 ///
45 /// The format string is always the same for a given level, i.e. for a
46 /// given `prefix`, which are the kernel's `KERN_*` constants.
47 ///
48 /// [`_printk`]: srctree/include/linux/printk.h
49 const fn generate(is_cont: bool, prefix: &[u8; 3]) -> [u8; LENGTH] {
50 // Ensure the `KERN_*` macros are what we expect.
51 assert!(prefix[0] == b'\x01');
52 if is_cont {
53 assert!(prefix[1] == b'c');
54 } else {
55 assert!(prefix[1] >= b'0' && prefix[1] <= b'7');
56 }
57 assert!(prefix[2] == b'\x00');
58
59 let suffix: &[u8; LENGTH - LENGTH_PREFIX] = if is_cont {
60 b"%pA\0\0\0\0\0"
61 } else {
62 b"%s: %pA\0"
63 };
64
65 [
66 prefix[0], prefix[1], suffix[0], suffix[1], suffix[2], suffix[3], suffix[4], suffix[5],
67 suffix[6], suffix[7],
68 ]
69 }
70
71 // Generate the format strings at compile-time.
72 //
73 // This avoids the compiler generating the contents on the fly in the stack.
74 //
75 // Furthermore, `static` instead of `const` is used to share the strings
76 // for all the kernel.
77 pub static EMERG: [u8; LENGTH] = generate(false, bindings::KERN_EMERG);
78 pub static ALERT: [u8; LENGTH] = generate(false, bindings::KERN_ALERT);
79 pub static CRIT: [u8; LENGTH] = generate(false, bindings::KERN_CRIT);
80 pub static ERR: [u8; LENGTH] = generate(false, bindings::KERN_ERR);
81 pub static WARNING: [u8; LENGTH] = generate(false, bindings::KERN_WARNING);
82 pub static NOTICE: [u8; LENGTH] = generate(false, bindings::KERN_NOTICE);
83 pub static INFO: [u8; LENGTH] = generate(false, bindings::KERN_INFO);
84 pub static DEBUG: [u8; LENGTH] = generate(false, bindings::KERN_DEBUG);
85 pub static CONT: [u8; LENGTH] = generate(true, bindings::KERN_CONT);
86}
87
88/// Prints a message via the kernel's [`_printk`].
89///
90/// Public but hidden since it should only be used from public macros.
91///
92/// # Safety
93///
94/// The format string must be one of the ones in [`format_strings`], and
95/// the module name must be null-terminated.
96///
97/// [`_printk`]: srctree/include/linux/_printk.h
98#[doc(hidden)]
99#[cfg_attr(not(CONFIG_PRINTK), allow(unused_variables))]
100#[safety{ValidInstance(format_string), ValidCStr(module_name)}]
101pub unsafe fn call_printk(
102 format_string: &[u8; format_strings::LENGTH],
103 module_name: &[u8],
104 args: fmt::Arguments<'_>,
105) {
106 // `_printk` does not seem to fail in any path.
107 #[cfg(CONFIG_PRINTK)]
108 // SAFETY: TODO.
109 unsafe {
110 bindings::_printk(
111 format_string.as_ptr(),
112 module_name.as_ptr(),
113 core::ptr::from_ref(&args).cast::<c_void>(),
114 );
115 }
116}
117
118/// Prints a message via the kernel's [`_printk`] for the `CONT` level.
119///
120/// Public but hidden since it should only be used from public macros.
121///
122/// [`_printk`]: srctree/include/linux/printk.h
123#[doc(hidden)]
124#[cfg_attr(not(CONFIG_PRINTK), allow(unused_variables))]
125pub fn call_printk_cont(args: fmt::Arguments<'_>) {
126 // `_printk` does not seem to fail in any path.
127 //
128 // SAFETY: The format string is fixed.
129 #[cfg(CONFIG_PRINTK)]
130 unsafe {
131 bindings::_printk(
132 format_strings::CONT.as_ptr(),
133 core::ptr::from_ref(&args).cast::<c_void>(),
134 );
135 }
136}
137
138/// Performs formatting and forwards the string to [`call_printk`].
139///
140/// Public but hidden since it should only be used from public macros.
141#[doc(hidden)]
142#[cfg(not(testlib))]
143#[macro_export]
144#[expect(clippy::crate_in_macro_def)]
145macro_rules! print_macro (
146 // The non-continuation cases (most of them, e.g. `INFO`).
147 ($format_string:path, false, $($arg:tt)+) => (
148 // To remain sound, `arg`s must be expanded outside the `unsafe` block.
149 // Typically one would use a `let` binding for that; however, `format_args!`
150 // takes borrows on the arguments, but does not extend the scope of temporaries.
151 // Therefore, a `match` expression is used to keep them around, since
152 // the scrutinee is kept until the end of the `match`.
153 match $crate::prelude::fmt!($($arg)+) {
154 // SAFETY: This hidden macro should only be called by the documented
155 // printing macros which ensure the format string is one of the fixed
156 // ones. All `__LOG_PREFIX`s are null-terminated as they are generated
157 // by the `module!` proc macro or fixed values defined in a kernel
158 // crate.
159 args => unsafe {
160 $crate::print::call_printk(
161 &$format_string,
162 crate::__LOG_PREFIX,
163 args,
164 );
165 }
166 }
167 );
168
169 // The `CONT` case.
170 ($format_string:path, true, $($arg:tt)+) => (
171 $crate::print::call_printk_cont(
172 $crate::prelude::fmt!($($arg)+),
173 );
174 );
175);
176
177/// Stub for doctests
178#[cfg(testlib)]
179#[macro_export]
180macro_rules! print_macro (
181 ($format_string:path, $e:expr, $($arg:tt)+) => (
182 ()
183 );
184);
185
186// We could use a macro to generate these macros. However, doing so ends
187// up being a bit ugly: it requires the dollar token trick to escape `$` as
188// well as playing with the `doc` attribute. Furthermore, they cannot be easily
189// imported in the prelude due to [1]. So, for the moment, we just write them
190// manually, like in the C side; while keeping most of the logic in another
191// macro, i.e. [`print_macro`].
192//
193// [1]: https://github.com/rust-lang/rust/issues/52234
194
195/// Prints an emergency-level message (level 0).
196///
197/// Use this level if the system is unusable.
198///
199/// Equivalent to the kernel's [`pr_emerg`] macro.
200///
201/// Mimics the interface of [`std::print!`]. See [`core::fmt`] and
202/// [`std::format!`] for information about the formatting syntax.
203///
204/// [`pr_emerg`]: https://docs.kernel.org/core-api/printk-basics.html#c.pr_emerg
205/// [`std::print!`]: https://doc.rust-lang.org/std/macro.print.html
206/// [`std::format!`]: https://doc.rust-lang.org/std/macro.format.html
207///
208/// # Examples
209///
210/// ```
211/// pr_emerg!("hello {}\n", "there");
212/// ```
213#[macro_export]
214macro_rules! pr_emerg (
215 ($($arg:tt)*) => (
216 $crate::print_macro!($crate::print::format_strings::EMERG, false, $($arg)*)
217 )
218);
219
220/// Prints an alert-level message (level 1).
221///
222/// Use this level if action must be taken immediately.
223///
224/// Equivalent to the kernel's [`pr_alert`] macro.
225///
226/// Mimics the interface of [`std::print!`]. See [`core::fmt`] and
227/// [`std::format!`] for information about the formatting syntax.
228///
229/// [`pr_alert`]: https://docs.kernel.org/core-api/printk-basics.html#c.pr_alert
230/// [`std::print!`]: https://doc.rust-lang.org/std/macro.print.html
231/// [`std::format!`]: https://doc.rust-lang.org/std/macro.format.html
232///
233/// # Examples
234///
235/// ```
236/// pr_alert!("hello {}\n", "there");
237/// ```
238#[macro_export]
239macro_rules! pr_alert (
240 ($($arg:tt)*) => (
241 $crate::print_macro!($crate::print::format_strings::ALERT, false, $($arg)*)
242 )
243);
244
245/// Prints a critical-level message (level 2).
246///
247/// Use this level for critical conditions.
248///
249/// Equivalent to the kernel's [`pr_crit`] macro.
250///
251/// Mimics the interface of [`std::print!`]. See [`core::fmt`] and
252/// [`std::format!`] for information about the formatting syntax.
253///
254/// [`pr_crit`]: https://docs.kernel.org/core-api/printk-basics.html#c.pr_crit
255/// [`std::print!`]: https://doc.rust-lang.org/std/macro.print.html
256/// [`std::format!`]: https://doc.rust-lang.org/std/macro.format.html
257///
258/// # Examples
259///
260/// ```
261/// pr_crit!("hello {}\n", "there");
262/// ```
263#[macro_export]
264macro_rules! pr_crit (
265 ($($arg:tt)*) => (
266 $crate::print_macro!($crate::print::format_strings::CRIT, false, $($arg)*)
267 )
268);
269
270/// Prints an error-level message (level 3).
271///
272/// Use this level for error conditions.
273///
274/// Equivalent to the kernel's [`pr_err`] macro.
275///
276/// Mimics the interface of [`std::print!`]. See [`core::fmt`] and
277/// [`std::format!`] for information about the formatting syntax.
278///
279/// [`pr_err`]: https://docs.kernel.org/core-api/printk-basics.html#c.pr_err
280/// [`std::print!`]: https://doc.rust-lang.org/std/macro.print.html
281/// [`std::format!`]: https://doc.rust-lang.org/std/macro.format.html
282///
283/// # Examples
284///
285/// ```
286/// pr_err!("hello {}\n", "there");
287/// ```
288#[macro_export]
289macro_rules! pr_err (
290 ($($arg:tt)*) => (
291 $crate::print_macro!($crate::print::format_strings::ERR, false, $($arg)*)
292 )
293);
294
295/// Prints a warning-level message (level 4).
296///
297/// Use this level for warning conditions.
298///
299/// Equivalent to the kernel's [`pr_warn`] macro.
300///
301/// Mimics the interface of [`std::print!`]. See [`core::fmt`] and
302/// [`std::format!`] for information about the formatting syntax.
303///
304/// [`pr_warn`]: https://docs.kernel.org/core-api/printk-basics.html#c.pr_warn
305/// [`std::print!`]: https://doc.rust-lang.org/std/macro.print.html
306/// [`std::format!`]: https://doc.rust-lang.org/std/macro.format.html
307///
308/// # Examples
309///
310/// ```
311/// pr_warn!("hello {}\n", "there");
312/// ```
313#[macro_export]
314macro_rules! pr_warn (
315 ($($arg:tt)*) => (
316 $crate::print_macro!($crate::print::format_strings::WARNING, false, $($arg)*)
317 )
318);
319
320/// Prints a notice-level message (level 5).
321///
322/// Use this level for normal but significant conditions.
323///
324/// Equivalent to the kernel's [`pr_notice`] macro.
325///
326/// Mimics the interface of [`std::print!`]. See [`core::fmt`] and
327/// [`std::format!`] for information about the formatting syntax.
328///
329/// [`pr_notice`]: https://docs.kernel.org/core-api/printk-basics.html#c.pr_notice
330/// [`std::print!`]: https://doc.rust-lang.org/std/macro.print.html
331/// [`std::format!`]: https://doc.rust-lang.org/std/macro.format.html
332///
333/// # Examples
334///
335/// ```
336/// pr_notice!("hello {}\n", "there");
337/// ```
338#[macro_export]
339macro_rules! pr_notice (
340 ($($arg:tt)*) => (
341 $crate::print_macro!($crate::print::format_strings::NOTICE, false, $($arg)*)
342 )
343);
344
345/// Prints an info-level message (level 6).
346///
347/// Use this level for informational messages.
348///
349/// Equivalent to the kernel's [`pr_info`] macro.
350///
351/// Mimics the interface of [`std::print!`]. See [`core::fmt`] and
352/// [`std::format!`] for information about the formatting syntax.
353///
354/// [`pr_info`]: https://docs.kernel.org/core-api/printk-basics.html#c.pr_info
355/// [`std::print!`]: https://doc.rust-lang.org/std/macro.print.html
356/// [`std::format!`]: https://doc.rust-lang.org/std/macro.format.html
357///
358/// # Examples
359///
360/// ```
361/// pr_info!("hello {}\n", "there");
362/// ```
363#[macro_export]
364#[doc(alias = "print")]
365macro_rules! pr_info (
366 ($($arg:tt)*) => (
367 $crate::print_macro!($crate::print::format_strings::INFO, false, $($arg)*)
368 )
369);
370
371/// Prints a debug-level message (level 7).
372///
373/// Use this level for debug messages.
374///
375/// Equivalent to the kernel's [`pr_debug`] macro, except that it doesn't support dynamic debug
376/// yet.
377///
378/// Mimics the interface of [`std::print!`]. See [`core::fmt`] and
379/// [`std::format!`] for information about the formatting syntax.
380///
381/// [`pr_debug`]: https://docs.kernel.org/core-api/printk-basics.html#c.pr_debug
382/// [`std::print!`]: https://doc.rust-lang.org/std/macro.print.html
383/// [`std::format!`]: https://doc.rust-lang.org/std/macro.format.html
384///
385/// # Examples
386///
387/// ```
388/// pr_debug!("hello {}\n", "there");
389/// ```
390#[macro_export]
391#[doc(alias = "print")]
392macro_rules! pr_debug (
393 ($($arg:tt)*) => (
394 if cfg!(debug_assertions) {
395 $crate::print_macro!($crate::print::format_strings::DEBUG, false, $($arg)*)
396 }
397 )
398);
399
400/// Continues a previous log message in the same line.
401///
402/// Use only when continuing a previous `pr_*!` macro (e.g. [`pr_info!`]).
403///
404/// Equivalent to the kernel's [`pr_cont`] macro.
405///
406/// Mimics the interface of [`std::print!`]. See [`core::fmt`] and
407/// [`std::format!`] for information about the formatting syntax.
408///
409/// [`pr_info!`]: crate::pr_info!
410/// [`pr_cont`]: https://docs.kernel.org/core-api/printk-basics.html#c.pr_cont
411/// [`std::print!`]: https://doc.rust-lang.org/std/macro.print.html
412/// [`std::format!`]: https://doc.rust-lang.org/std/macro.format.html
413///
414/// # Examples
415///
416/// ```
417/// # use kernel::pr_cont;
418/// pr_info!("hello");
419/// pr_cont!(" {}\n", "there");
420/// ```
421#[macro_export]
422macro_rules! pr_cont (
423 ($($arg:tt)*) => (
424 $crate::print_macro!($crate::print::format_strings::CONT, true, $($arg)*)
425 )
426);