GNU Linux-libre 6.1.86-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 extern "C" fn rust_fmt_argument(
22     buf: *mut c_char,
23     end: *mut c_char,
24     ptr: *const c_void,
25 ) -> *mut c_char {
26     use fmt::Write;
27     // SAFETY: The C contract guarantees that `buf` is valid if it's less than `end`.
28     let mut w = unsafe { RawFormatter::from_ptrs(buf.cast(), end.cast()) };
29     let _ = w.write_fmt(unsafe { *(ptr as *const fmt::Arguments<'_>) });
30     w.pos().cast()
31 }
32
33 /// Format strings.
34 ///
35 /// Public but hidden since it should only be used from public macros.
36 #[doc(hidden)]
37 pub mod format_strings {
38     use crate::bindings;
39
40     /// The length we copy from the `KERN_*` kernel prefixes.
41     const LENGTH_PREFIX: usize = 2;
42
43     /// The length of the fixed format strings.
44     pub const LENGTH: usize = 10;
45
46     /// Generates a fixed format string for the kernel's [`_printk`].
47     ///
48     /// The format string is always the same for a given level, i.e. for a
49     /// given `prefix`, which are the kernel's `KERN_*` constants.
50     ///
51     /// [`_printk`]: ../../../../include/linux/printk.h
52     const fn generate(is_cont: bool, prefix: &[u8; 3]) -> [u8; LENGTH] {
53         // Ensure the `KERN_*` macros are what we expect.
54         assert!(prefix[0] == b'\x01');
55         if is_cont {
56             assert!(prefix[1] == b'c');
57         } else {
58             assert!(prefix[1] >= b'0' && prefix[1] <= b'7');
59         }
60         assert!(prefix[2] == b'\x00');
61
62         let suffix: &[u8; LENGTH - LENGTH_PREFIX] = if is_cont {
63             b"%pA\0\0\0\0\0"
64         } else {
65             b"%s: %pA\0"
66         };
67
68         [
69             prefix[0], prefix[1], suffix[0], suffix[1], suffix[2], suffix[3], suffix[4], suffix[5],
70             suffix[6], suffix[7],
71         ]
72     }
73
74     // Generate the format strings at compile-time.
75     //
76     // This avoids the compiler generating the contents on the fly in the stack.
77     //
78     // Furthermore, `static` instead of `const` is used to share the strings
79     // for all the kernel.
80     pub static EMERG: [u8; LENGTH] = generate(false, bindings::KERN_EMERG);
81     pub static INFO: [u8; LENGTH] = generate(false, bindings::KERN_INFO);
82 }
83
84 /// Prints a message via the kernel's [`_printk`].
85 ///
86 /// Public but hidden since it should only be used from public macros.
87 ///
88 /// # Safety
89 ///
90 /// The format string must be one of the ones in [`format_strings`], and
91 /// the module name must be null-terminated.
92 ///
93 /// [`_printk`]: ../../../../include/linux/_printk.h
94 #[doc(hidden)]
95 #[cfg_attr(not(CONFIG_PRINTK), allow(unused_variables))]
96 pub unsafe fn call_printk(
97     format_string: &[u8; format_strings::LENGTH],
98     module_name: &[u8],
99     args: fmt::Arguments<'_>,
100 ) {
101     // `_printk` does not seem to fail in any path.
102     #[cfg(CONFIG_PRINTK)]
103     unsafe {
104         bindings::_printk(
105             format_string.as_ptr() as _,
106             module_name.as_ptr(),
107             &args as *const _ as *const c_void,
108         );
109     }
110 }
111
112 /// Performs formatting and forwards the string to [`call_printk`].
113 ///
114 /// Public but hidden since it should only be used from public macros.
115 #[doc(hidden)]
116 #[cfg(not(testlib))]
117 #[macro_export]
118 #[allow(clippy::crate_in_macro_def)]
119 macro_rules! print_macro (
120     // The non-continuation cases (most of them, e.g. `INFO`).
121     ($format_string:path, $($arg:tt)+) => (
122         // To remain sound, `arg`s must be expanded outside the `unsafe` block.
123         // Typically one would use a `let` binding for that; however, `format_args!`
124         // takes borrows on the arguments, but does not extend the scope of temporaries.
125         // Therefore, a `match` expression is used to keep them around, since
126         // the scrutinee is kept until the end of the `match`.
127         match format_args!($($arg)+) {
128             // SAFETY: This hidden macro should only be called by the documented
129             // printing macros which ensure the format string is one of the fixed
130             // ones. All `__LOG_PREFIX`s are null-terminated as they are generated
131             // by the `module!` proc macro or fixed values defined in a kernel
132             // crate.
133             args => unsafe {
134                 $crate::print::call_printk(
135                     &$format_string,
136                     crate::__LOG_PREFIX,
137                     args,
138                 );
139             }
140         }
141     );
142 );
143
144 /// Stub for doctests
145 #[cfg(testlib)]
146 #[macro_export]
147 macro_rules! print_macro (
148     ($format_string:path, $e:expr, $($arg:tt)+) => (
149         ()
150     );
151 );
152
153 // We could use a macro to generate these macros. However, doing so ends
154 // up being a bit ugly: it requires the dollar token trick to escape `$` as
155 // well as playing with the `doc` attribute. Furthermore, they cannot be easily
156 // imported in the prelude due to [1]. So, for the moment, we just write them
157 // manually, like in the C side; while keeping most of the logic in another
158 // macro, i.e. [`print_macro`].
159 //
160 // [1]: https://github.com/rust-lang/rust/issues/52234
161
162 /// Prints an emergency-level message (level 0).
163 ///
164 /// Use this level if the system is unusable.
165 ///
166 /// Equivalent to the kernel's [`pr_emerg`] macro.
167 ///
168 /// Mimics the interface of [`std::print!`]. See [`core::fmt`] and
169 /// `alloc::format!` for information about the formatting syntax.
170 ///
171 /// [`pr_emerg`]: https://www.kernel.org/doc/html/latest/core-api/printk-basics.html#c.pr_emerg
172 /// [`std::print!`]: https://doc.rust-lang.org/std/macro.print.html
173 ///
174 /// # Examples
175 ///
176 /// ```
177 /// pr_emerg!("hello {}\n", "there");
178 /// ```
179 #[macro_export]
180 macro_rules! pr_emerg (
181     ($($arg:tt)*) => (
182         $crate::print_macro!($crate::print::format_strings::EMERG, $($arg)*)
183     )
184 );
185
186 /// Prints an info-level message (level 6).
187 ///
188 /// Use this level for informational messages.
189 ///
190 /// Equivalent to the kernel's [`pr_info`] macro.
191 ///
192 /// Mimics the interface of [`std::print!`]. See [`core::fmt`] and
193 /// `alloc::format!` for information about the formatting syntax.
194 ///
195 /// [`pr_info`]: https://www.kernel.org/doc/html/latest/core-api/printk-basics.html#c.pr_info
196 /// [`std::print!`]: https://doc.rust-lang.org/std/macro.print.html
197 ///
198 /// # Examples
199 ///
200 /// ```
201 /// pr_info!("hello {}\n", "there");
202 /// ```
203 #[macro_export]
204 #[doc(alias = "print")]
205 macro_rules! pr_info (
206     ($($arg:tt)*) => (
207         $crate::print_macro!($crate::print::format_strings::INFO, $($arg)*)
208     )
209 );