1 // SPDX-License-Identifier: GPL-2.0
3 //! Crate for all kernel procedural macros.
5 // When fixdep scans this, it will find this string `CONFIG_RUSTC_VERSION_TEXT`
6 // and thus add a dependency on `include/config/RUSTC_VERSION_TEXT`, which is
7 // touched by Kconfig when the version string from the compiler changes.
20 use proc_macro::TokenStream;
22 /// Declares a kernel module.
24 /// The `type` argument should be a type which implements the [`Module`]
25 /// trait. Also accepts various forms of kernel metadata.
27 /// C header: [`include/linux/moduleparam.h`](srctree/include/linux/moduleparam.h)
29 /// [`Module`]: ../kernel/trait.Module.html
34 /// use kernel::prelude::*;
38 /// name: "my_kernel_module",
39 /// author: "Rust for Linux Contributors",
40 /// description: "My very own kernel module!",
42 /// alias: ["alternate_module_name"],
47 /// impl kernel::Module for MyModule {
48 /// fn init() -> Result<Self> {
49 /// // If the parameter is writeable, then the kparam lock must be
50 /// // taken to read the parameter:
52 /// let lock = THIS_MODULE.kernel_param_lock();
53 /// pr_info!("i32 param is: {}\n", writeable_i32.read(&lock));
55 /// // If the parameter is read only, it can be read without locking
56 /// // the kernel parameters:
57 /// pr_info!("i32 param is: {}\n", my_i32.read());
65 /// The following example shows how to declare a kernel module that needs
66 /// to load binary firmware files. You need to specify the file names of
67 /// the firmware in the `firmware` field. The information is embedded
68 /// in the `modinfo` section of the kernel module. For example, a tool to
69 /// build an initramfs uses this information to put the firmware files into
70 /// the initramfs image.
73 /// use kernel::prelude::*;
76 /// type: MyDeviceDriverModule,
77 /// name: "my_device_driver_module",
78 /// author: "Rust for Linux Contributors",
79 /// description: "My device driver requires firmware",
81 /// firmware: ["my_device_firmware1.bin", "my_device_firmware2.bin"],
84 /// struct MyDeviceDriverModule;
86 /// impl kernel::Module for MyDeviceDriverModule {
87 /// fn init() -> Result<Self> {
93 /// # Supported argument types
94 /// - `type`: type which implements the [`Module`] trait (required).
95 /// - `name`: ASCII string literal of the name of the kernel module (required).
96 /// - `author`: string literal of the author of the kernel module.
97 /// - `description`: string literal of the description of the kernel module.
98 /// - `license`: ASCII string literal of the license of the kernel module (required).
99 /// - `alias`: array of ASCII string literals of the alias names of the kernel module.
100 /// - `firmware`: array of ASCII string literals of the firmware files of
101 /// the kernel module.
103 pub fn module(ts: TokenStream) -> TokenStream {
107 /// Declares or implements a vtable trait.
109 /// Linux's use of pure vtables is very close to Rust traits, but they differ
110 /// in how unimplemented functions are represented. In Rust, traits can provide
111 /// default implementation for all non-required methods (and the default
112 /// implementation could just return `Error::EINVAL`); Linux typically use C
113 /// `NULL` pointers to represent these functions.
115 /// This attribute closes that gap. A trait can be annotated with the
116 /// `#[vtable]` attribute. Implementers of the trait will then also have to
117 /// annotate the trait with `#[vtable]`. This attribute generates a `HAS_*`
118 /// associated constant bool for each method in the trait that is set to true if
119 /// the implementer has overridden the associated method.
121 /// For a trait method to be optional, it must have a default implementation.
122 /// This is also the case for traits annotated with `#[vtable]`, but in this
123 /// case the default implementation will never be executed. The reason for this
124 /// is that the functions will be called through function pointers installed in
125 /// C side vtables. When an optional method is not implemented on a `#[vtable]`
126 /// trait, a NULL entry is installed in the vtable. Thus the default
127 /// implementation is never called. Since these traits are not designed to be
128 /// used on the Rust side, it should not be possible to call the default
129 /// implementation. This is done to ensure that we call the vtable methods
130 /// through the C vtable, and not through the Rust vtable. Therefore, the
131 /// default implementation should call `kernel::build_error`, which prevents
132 /// calls to this function at compile time:
135 /// # use kernel::error::VTABLE_DEFAULT_ERROR;
136 /// kernel::build_error(VTABLE_DEFAULT_ERROR)
139 /// Note that you might need to import [`kernel::error::VTABLE_DEFAULT_ERROR`].
141 /// This macro should not be used when all functions are required.
146 /// use kernel::error::VTABLE_DEFAULT_ERROR;
147 /// use kernel::prelude::*;
149 /// // Declares a `#[vtable]` trait
151 /// pub trait Operations: Send + Sync + Sized {
152 /// fn foo(&self) -> Result<()> {
153 /// kernel::build_error(VTABLE_DEFAULT_ERROR)
156 /// fn bar(&self) -> Result<()> {
157 /// kernel::build_error(VTABLE_DEFAULT_ERROR)
163 /// // Implements the `#[vtable]` trait
165 /// impl Operations for Foo {
166 /// fn foo(&self) -> Result<()> {
172 /// assert_eq!(<Foo as Operations>::HAS_FOO, true);
173 /// assert_eq!(<Foo as Operations>::HAS_BAR, false);
176 /// [`kernel::error::VTABLE_DEFAULT_ERROR`]: ../kernel/error/constant.VTABLE_DEFAULT_ERROR.html
177 #[proc_macro_attribute]
178 pub fn vtable(attr: TokenStream, ts: TokenStream) -> TokenStream {
179 vtable::vtable(attr, ts)
182 /// Concatenate two identifiers.
184 /// This is useful in macros that need to declare or reference items with names
185 /// starting with a fixed prefix and ending in a user specified name. The resulting
186 /// identifier has the span of the second argument.
191 /// use kernel::macro::concat_idents;
193 /// macro_rules! pub_no_prefix {
194 /// ($prefix:ident, $($newname:ident),+) => {
195 /// $(pub(crate) const $newname: u32 = kernel::macros::concat_idents!($prefix, $newname);)+
200 /// binder_driver_return_protocol_,
206 /// BR_TRANSACTION_COMPLETE,
214 /// BR_CLEAR_DEATH_NOTIFICATION_DONE,
218 /// assert_eq!(BR_OK, binder_driver_return_protocol_BR_OK);
221 pub fn concat_idents(ts: TokenStream) -> TokenStream {
222 concat_idents::concat_idents(ts)
225 /// Used to specify the pinning information of the fields of a struct.
227 /// This is somewhat similar in purpose as
228 /// [pin-project-lite](https://crates.io/crates/pin-project-lite).
229 /// Place this macro on a struct definition and then `#[pin]` in front of the attributes of each
230 /// field you want to structurally pin.
232 /// This macro enables the use of the [`pin_init!`] macro. When pin-initializing a `struct`,
233 /// then `#[pin]` directs the type of initializer that is required.
235 /// If your `struct` implements `Drop`, then you need to add `PinnedDrop` as arguments to this
236 /// macro, and change your `Drop` implementation to `PinnedDrop` annotated with
237 /// `#[`[`macro@pinned_drop`]`]`, since dropping pinned values requires extra care.
243 /// struct DriverData {
245 /// queue: Mutex<Vec<Command>>,
246 /// buf: Box<[u8; 1024 * 1024]>,
251 /// #[pin_data(PinnedDrop)]
252 /// struct DriverData {
254 /// queue: Mutex<Vec<Command>>,
255 /// buf: Box<[u8; 1024 * 1024]>,
256 /// raw_info: *mut Info,
260 /// impl PinnedDrop for DriverData {
261 /// fn drop(self: Pin<&mut Self>) {
262 /// unsafe { bindings::destroy_info(self.raw_info) };
267 /// [`pin_init!`]: ../kernel/macro.pin_init.html
268 // ^ cannot use direct link, since `kernel` is not a dependency of `macros`.
269 #[proc_macro_attribute]
270 pub fn pin_data(inner: TokenStream, item: TokenStream) -> TokenStream {
271 pin_data::pin_data(inner, item)
274 /// Used to implement `PinnedDrop` safely.
276 /// Only works on structs that are annotated via `#[`[`macro@pin_data`]`]`.
281 /// #[pin_data(PinnedDrop)]
282 /// struct DriverData {
284 /// queue: Mutex<Vec<Command>>,
285 /// buf: Box<[u8; 1024 * 1024]>,
286 /// raw_info: *mut Info,
290 /// impl PinnedDrop for DriverData {
291 /// fn drop(self: Pin<&mut Self>) {
292 /// unsafe { bindings::destroy_info(self.raw_info) };
296 #[proc_macro_attribute]
297 pub fn pinned_drop(args: TokenStream, input: TokenStream) -> TokenStream {
298 pinned_drop::pinned_drop(args, input)
301 /// Paste identifiers together.
303 /// Within the `paste!` macro, identifiers inside `[<` and `>]` are concatenated together to form a
304 /// single identifier.
306 /// This is similar to the [`paste`] crate, but with pasting feature limited to identifiers and
307 /// literals (lifetimes and documentation strings are not supported). There is a difference in
308 /// supported modifiers as well.
313 /// use kernel::macro::paste;
315 /// macro_rules! pub_no_prefix {
316 /// ($prefix:ident, $($newname:ident),+) => {
318 /// $(pub(crate) const $newname: u32 = [<$prefix $newname>];)+
324 /// binder_driver_return_protocol_,
330 /// BR_TRANSACTION_COMPLETE,
338 /// BR_CLEAR_DEATH_NOTIFICATION_DONE,
342 /// assert_eq!(BR_OK, binder_driver_return_protocol_BR_OK);
347 /// For each identifier, it is possible to attach one or multiple modifiers to
350 /// Currently supported modifiers are:
351 /// * `span`: change the span of concatenated identifier to the span of the specified token. By
352 /// default the span of the `[< >]` group is used.
353 /// * `lower`: change the identifier to lower case.
354 /// * `upper`: change the identifier to upper case.
357 /// use kernel::macro::paste;
359 /// macro_rules! pub_no_prefix {
360 /// ($prefix:ident, $($newname:ident),+) => {
361 /// kernel::macros::paste! {
362 /// $(pub(crate) const fn [<$newname:lower:span>]: u32 = [<$prefix $newname:span>];)+
368 /// binder_driver_return_protocol_,
374 /// BR_TRANSACTION_COMPLETE,
382 /// BR_CLEAR_DEATH_NOTIFICATION_DONE,
386 /// assert_eq!(br_ok(), binder_driver_return_protocol_BR_OK);
391 /// Literals can also be concatenated with other identifiers:
394 /// macro_rules! create_numbered_fn {
395 /// ($name:literal, $val:literal) => {
396 /// kernel::macros::paste! {
397 /// fn [<some_ $name _fn $val>]() -> u32 { $val }
402 /// create_numbered_fn!("foo", 100);
404 /// assert_eq!(some_foo_fn100(), 100)
407 /// [`paste`]: https://docs.rs/paste/
409 pub fn paste(input: TokenStream) -> TokenStream {
410 let mut tokens = input.into_iter().collect();
411 paste::expand(&mut tokens);
412 tokens.into_iter().collect()
415 /// Derives the [`Zeroable`] trait for the given struct.
417 /// This can only be used for structs where every field implements the [`Zeroable`] trait.
422 /// #[derive(Zeroable)]
423 /// pub struct DriverData {
425 /// buf_ptr: *mut u8,
429 #[proc_macro_derive(Zeroable)]
430 pub fn derive_zeroable(input: TokenStream) -> TokenStream {
431 zeroable::derive(input)