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!",
38 /// alias: ["alternate_module_name"],
43 /// impl kernel::Module for MyModule {
44 /// fn init() -> Result<Self> {
45 /// // If the parameter is writeable, then the kparam lock must be
46 /// // taken to read the parameter:
48 /// let lock = THIS_MODULE.kernel_param_lock();
49 /// pr_info!("i32 param is: {}\n", writeable_i32.read(&lock));
51 /// // If the parameter is read only, it can be read without locking
52 /// // the kernel parameters:
53 /// pr_info!("i32 param is: {}\n", my_i32.read());
61 /// The following example shows how to declare a kernel module that needs
62 /// to load binary firmware files. You need to specify the file names of
63 /// the firmware in the `firmware` field. The information is embedded
64 /// in the `modinfo` section of the kernel module. For example, a tool to
65 /// build an initramfs uses this information to put the firmware files into
66 /// the initramfs image.
69 /// use kernel::prelude::*;
72 /// type: MyDeviceDriverModule,
73 /// name: "my_device_driver_module",
74 /// author: "Rust for Linux Contributors",
75 /// description: "My device driver requires firmware",
77 /// firmware: ["my_device_firmware1.bin", "my_device_firmware2.bin"],
80 /// struct MyDeviceDriverModule;
82 /// impl kernel::Module for MyDeviceDriverModule {
83 /// fn init() -> Result<Self> {
89 /// # Supported argument types
90 /// - `type`: type which implements the [`Module`] trait (required).
91 /// - `name`: ASCII string literal of the name of the kernel module (required).
92 /// - `author`: string literal of the author of the kernel module.
93 /// - `description`: string literal of the description of the kernel module.
94 /// - `license`: ASCII string literal of the license of the kernel module (required).
95 /// - `alias`: array of ASCII string literals of the alias names of the kernel module.
96 /// - `firmware`: array of ASCII string literals of the firmware files of
97 /// the kernel module.
99 pub fn module(ts: TokenStream) -> TokenStream {
103 /// Declares or implements a vtable trait.
105 /// Linux's use of pure vtables is very close to Rust traits, but they differ
106 /// in how unimplemented functions are represented. In Rust, traits can provide
107 /// default implementation for all non-required methods (and the default
108 /// implementation could just return `Error::EINVAL`); Linux typically use C
109 /// `NULL` pointers to represent these functions.
111 /// This attribute closes that gap. A trait can be annotated with the
112 /// `#[vtable]` attribute. Implementers of the trait will then also have to
113 /// annotate the trait with `#[vtable]`. This attribute generates a `HAS_*`
114 /// associated constant bool for each method in the trait that is set to true if
115 /// the implementer has overridden the associated method.
117 /// For a trait method to be optional, it must have a default implementation.
118 /// This is also the case for traits annotated with `#[vtable]`, but in this
119 /// case the default implementation will never be executed. The reason for this
120 /// is that the functions will be called through function pointers installed in
121 /// C side vtables. When an optional method is not implemented on a `#[vtable]`
122 /// trait, a NULL entry is installed in the vtable. Thus the default
123 /// implementation is never called. Since these traits are not designed to be
124 /// used on the Rust side, it should not be possible to call the default
125 /// implementation. This is done to ensure that we call the vtable methods
126 /// through the C vtable, and not through the Rust vtable. Therefore, the
127 /// default implementation should call `kernel::build_error`, which prevents
128 /// calls to this function at compile time:
131 /// # use kernel::error::VTABLE_DEFAULT_ERROR;
132 /// kernel::build_error(VTABLE_DEFAULT_ERROR)
135 /// Note that you might need to import [`kernel::error::VTABLE_DEFAULT_ERROR`].
137 /// This macro should not be used when all functions are required.
142 /// use kernel::error::VTABLE_DEFAULT_ERROR;
143 /// use kernel::prelude::*;
145 /// // Declares a `#[vtable]` trait
147 /// pub trait Operations: Send + Sync + Sized {
148 /// fn foo(&self) -> Result<()> {
149 /// kernel::build_error(VTABLE_DEFAULT_ERROR)
152 /// fn bar(&self) -> Result<()> {
153 /// kernel::build_error(VTABLE_DEFAULT_ERROR)
159 /// // Implements the `#[vtable]` trait
161 /// impl Operations for Foo {
162 /// fn foo(&self) -> Result<()> {
168 /// assert_eq!(<Foo as Operations>::HAS_FOO, true);
169 /// assert_eq!(<Foo as Operations>::HAS_BAR, false);
172 /// [`kernel::error::VTABLE_DEFAULT_ERROR`]: ../kernel/error/constant.VTABLE_DEFAULT_ERROR.html
173 #[proc_macro_attribute]
174 pub fn vtable(attr: TokenStream, ts: TokenStream) -> TokenStream {
175 vtable::vtable(attr, ts)
178 /// Concatenate two identifiers.
180 /// This is useful in macros that need to declare or reference items with names
181 /// starting with a fixed prefix and ending in a user specified name. The resulting
182 /// identifier has the span of the second argument.
187 /// use kernel::macro::concat_idents;
189 /// macro_rules! pub_no_prefix {
190 /// ($prefix:ident, $($newname:ident),+) => {
191 /// $(pub(crate) const $newname: u32 = kernel::macros::concat_idents!($prefix, $newname);)+
196 /// binder_driver_return_protocol_,
202 /// BR_TRANSACTION_COMPLETE,
210 /// BR_CLEAR_DEATH_NOTIFICATION_DONE,
214 /// assert_eq!(BR_OK, binder_driver_return_protocol_BR_OK);
217 pub fn concat_idents(ts: TokenStream) -> TokenStream {
218 concat_idents::concat_idents(ts)
221 /// Used to specify the pinning information of the fields of a struct.
223 /// This is somewhat similar in purpose as
224 /// [pin-project-lite](https://crates.io/crates/pin-project-lite).
225 /// Place this macro on a struct definition and then `#[pin]` in front of the attributes of each
226 /// field you want to structurally pin.
228 /// This macro enables the use of the [`pin_init!`] macro. When pin-initializing a `struct`,
229 /// then `#[pin]` directs the type of initializer that is required.
231 /// If your `struct` implements `Drop`, then you need to add `PinnedDrop` as arguments to this
232 /// macro, and change your `Drop` implementation to `PinnedDrop` annotated with
233 /// `#[`[`macro@pinned_drop`]`]`, since dropping pinned values requires extra care.
239 /// struct DriverData {
241 /// queue: Mutex<Vec<Command>>,
242 /// buf: Box<[u8; 1024 * 1024]>,
247 /// #[pin_data(PinnedDrop)]
248 /// struct DriverData {
250 /// queue: Mutex<Vec<Command>>,
251 /// buf: Box<[u8; 1024 * 1024]>,
252 /// raw_info: *mut Info,
256 /// impl PinnedDrop for DriverData {
257 /// fn drop(self: Pin<&mut Self>) {
258 /// unsafe { bindings::destroy_info(self.raw_info) };
263 /// [`pin_init!`]: ../kernel/macro.pin_init.html
264 // ^ cannot use direct link, since `kernel` is not a dependency of `macros`.
265 #[proc_macro_attribute]
266 pub fn pin_data(inner: TokenStream, item: TokenStream) -> TokenStream {
267 pin_data::pin_data(inner, item)
270 /// Used to implement `PinnedDrop` safely.
272 /// Only works on structs that are annotated via `#[`[`macro@pin_data`]`]`.
277 /// #[pin_data(PinnedDrop)]
278 /// struct DriverData {
280 /// queue: Mutex<Vec<Command>>,
281 /// buf: Box<[u8; 1024 * 1024]>,
282 /// raw_info: *mut Info,
286 /// impl PinnedDrop for DriverData {
287 /// fn drop(self: Pin<&mut Self>) {
288 /// unsafe { bindings::destroy_info(self.raw_info) };
292 #[proc_macro_attribute]
293 pub fn pinned_drop(args: TokenStream, input: TokenStream) -> TokenStream {
294 pinned_drop::pinned_drop(args, input)
297 /// Paste identifiers together.
299 /// Within the `paste!` macro, identifiers inside `[<` and `>]` are concatenated together to form a
300 /// single identifier.
302 /// This is similar to the [`paste`] crate, but with pasting feature limited to identifiers and
303 /// literals (lifetimes and documentation strings are not supported). There is a difference in
304 /// supported modifiers as well.
309 /// use kernel::macro::paste;
311 /// macro_rules! pub_no_prefix {
312 /// ($prefix:ident, $($newname:ident),+) => {
314 /// $(pub(crate) const $newname: u32 = [<$prefix $newname>];)+
320 /// binder_driver_return_protocol_,
326 /// BR_TRANSACTION_COMPLETE,
334 /// BR_CLEAR_DEATH_NOTIFICATION_DONE,
338 /// assert_eq!(BR_OK, binder_driver_return_protocol_BR_OK);
343 /// For each identifier, it is possible to attach one or multiple modifiers to
346 /// Currently supported modifiers are:
347 /// * `span`: change the span of concatenated identifier to the span of the specified token. By
348 /// default the span of the `[< >]` group is used.
349 /// * `lower`: change the identifier to lower case.
350 /// * `upper`: change the identifier to upper case.
353 /// use kernel::macro::paste;
355 /// macro_rules! pub_no_prefix {
356 /// ($prefix:ident, $($newname:ident),+) => {
357 /// kernel::macros::paste! {
358 /// $(pub(crate) const fn [<$newname:lower:span>]: u32 = [<$prefix $newname:span>];)+
364 /// binder_driver_return_protocol_,
370 /// BR_TRANSACTION_COMPLETE,
378 /// BR_CLEAR_DEATH_NOTIFICATION_DONE,
382 /// assert_eq!(br_ok(), binder_driver_return_protocol_BR_OK);
387 /// Literals can also be concatenated with other identifiers:
390 /// macro_rules! create_numbered_fn {
391 /// ($name:literal, $val:literal) => {
392 /// kernel::macros::paste! {
393 /// fn [<some_ $name _fn $val>]() -> u32 { $val }
398 /// create_numbered_fn!("foo", 100);
400 /// assert_eq!(some_foo_fn100(), 100)
403 /// [`paste`]: https://docs.rs/paste/
405 pub fn paste(input: TokenStream) -> TokenStream {
406 let mut tokens = input.into_iter().collect();
407 paste::expand(&mut tokens);
408 tokens.into_iter().collect()
411 /// Derives the [`Zeroable`] trait for the given struct.
413 /// This can only be used for structs where every field implements the [`Zeroable`] trait.
418 /// #[derive(Zeroable)]
419 /// pub struct DriverData {
421 /// buf_ptr: *mut u8,
425 #[proc_macro_derive(Zeroable)]
426 pub fn derive_zeroable(input: TokenStream) -> TokenStream {
427 zeroable::derive(input)