kernel/
seq_file.rs

1// SPDX-License-Identifier: GPL-2.0
2
3//! Seq file bindings.
4//!
5//! C header: [`include/linux/seq_file.h`](srctree/include/linux/seq_file.h)
6
7use crate::{bindings, c_str, fmt, str::CStrExt as _, types::NotThreadSafe, types::Opaque};
8use safety_macro::safety;
9/// A utility for generating the contents of a seq file.
10#[repr(transparent)]
11pub struct SeqFile {
12    inner: Opaque<bindings::seq_file>,
13    _not_send: NotThreadSafe,
14}
15
16impl SeqFile {
17    /// Creates a new [`SeqFile`] from a raw pointer.
18    ///
19    /// # Safety
20    ///
21    /// The caller must ensure that for the duration of `'a` the following is satisfied:
22    /// * The pointer points at a valid `struct seq_file`.
23    /// * The `struct seq_file` is not accessed from any other thread.
24    #[safety{Typed(ptr, bindings::seq_file), CurThread(SeqFile)}]
25    pub unsafe fn from_raw<'a>(ptr: *mut bindings::seq_file) -> &'a SeqFile {
26        // SAFETY: The caller ensures that the reference is valid for 'a. There's no way to trigger
27        // a data race by using the `&SeqFile` since this is the only thread accessing the seq_file.
28        //
29        // CAST: The layout of `struct seq_file` and `SeqFile` is compatible.
30        unsafe { &*ptr.cast() }
31    }
32
33    /// Used by the [`seq_print`] macro.
34    #[inline]
35    pub fn call_printf(&self, args: fmt::Arguments<'_>) {
36        // SAFETY: Passing a void pointer to `Arguments` is valid for `%pA`.
37        unsafe {
38            bindings::seq_printf(
39                self.inner.get(),
40                c_str!("%pA").as_char_ptr(),
41                core::ptr::from_ref(&args).cast::<crate::ffi::c_void>(),
42            );
43        }
44    }
45}
46
47/// Write to a [`SeqFile`] with the ordinary Rust formatting syntax.
48#[macro_export]
49macro_rules! seq_print {
50    ($m:expr, $($arg:tt)+) => (
51        $m.call_printf($crate::prelude::fmt!($($arg)+))
52    );
53}
54pub use seq_print;