print.rs 13 KB

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