1 // SPDX-License-Identifier: GPL-2.0
3 //! Crate for all kernel procedural macros.
16 use proc_macro::TokenStream;
18 /// Declares a kernel module.
20 /// The `type` argument should be a type which implements the [`Module`]
21 /// trait. Also accepts various forms of kernel metadata.
23 /// C header: [`include/linux/moduleparam.h`](srctree/include/linux/moduleparam.h)
25 /// [`Module`]: ../kernel/trait.Module.html
30 /// use kernel::prelude::*;
34 /// name: "my_kernel_module",
35 /// author: "Rust for Linux Contributors",
36 /// description: "My very own kernel module!",
42 /// impl kernel::Module for MyModule {
43 /// fn init() -> Result<Self> {
44 /// // If the parameter is writeable, then the kparam lock must be
45 /// // taken to read the parameter:
47 /// let lock = THIS_MODULE.kernel_param_lock();
48 /// pr_info!("i32 param is: {}\n", writeable_i32.read(&lock));
50 /// // If the parameter is read only, it can be read without locking
51 /// // the kernel parameters:
52 /// pr_info!("i32 param is: {}\n", my_i32.read());
58 /// # Supported argument types
59 /// - `type`: type which implements the [`Module`] trait (required).
60 /// - `name`: byte array of the name of the kernel module (required).
61 /// - `author`: byte array of the author of the kernel module.
62 /// - `description`: byte array of the description of the kernel module.
63 /// - `license`: byte array of the license of the kernel module (required).
64 /// - `alias`: byte array of alias name of the kernel module.
66 pub fn module(ts: TokenStream) -> TokenStream {
70 /// Declares or implements a vtable trait.
72 /// Linux's use of pure vtables is very close to Rust traits, but they differ
73 /// in how unimplemented functions are represented. In Rust, traits can provide
74 /// default implementation for all non-required methods (and the default
75 /// implementation could just return `Error::EINVAL`); Linux typically use C
76 /// `NULL` pointers to represent these functions.
78 /// This attribute closes that gap. A trait can be annotated with the
79 /// `#[vtable]` attribute. Implementers of the trait will then also have to
80 /// annotate the trait with `#[vtable]`. This attribute generates a `HAS_*`
81 /// associated constant bool for each method in the trait that is set to true if
82 /// the implementer has overridden the associated method.
84 /// For a trait method to be optional, it must have a default implementation.
85 /// This is also the case for traits annotated with `#[vtable]`, but in this
86 /// case the default implementation will never be executed. The reason for this
87 /// is that the functions will be called through function pointers installed in
88 /// C side vtables. When an optional method is not implemented on a `#[vtable]`
89 /// trait, a NULL entry is installed in the vtable. Thus the default
90 /// implementation is never called. Since these traits are not designed to be
91 /// used on the Rust side, it should not be possible to call the default
92 /// implementation. This is done to ensure that we call the vtable methods
93 /// through the C vtable, and not through the Rust vtable. Therefore, the
94 /// default implementation should call `kernel::build_error`, which prevents
95 /// calls to this function at compile time:
98 /// # use kernel::error::VTABLE_DEFAULT_ERROR;
99 /// kernel::build_error(VTABLE_DEFAULT_ERROR)
102 /// Note that you might need to import [`kernel::error::VTABLE_DEFAULT_ERROR`].
104 /// This macro should not be used when all functions are required.
109 /// use kernel::error::VTABLE_DEFAULT_ERROR;
110 /// use kernel::prelude::*;
112 /// // Declares a `#[vtable]` trait
114 /// pub trait Operations: Send + Sync + Sized {
115 /// fn foo(&self) -> Result<()> {
116 /// kernel::build_error(VTABLE_DEFAULT_ERROR)
119 /// fn bar(&self) -> Result<()> {
120 /// kernel::build_error(VTABLE_DEFAULT_ERROR)
126 /// // Implements the `#[vtable]` trait
128 /// impl Operations for Foo {
129 /// fn foo(&self) -> Result<()> {
135 /// assert_eq!(<Foo as Operations>::HAS_FOO, true);
136 /// assert_eq!(<Foo as Operations>::HAS_BAR, false);
139 /// [`kernel::error::VTABLE_DEFAULT_ERROR`]: ../kernel/error/constant.VTABLE_DEFAULT_ERROR.html
140 #[proc_macro_attribute]
141 pub fn vtable(attr: TokenStream, ts: TokenStream) -> TokenStream {
142 vtable::vtable(attr, ts)
145 /// Concatenate two identifiers.
147 /// This is useful in macros that need to declare or reference items with names
148 /// starting with a fixed prefix and ending in a user specified name. The resulting
149 /// identifier has the span of the second argument.
154 /// use kernel::macro::concat_idents;
156 /// macro_rules! pub_no_prefix {
157 /// ($prefix:ident, $($newname:ident),+) => {
158 /// $(pub(crate) const $newname: u32 = kernel::macros::concat_idents!($prefix, $newname);)+
163 /// binder_driver_return_protocol_,
169 /// BR_TRANSACTION_COMPLETE,
177 /// BR_CLEAR_DEATH_NOTIFICATION_DONE,
181 /// assert_eq!(BR_OK, binder_driver_return_protocol_BR_OK);
184 pub fn concat_idents(ts: TokenStream) -> TokenStream {
185 concat_idents::concat_idents(ts)
188 /// Used to specify the pinning information of the fields of a struct.
190 /// This is somewhat similar in purpose as
191 /// [pin-project-lite](https://crates.io/crates/pin-project-lite).
192 /// Place this macro on a struct definition and then `#[pin]` in front of the attributes of each
193 /// field you want to structurally pin.
195 /// This macro enables the use of the [`pin_init!`] macro. When pin-initializing a `struct`,
196 /// then `#[pin]` directs the type of initializer that is required.
198 /// If your `struct` implements `Drop`, then you need to add `PinnedDrop` as arguments to this
199 /// macro, and change your `Drop` implementation to `PinnedDrop` annotated with
200 /// `#[`[`macro@pinned_drop`]`]`, since dropping pinned values requires extra care.
206 /// struct DriverData {
208 /// queue: Mutex<Vec<Command>>,
209 /// buf: Box<[u8; 1024 * 1024]>,
214 /// #[pin_data(PinnedDrop)]
215 /// struct DriverData {
217 /// queue: Mutex<Vec<Command>>,
218 /// buf: Box<[u8; 1024 * 1024]>,
219 /// raw_info: *mut Info,
223 /// impl PinnedDrop for DriverData {
224 /// fn drop(self: Pin<&mut Self>) {
225 /// unsafe { bindings::destroy_info(self.raw_info) };
230 /// [`pin_init!`]: ../kernel/macro.pin_init.html
231 // ^ cannot use direct link, since `kernel` is not a dependency of `macros`.
232 #[proc_macro_attribute]
233 pub fn pin_data(inner: TokenStream, item: TokenStream) -> TokenStream {
234 pin_data::pin_data(inner, item)
237 /// Used to implement `PinnedDrop` safely.
239 /// Only works on structs that are annotated via `#[`[`macro@pin_data`]`]`.
244 /// #[pin_data(PinnedDrop)]
245 /// struct DriverData {
247 /// queue: Mutex<Vec<Command>>,
248 /// buf: Box<[u8; 1024 * 1024]>,
249 /// raw_info: *mut Info,
253 /// impl PinnedDrop for DriverData {
254 /// fn drop(self: Pin<&mut Self>) {
255 /// unsafe { bindings::destroy_info(self.raw_info) };
259 #[proc_macro_attribute]
260 pub fn pinned_drop(args: TokenStream, input: TokenStream) -> TokenStream {
261 pinned_drop::pinned_drop(args, input)
264 /// Paste identifiers together.
266 /// Within the `paste!` macro, identifiers inside `[<` and `>]` are concatenated together to form a
267 /// single identifier.
269 /// This is similar to the [`paste`] crate, but with pasting feature limited to identifiers and
270 /// literals (lifetimes and documentation strings are not supported). There is a difference in
271 /// supported modifiers as well.
276 /// use kernel::macro::paste;
278 /// macro_rules! pub_no_prefix {
279 /// ($prefix:ident, $($newname:ident),+) => {
281 /// $(pub(crate) const $newname: u32 = [<$prefix $newname>];)+
287 /// binder_driver_return_protocol_,
293 /// BR_TRANSACTION_COMPLETE,
301 /// BR_CLEAR_DEATH_NOTIFICATION_DONE,
305 /// assert_eq!(BR_OK, binder_driver_return_protocol_BR_OK);
310 /// For each identifier, it is possible to attach one or multiple modifiers to
313 /// Currently supported modifiers are:
314 /// * `span`: change the span of concatenated identifier to the span of the specified token. By
315 /// default the span of the `[< >]` group is used.
316 /// * `lower`: change the identifier to lower case.
317 /// * `upper`: change the identifier to upper case.
320 /// use kernel::macro::paste;
322 /// macro_rules! pub_no_prefix {
323 /// ($prefix:ident, $($newname:ident),+) => {
324 /// kernel::macros::paste! {
325 /// $(pub(crate) const fn [<$newname:lower:span>]: u32 = [<$prefix $newname:span>];)+
331 /// binder_driver_return_protocol_,
337 /// BR_TRANSACTION_COMPLETE,
345 /// BR_CLEAR_DEATH_NOTIFICATION_DONE,
349 /// assert_eq!(br_ok(), binder_driver_return_protocol_BR_OK);
354 /// Literals can also be concatenated with other identifiers:
357 /// macro_rules! create_numbered_fn {
358 /// ($name:literal, $val:literal) => {
359 /// kernel::macros::paste! {
360 /// fn [<some_ $name _fn $val>]() -> u32 { $val }
365 /// create_numbered_fn!("foo", 100);
367 /// assert_eq!(some_foo_fn100(), 100)
370 /// [`paste`]: https://docs.rs/paste/
372 pub fn paste(input: TokenStream) -> TokenStream {
373 let mut tokens = input.into_iter().collect();
374 paste::expand(&mut tokens);
375 tokens.into_iter().collect()
378 /// Derives the [`Zeroable`] trait for the given struct.
380 /// This can only be used for structs where every field implements the [`Zeroable`] trait.
385 /// #[derive(Zeroable)]
386 /// pub struct DriverData {
388 /// buf_ptr: *mut u8,
392 #[proc_macro_derive(Zeroable)]
393 pub fn derive_zeroable(input: TokenStream) -> TokenStream {
394 zeroable::derive(input)