GNU Linux-libre 6.1.24-gnu
[releases.git] / rust / kernel / print.rs
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 INFO: [u8; LENGTH] = generate(false, bindings::KERN_INFO);
78 }
79
80 /// Prints a message via the kernel's [`_printk`].
81 ///
82 /// Public but hidden since it should only be used from public macros.
83 ///
84 /// # Safety
85 ///
86 /// The format string must be one of the ones in [`format_strings`], and
87 /// the module name must be null-terminated.
88 ///
89 /// [`_printk`]: ../../../../include/linux/_printk.h
90 #[doc(hidden)]
91 #[cfg_attr(not(CONFIG_PRINTK), allow(unused_variables))]
92 pub unsafe fn call_printk(
93     format_string: &[u8; format_strings::LENGTH],
94     module_name: &[u8],
95     args: fmt::Arguments<'_>,
96 ) {
97     // `_printk` does not seem to fail in any path.
98     #[cfg(CONFIG_PRINTK)]
99     unsafe {
100         bindings::_printk(
101             format_string.as_ptr() as _,
102             module_name.as_ptr(),
103             &args as *const _ as *const c_void,
104         );
105     }
106 }
107
108 /// Performs formatting and forwards the string to [`call_printk`].
109 ///
110 /// Public but hidden since it should only be used from public macros.
111 #[doc(hidden)]
112 #[cfg(not(testlib))]
113 #[macro_export]
114 #[allow(clippy::crate_in_macro_def)]
115 macro_rules! print_macro (
116     // The non-continuation cases (most of them, e.g. `INFO`).
117     ($format_string:path, $($arg:tt)+) => (
118         // To remain sound, `arg`s must be expanded outside the `unsafe` block.
119         // Typically one would use a `let` binding for that; however, `format_args!`
120         // takes borrows on the arguments, but does not extend the scope of temporaries.
121         // Therefore, a `match` expression is used to keep them around, since
122         // the scrutinee is kept until the end of the `match`.
123         match format_args!($($arg)+) {
124             // SAFETY: This hidden macro should only be called by the documented
125             // printing macros which ensure the format string is one of the fixed
126             // ones. All `__LOG_PREFIX`s are null-terminated as they are generated
127             // by the `module!` proc macro or fixed values defined in a kernel
128             // crate.
129             args => unsafe {
130                 $crate::print::call_printk(
131                     &$format_string,
132                     crate::__LOG_PREFIX,
133                     args,
134                 );
135             }
136         }
137     );
138 );
139
140 /// Stub for doctests
141 #[cfg(testlib)]
142 #[macro_export]
143 macro_rules! print_macro (
144     ($format_string:path, $e:expr, $($arg:tt)+) => (
145         ()
146     );
147 );
148
149 // We could use a macro to generate these macros. However, doing so ends
150 // up being a bit ugly: it requires the dollar token trick to escape `$` as
151 // well as playing with the `doc` attribute. Furthermore, they cannot be easily
152 // imported in the prelude due to [1]. So, for the moment, we just write them
153 // manually, like in the C side; while keeping most of the logic in another
154 // macro, i.e. [`print_macro`].
155 //
156 // [1]: https://github.com/rust-lang/rust/issues/52234
157
158 /// Prints an emergency-level message (level 0).
159 ///
160 /// Use this level if the system is unusable.
161 ///
162 /// Equivalent to the kernel's [`pr_emerg`] macro.
163 ///
164 /// Mimics the interface of [`std::print!`]. See [`core::fmt`] and
165 /// `alloc::format!` for information about the formatting syntax.
166 ///
167 /// [`pr_emerg`]: https://www.kernel.org/doc/html/latest/core-api/printk-basics.html#c.pr_emerg
168 /// [`std::print!`]: https://doc.rust-lang.org/std/macro.print.html
169 ///
170 /// # Examples
171 ///
172 /// ```
173 /// pr_emerg!("hello {}\n", "there");
174 /// ```
175 #[macro_export]
176 macro_rules! pr_emerg (
177     ($($arg:tt)*) => (
178         $crate::print_macro!($crate::print::format_strings::EMERG, $($arg)*)
179     )
180 );
181
182 /// Prints an info-level message (level 6).
183 ///
184 /// Use this level for informational messages.
185 ///
186 /// Equivalent to the kernel's [`pr_info`] macro.
187 ///
188 /// Mimics the interface of [`std::print!`]. See [`core::fmt`] and
189 /// `alloc::format!` for information about the formatting syntax.
190 ///
191 /// [`pr_info`]: https://www.kernel.org/doc/html/latest/core-api/printk-basics.html#c.pr_info
192 /// [`std::print!`]: https://doc.rust-lang.org/std/macro.print.html
193 ///
194 /// # Examples
195 ///
196 /// ```
197 /// pr_info!("hello {}\n", "there");
198 /// ```
199 #[macro_export]
200 #[doc(alias = "print")]
201 macro_rules! pr_info (
202     ($($arg:tt)*) => (
203         $crate::print_macro!($crate::print::format_strings::INFO, $($arg)*)
204     )
205 );