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