xref: /linux/rust/kernel/print.rs (revision 90e0d94d369d342e735a75174439482119b6c393)
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         // SAFETY: This hidden macro should only be called by the documented
119         // printing macros which ensure the format string is one of the fixed
120         // ones. All `__LOG_PREFIX`s are null-terminated as they are generated
121         // by the `module!` proc macro or fixed values defined in a kernel
122         // crate.
123         unsafe {
124             $crate::print::call_printk(
125                 &$format_string,
126                 crate::__LOG_PREFIX,
127                 format_args!($($arg)+),
128             );
129         }
130     );
131 );
132 
133 /// Stub for doctests
134 #[cfg(testlib)]
135 #[macro_export]
136 macro_rules! print_macro (
137     ($format_string:path, $e:expr, $($arg:tt)+) => (
138         ()
139     );
140 );
141 
142 // We could use a macro to generate these macros. However, doing so ends
143 // up being a bit ugly: it requires the dollar token trick to escape `$` as
144 // well as playing with the `doc` attribute. Furthermore, they cannot be easily
145 // imported in the prelude due to [1]. So, for the moment, we just write them
146 // manually, like in the C side; while keeping most of the logic in another
147 // macro, i.e. [`print_macro`].
148 //
149 // [1]: https://github.com/rust-lang/rust/issues/52234
150 
151 /// Prints an emergency-level message (level 0).
152 ///
153 /// Use this level if the system is unusable.
154 ///
155 /// Equivalent to the kernel's [`pr_emerg`] macro.
156 ///
157 /// Mimics the interface of [`std::print!`]. See [`core::fmt`] and
158 /// `alloc::format!` for information about the formatting syntax.
159 ///
160 /// [`pr_emerg`]: https://www.kernel.org/doc/html/latest/core-api/printk-basics.html#c.pr_emerg
161 /// [`std::print!`]: https://doc.rust-lang.org/std/macro.print.html
162 ///
163 /// # Examples
164 ///
165 /// ```
166 /// pr_emerg!("hello {}\n", "there");
167 /// ```
168 #[macro_export]
169 macro_rules! pr_emerg (
170     ($($arg:tt)*) => (
171         $crate::print_macro!($crate::print::format_strings::EMERG, $($arg)*)
172     )
173 );
174 
175 /// Prints an info-level message (level 6).
176 ///
177 /// Use this level for informational messages.
178 ///
179 /// Equivalent to the kernel's [`pr_info`] macro.
180 ///
181 /// Mimics the interface of [`std::print!`]. See [`core::fmt`] and
182 /// `alloc::format!` for information about the formatting syntax.
183 ///
184 /// [`pr_info`]: https://www.kernel.org/doc/html/latest/core-api/printk-basics.html#c.pr_info
185 /// [`std::print!`]: https://doc.rust-lang.org/std/macro.print.html
186 ///
187 /// # Examples
188 ///
189 /// ```
190 /// pr_info!("hello {}\n", "there");
191 /// ```
192 #[macro_export]
193 #[doc(alias = "print")]
194 macro_rules! pr_info (
195     ($($arg:tt)*) => (
196         $crate::print_macro!($crate::print::format_strings::INFO, $($arg)*)
197     )
198 );
199