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!",
41 /// permissions: 0o000,
42 /// description: "Example of i32",
44 /// writeable_i32: i32 {
46 /// permissions: 0o644,
47 /// description: "Example of i32",
54 /// impl kernel::Module for MyModule {
55 /// fn init() -> Result<Self> {
56 /// // If the parameter is writeable, then the kparam lock must be
57 /// // taken to read the parameter:
59 /// let lock = THIS_MODULE.kernel_param_lock();
60 /// pr_info!("i32 param is: {}\n", writeable_i32.read(&lock));
62 /// // If the parameter is read only, it can be read without locking
63 /// // the kernel parameters:
64 /// pr_info!("i32 param is: {}\n", my_i32.read());
70 /// # Supported argument types
71 /// - `type`: type which implements the [`Module`] trait (required).
72 /// - `name`: byte array of the name of the kernel module (required).
73 /// - `author`: byte array of the author of the kernel module.
74 /// - `description`: byte array of the description of the kernel module.
75 /// - `license`: byte array of the license of the kernel module (required).
76 /// - `alias`: byte array of alias name of the kernel module.
78 pub fn module(ts: TokenStream) -> TokenStream {
82 /// Declares or implements a vtable trait.
84 /// Linux's use of pure vtables is very close to Rust traits, but they differ
85 /// in how unimplemented functions are represented. In Rust, traits can provide
86 /// default implementation for all non-required methods (and the default
87 /// implementation could just return `Error::EINVAL`); Linux typically use C
88 /// `NULL` pointers to represent these functions.
90 /// This attribute closes that gap. A trait can be annotated with the
91 /// `#[vtable]` attribute. Implementers of the trait will then also have to
92 /// annotate the trait with `#[vtable]`. This attribute generates a `HAS_*`
93 /// associated constant bool for each method in the trait that is set to true if
94 /// the implementer has overridden the associated method.
96 /// For a trait method to be optional, it must have a default implementation.
97 /// This is also the case for traits annotated with `#[vtable]`, but in this
98 /// case the default implementation will never be executed. The reason for this
99 /// is that the functions will be called through function pointers installed in
100 /// C side vtables. When an optional method is not implemented on a `#[vtable]`
101 /// trait, a NULL entry is installed in the vtable. Thus the default
102 /// implementation is never called. Since these traits are not designed to be
103 /// used on the Rust side, it should not be possible to call the default
104 /// implementation. This is done to ensure that we call the vtable methods
105 /// through the C vtable, and not through the Rust vtable. Therefore, the
106 /// default implementation should call `kernel::build_error`, which prevents
107 /// calls to this function at compile time:
110 /// # use kernel::error::VTABLE_DEFAULT_ERROR;
111 /// kernel::build_error(VTABLE_DEFAULT_ERROR)
114 /// Note that you might need to import [`kernel::error::VTABLE_DEFAULT_ERROR`].
116 /// This macro should not be used when all functions are required.
121 /// use kernel::error::VTABLE_DEFAULT_ERROR;
122 /// use kernel::prelude::*;
124 /// // Declares a `#[vtable]` trait
126 /// pub trait Operations: Send + Sync + Sized {
127 /// fn foo(&self) -> Result<()> {
128 /// kernel::build_error(VTABLE_DEFAULT_ERROR)
131 /// fn bar(&self) -> Result<()> {
132 /// kernel::build_error(VTABLE_DEFAULT_ERROR)
138 /// // Implements the `#[vtable]` trait
140 /// impl Operations for Foo {
141 /// fn foo(&self) -> Result<()> {
147 /// assert_eq!(<Foo as Operations>::HAS_FOO, true);
148 /// assert_eq!(<Foo as Operations>::HAS_BAR, false);
151 /// [`kernel::error::VTABLE_DEFAULT_ERROR`]: ../kernel/error/constant.VTABLE_DEFAULT_ERROR.html
152 #[proc_macro_attribute]
153 pub fn vtable(attr: TokenStream, ts: TokenStream) -> TokenStream {
154 vtable::vtable(attr, ts)
157 /// Concatenate two identifiers.
159 /// This is useful in macros that need to declare or reference items with names
160 /// starting with a fixed prefix and ending in a user specified name. The resulting
161 /// identifier has the span of the second argument.
166 /// use kernel::macro::concat_idents;
168 /// macro_rules! pub_no_prefix {
169 /// ($prefix:ident, $($newname:ident),+) => {
170 /// $(pub(crate) const $newname: u32 = kernel::macros::concat_idents!($prefix, $newname);)+
175 /// binder_driver_return_protocol_,
181 /// BR_TRANSACTION_COMPLETE,
189 /// BR_CLEAR_DEATH_NOTIFICATION_DONE,
193 /// assert_eq!(BR_OK, binder_driver_return_protocol_BR_OK);
196 pub fn concat_idents(ts: TokenStream) -> TokenStream {
197 concat_idents::concat_idents(ts)
200 /// Used to specify the pinning information of the fields of a struct.
202 /// This is somewhat similar in purpose as
203 /// [pin-project-lite](https://crates.io/crates/pin-project-lite).
204 /// Place this macro on a struct definition and then `#[pin]` in front of the attributes of each
205 /// field you want to structurally pin.
207 /// This macro enables the use of the [`pin_init!`] macro. When pin-initializing a `struct`,
208 /// then `#[pin]` directs the type of initializer that is required.
210 /// If your `struct` implements `Drop`, then you need to add `PinnedDrop` as arguments to this
211 /// macro, and change your `Drop` implementation to `PinnedDrop` annotated with
212 /// `#[`[`macro@pinned_drop`]`]`, since dropping pinned values requires extra care.
218 /// struct DriverData {
220 /// queue: Mutex<Vec<Command>>,
221 /// buf: Box<[u8; 1024 * 1024]>,
226 /// #[pin_data(PinnedDrop)]
227 /// struct DriverData {
229 /// queue: Mutex<Vec<Command>>,
230 /// buf: Box<[u8; 1024 * 1024]>,
231 /// raw_info: *mut Info,
235 /// impl PinnedDrop for DriverData {
236 /// fn drop(self: Pin<&mut Self>) {
237 /// unsafe { bindings::destroy_info(self.raw_info) };
242 /// [`pin_init!`]: ../kernel/macro.pin_init.html
243 // ^ cannot use direct link, since `kernel` is not a dependency of `macros`.
244 #[proc_macro_attribute]
245 pub fn pin_data(inner: TokenStream, item: TokenStream) -> TokenStream {
246 pin_data::pin_data(inner, item)
249 /// Used to implement `PinnedDrop` safely.
251 /// Only works on structs that are annotated via `#[`[`macro@pin_data`]`]`.
256 /// #[pin_data(PinnedDrop)]
257 /// struct DriverData {
259 /// queue: Mutex<Vec<Command>>,
260 /// buf: Box<[u8; 1024 * 1024]>,
261 /// raw_info: *mut Info,
265 /// impl PinnedDrop for DriverData {
266 /// fn drop(self: Pin<&mut Self>) {
267 /// unsafe { bindings::destroy_info(self.raw_info) };
271 #[proc_macro_attribute]
272 pub fn pinned_drop(args: TokenStream, input: TokenStream) -> TokenStream {
273 pinned_drop::pinned_drop(args, input)
276 /// Paste identifiers together.
278 /// Within the `paste!` macro, identifiers inside `[<` and `>]` are concatenated together to form a
279 /// single identifier.
281 /// This is similar to the [`paste`] crate, but with pasting feature limited to identifiers and
282 /// literals (lifetimes and documentation strings are not supported). There is a difference in
283 /// supported modifiers as well.
288 /// use kernel::macro::paste;
290 /// macro_rules! pub_no_prefix {
291 /// ($prefix:ident, $($newname:ident),+) => {
293 /// $(pub(crate) const $newname: u32 = [<$prefix $newname>];)+
299 /// binder_driver_return_protocol_,
305 /// BR_TRANSACTION_COMPLETE,
313 /// BR_CLEAR_DEATH_NOTIFICATION_DONE,
317 /// assert_eq!(BR_OK, binder_driver_return_protocol_BR_OK);
322 /// For each identifier, it is possible to attach one or multiple modifiers to
325 /// Currently supported modifiers are:
326 /// * `span`: change the span of concatenated identifier to the span of the specified token. By
327 /// default the span of the `[< >]` group is used.
328 /// * `lower`: change the identifier to lower case.
329 /// * `upper`: change the identifier to upper case.
332 /// use kernel::macro::paste;
334 /// macro_rules! pub_no_prefix {
335 /// ($prefix:ident, $($newname:ident),+) => {
336 /// kernel::macros::paste! {
337 /// $(pub(crate) const fn [<$newname:lower:span>]: u32 = [<$prefix $newname:span>];)+
343 /// binder_driver_return_protocol_,
349 /// BR_TRANSACTION_COMPLETE,
357 /// BR_CLEAR_DEATH_NOTIFICATION_DONE,
361 /// assert_eq!(br_ok(), binder_driver_return_protocol_BR_OK);
366 /// Literals can also be concatenated with other identifiers:
369 /// macro_rules! create_numbered_fn {
370 /// ($name:literal, $val:literal) => {
371 /// kernel::macros::paste! {
372 /// fn [<some_ $name _fn $val>]() -> u32 { $val }
377 /// create_numbered_fn!("foo", 100);
379 /// assert_eq!(some_foo_fn100(), 100)
382 /// [`paste`]: https://docs.rs/paste/
384 pub fn paste(input: TokenStream) -> TokenStream {
385 let mut tokens = input.into_iter().collect();
386 paste::expand(&mut tokens);
387 tokens.into_iter().collect()
390 /// Derives the [`Zeroable`] trait for the given struct.
392 /// This can only be used for structs where every field implements the [`Zeroable`] trait.
397 /// #[derive(Zeroable)]
398 /// pub struct DriverData {
400 /// buf_ptr: *mut u8,
404 #[proc_macro_derive(Zeroable)]
405 pub fn derive_zeroable(input: TokenStream) -> TokenStream {
406 zeroable::derive(input)