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 prelude::*,
12 str::RawFormatter,
13};
14use core::fmt;
15
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 as *const 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))]
100pub unsafe fn call_printk(
101 format_string: &[u8; format_strings::LENGTH],
102 module_name: &[u8],
103 args: fmt::Arguments<'_>,
104) {
105 // `_printk` does not seem to fail in any path.
106 #[cfg(CONFIG_PRINTK)]
107 // SAFETY: TODO.
108 unsafe {
109 bindings::_printk(
110 format_string.as_ptr(),
111 module_name.as_ptr(),
112 &args as *const _ as *const c_void,
113 );
114 }
115}
116
117/// Prints a message via the kernel's [`_printk`] for the `CONT` level.
118///
119/// Public but hidden since it should only be used from public macros.
120///
121/// [`_printk`]: srctree/include/linux/printk.h
122#[doc(hidden)]
123#[cfg_attr(not(CONFIG_PRINTK), allow(unused_variables))]
124pub fn call_printk_cont(args: fmt::Arguments<'_>) {
125 // `_printk` does not seem to fail in any path.
126 //
127 // SAFETY: The format string is fixed.
128 #[cfg(CONFIG_PRINTK)]
129 unsafe {
130 bindings::_printk(
131 format_strings::CONT.as_ptr(),
132 &args as *const _ as *const c_void,
133 );
134 }
135}
136
137/// Performs formatting and forwards the string to [`call_printk`].
138///
139/// Public but hidden since it should only be used from public macros.
140#[doc(hidden)]
141#[cfg(not(testlib))]
142#[macro_export]
143#[expect(clippy::crate_in_macro_def)]
144macro_rules! print_macro (
145 // The non-continuation cases (most of them, e.g. `INFO`).
146 ($format_string:path, false, $($arg:tt)+) => (
147 // To remain sound, `arg`s must be expanded outside the `unsafe` block.
148 // Typically one would use a `let` binding for that; however, `format_args!`
149 // takes borrows on the arguments, but does not extend the scope of temporaries.
150 // Therefore, a `match` expression is used to keep them around, since
151 // the scrutinee is kept until the end of the `match`.
152 match format_args!($($arg)+) {
153 // SAFETY: This hidden macro should only be called by the documented
154 // printing macros which ensure the format string is one of the fixed
155 // ones. All `__LOG_PREFIX`s are null-terminated as they are generated
156 // by the `module!` proc macro or fixed values defined in a kernel
157 // crate.
158 args => unsafe {
159 $crate::print::call_printk(
160 &$format_string,
161 crate::__LOG_PREFIX,
162 args,
163 );
164 }
165 }
166 );
167
168 // The `CONT` case.
169 ($format_string:path, true, $($arg:tt)+) => (
170 $crate::print::call_printk_cont(
171 format_args!($($arg)+),
172 );
173 );
174);
175
176/// Stub for doctests
177#[cfg(testlib)]
178#[macro_export]
179macro_rules! print_macro (
180 ($format_string:path, $e:expr, $($arg:tt)+) => (
181 ()
182 );
183);
184
185// We could use a macro to generate these macros. However, doing so ends
186// up being a bit ugly: it requires the dollar token trick to escape `$` as
187// well as playing with the `doc` attribute. Furthermore, they cannot be easily
188// imported in the prelude due to [1]. So, for the moment, we just write them
189// manually, like in the C side; while keeping most of the logic in another
190// macro, i.e. [`print_macro`].
191//
192// [1]: https://github.com/rust-lang/rust/issues/52234
193
194/// Prints an emergency-level message (level 0).
195///
196/// Use this level if the system is unusable.
197///
198/// Equivalent to the kernel's [`pr_emerg`] macro.
199///
200/// Mimics the interface of [`std::print!`]. See [`core::fmt`] and
201/// [`std::format!`] for information about the formatting syntax.
202///
203/// [`pr_emerg`]: https://docs.kernel.org/core-api/printk-basics.html#c.pr_emerg
204/// [`std::print!`]: https://doc.rust-lang.org/std/macro.print.html
205/// [`std::format!`]: https://doc.rust-lang.org/std/macro.format.html
206///
207/// # Examples
208///
209/// ```
210/// pr_emerg!("hello {}\n", "there");
211/// ```
212#[macro_export]
213macro_rules! pr_emerg (
214 ($($arg:tt)*) => (
215 $crate::print_macro!($crate::print::format_strings::EMERG, false, $($arg)*)
216 )
217);
218
219/// Prints an alert-level message (level 1).
220///
221/// Use this level if action must be taken immediately.
222///
223/// Equivalent to the kernel's [`pr_alert`] macro.
224///
225/// Mimics the interface of [`std::print!`]. See [`core::fmt`] and
226/// [`std::format!`] for information about the formatting syntax.
227///
228/// [`pr_alert`]: https://docs.kernel.org/core-api/printk-basics.html#c.pr_alert
229/// [`std::print!`]: https://doc.rust-lang.org/std/macro.print.html
230/// [`std::format!`]: https://doc.rust-lang.org/std/macro.format.html
231///
232/// # Examples
233///
234/// ```
235/// pr_alert!("hello {}\n", "there");
236/// ```
237#[macro_export]
238macro_rules! pr_alert (
239 ($($arg:tt)*) => (
240 $crate::print_macro!($crate::print::format_strings::ALERT, false, $($arg)*)
241 )
242);
243
244/// Prints a critical-level message (level 2).
245///
246/// Use this level for critical conditions.
247///
248/// Equivalent to the kernel's [`pr_crit`] macro.
249///
250/// Mimics the interface of [`std::print!`]. See [`core::fmt`] and
251/// [`std::format!`] for information about the formatting syntax.
252///
253/// [`pr_crit`]: https://docs.kernel.org/core-api/printk-basics.html#c.pr_crit
254/// [`std::print!`]: https://doc.rust-lang.org/std/macro.print.html
255/// [`std::format!`]: https://doc.rust-lang.org/std/macro.format.html
256///
257/// # Examples
258///
259/// ```
260/// pr_crit!("hello {}\n", "there");
261/// ```
262#[macro_export]
263macro_rules! pr_crit (
264 ($($arg:tt)*) => (
265 $crate::print_macro!($crate::print::format_strings::CRIT, false, $($arg)*)
266 )
267);
268
269/// Prints an error-level message (level 3).
270///
271/// Use this level for error conditions.
272///
273/// Equivalent to the kernel's [`pr_err`] macro.
274///
275/// Mimics the interface of [`std::print!`]. See [`core::fmt`] and
276/// [`std::format!`] for information about the formatting syntax.
277///
278/// [`pr_err`]: https://docs.kernel.org/core-api/printk-basics.html#c.pr_err
279/// [`std::print!`]: https://doc.rust-lang.org/std/macro.print.html
280/// [`std::format!`]: https://doc.rust-lang.org/std/macro.format.html
281///
282/// # Examples
283///
284/// ```
285/// pr_err!("hello {}\n", "there");
286/// ```
287#[macro_export]
288macro_rules! pr_err (
289 ($($arg:tt)*) => (
290 $crate::print_macro!($crate::print::format_strings::ERR, false, $($arg)*)
291 )
292);
293
294/// Prints a warning-level message (level 4).
295///
296/// Use this level for warning conditions.
297///
298/// Equivalent to the kernel's [`pr_warn`] macro.
299///
300/// Mimics the interface of [`std::print!`]. See [`core::fmt`] and
301/// [`std::format!`] for information about the formatting syntax.
302///
303/// [`pr_warn`]: https://docs.kernel.org/core-api/printk-basics.html#c.pr_warn
304/// [`std::print!`]: https://doc.rust-lang.org/std/macro.print.html
305/// [`std::format!`]: https://doc.rust-lang.org/std/macro.format.html
306///
307/// # Examples
308///
309/// ```
310/// pr_warn!("hello {}\n", "there");
311/// ```
312#[macro_export]
313macro_rules! pr_warn (
314 ($($arg:tt)*) => (
315 $crate::print_macro!($crate::print::format_strings::WARNING, false, $($arg)*)
316 )
317);
318
319/// Prints a notice-level message (level 5).
320///
321/// Use this level for normal but significant conditions.
322///
323/// Equivalent to the kernel's [`pr_notice`] macro.
324///
325/// Mimics the interface of [`std::print!`]. See [`core::fmt`] and
326/// [`std::format!`] for information about the formatting syntax.
327///
328/// [`pr_notice`]: https://docs.kernel.org/core-api/printk-basics.html#c.pr_notice
329/// [`std::print!`]: https://doc.rust-lang.org/std/macro.print.html
330/// [`std::format!`]: https://doc.rust-lang.org/std/macro.format.html
331///
332/// # Examples
333///
334/// ```
335/// pr_notice!("hello {}\n", "there");
336/// ```
337#[macro_export]
338macro_rules! pr_notice (
339 ($($arg:tt)*) => (
340 $crate::print_macro!($crate::print::format_strings::NOTICE, false, $($arg)*)
341 )
342);
343
344/// Prints an info-level message (level 6).
345///
346/// Use this level for informational messages.
347///
348/// Equivalent to the kernel's [`pr_info`] macro.
349///
350/// Mimics the interface of [`std::print!`]. See [`core::fmt`] and
351/// [`std::format!`] for information about the formatting syntax.
352///
353/// [`pr_info`]: https://docs.kernel.org/core-api/printk-basics.html#c.pr_info
354/// [`std::print!`]: https://doc.rust-lang.org/std/macro.print.html
355/// [`std::format!`]: https://doc.rust-lang.org/std/macro.format.html
356///
357/// # Examples
358///
359/// ```
360/// pr_info!("hello {}\n", "there");
361/// ```
362#[macro_export]
363#[doc(alias = "print")]
364macro_rules! pr_info (
365 ($($arg:tt)*) => (
366 $crate::print_macro!($crate::print::format_strings::INFO, false, $($arg)*)
367 )
368);
369
370/// Prints a debug-level message (level 7).
371///
372/// Use this level for debug messages.
373///
374/// Equivalent to the kernel's [`pr_debug`] macro, except that it doesn't support dynamic debug
375/// yet.
376///
377/// Mimics the interface of [`std::print!`]. See [`core::fmt`] and
378/// [`std::format!`] for information about the formatting syntax.
379///
380/// [`pr_debug`]: https://docs.kernel.org/core-api/printk-basics.html#c.pr_debug
381/// [`std::print!`]: https://doc.rust-lang.org/std/macro.print.html
382/// [`std::format!`]: https://doc.rust-lang.org/std/macro.format.html
383///
384/// # Examples
385///
386/// ```
387/// pr_debug!("hello {}\n", "there");
388/// ```
389#[macro_export]
390#[doc(alias = "print")]
391macro_rules! pr_debug (
392 ($($arg:tt)*) => (
393 if cfg!(debug_assertions) {
394 $crate::print_macro!($crate::print::format_strings::DEBUG, false, $($arg)*)
395 }
396 )
397);
398
399/// Continues a previous log message in the same line.
400///
401/// Use only when continuing a previous `pr_*!` macro (e.g. [`pr_info!`]).
402///
403/// Equivalent to the kernel's [`pr_cont`] macro.
404///
405/// Mimics the interface of [`std::print!`]. See [`core::fmt`] and
406/// [`std::format!`] for information about the formatting syntax.
407///
408/// [`pr_info!`]: crate::pr_info!
409/// [`pr_cont`]: https://docs.kernel.org/core-api/printk-basics.html#c.pr_cont
410/// [`std::print!`]: https://doc.rust-lang.org/std/macro.print.html
411/// [`std::format!`]: https://doc.rust-lang.org/std/macro.format.html
412///
413/// # Examples
414///
415/// ```
416/// # use kernel::pr_cont;
417/// pr_info!("hello");
418/// pr_cont!(" {}\n", "there");
419/// ```
420#[macro_export]
421macro_rules! pr_cont (
422 ($($arg:tt)*) => (
423 $crate::print_macro!($crate::print::format_strings::CONT, true, $($arg)*)
424 )
425);