Skip to main content

macros/
lib.rs

1// SPDX-License-Identifier: GPL-2.0
2
3//! Crate for all kernel procedural macros.
4
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.
8
9// Stable since Rust 1.87.0.
10#![feature(extract_if)]
11//
12// Stable since Rust 1.88.0 under a different name, `proc_macro_span_file`,
13// which was added in Rust 1.88.0. This is why `cfg_attr` is used here, i.e.
14// to avoid depending on the full `proc_macro_span` on Rust >= 1.88.0.
15#![cfg_attr(not(CONFIG_RUSTC_HAS_SPAN_FILE), feature(proc_macro_span))]
16
17mod concat_idents;
18mod export;
19mod fmt;
20mod for_lt;
21mod helpers;
22mod io;
23mod kunit;
24mod module;
25mod paste;
26mod vtable;
27
28use proc_macro::TokenStream;
29
30use syn::parse_macro_input;
31
32/// Declares a kernel module.
33///
34/// The `type` argument should be a type which implements the [`Module`]
35/// trait. Also accepts various forms of kernel metadata.
36///
37/// The `params` field describe module parameters. Each entry has the form
38///
39/// ```ignore
40/// parameter_name: type {
41///     default: default_value,
42///     description: "Description",
43/// }
44/// ```
45///
46/// `type` may be one of
47///
48/// - [`i8`]
49/// - [`u8`]
50/// - [`i8`]
51/// - [`u8`]
52/// - [`i16`]
53/// - [`u16`]
54/// - [`i32`]
55/// - [`u32`]
56/// - [`i64`]
57/// - [`u64`]
58/// - [`isize`]
59/// - [`usize`]
60/// - [`bool`]
61///
62/// C header: [`include/linux/moduleparam.h`](srctree/include/linux/moduleparam.h)
63///
64/// [`Module`]: ../kernel/trait.Module.html
65///
66/// # Examples
67///
68/// ```ignore
69/// use kernel::prelude::*;
70///
71/// module!{
72///     type: MyModule,
73///     name: "my_kernel_module",
74///     authors: ["Rust for Linux Contributors"],
75///     description: "My very own kernel module!",
76///     license: "GPL",
77///     alias: ["alternate_module_name"],
78///     params: {
79///         my_parameter: i64 {
80///             default: 1,
81///             description: "This parameter has a default of 1",
82///         },
83///     },
84/// }
85///
86/// struct MyModule(i32);
87///
88/// impl kernel::Module for MyModule {
89///     fn init(_module: &'static ThisModule) -> Result<Self> {
90///         let foo: i32 = 42;
91///         pr_info!("I contain:  {}\n", foo);
92///         pr_info!("i32 param is:  {}\n", module_parameters::my_parameter.read());
93///         Ok(Self(foo))
94///     }
95/// }
96/// # fn main() {}
97/// ```
98///
99/// ## Firmware
100///
101/// The following example shows how to declare a kernel module that needs
102/// to load binary firmware files. You need to specify the file names of
103/// the firmware in the `firmware` field. The information is embedded
104/// in the `modinfo` section of the kernel module. For example, a tool to
105/// build an initramfs uses this information to put the firmware files into
106/// the initramfs image.
107///
108/// ```
109/// use kernel::prelude::*;
110///
111/// module!{
112///     type: MyDeviceDriverModule,
113///     name: "my_device_driver_module",
114///     authors: ["Rust for Linux Contributors"],
115///     description: "My device driver requires firmware",
116///     license: "GPL",
117///     firmware: ["my_device_firmware1.bin", "my_device_firmware2.bin"],
118/// }
119///
120/// struct MyDeviceDriverModule;
121///
122/// impl kernel::Module for MyDeviceDriverModule {
123///     fn init(_module: &'static ThisModule) -> Result<Self> {
124///         Ok(Self)
125///     }
126/// }
127/// # fn main() {}
128/// ```
129///
130/// # Supported argument types
131///   - `type`: type which implements the [`Module`] trait (required).
132///   - `name`: ASCII string literal of the name of the kernel module (required).
133///   - `authors`: array of ASCII string literals of the authors of the kernel module.
134///   - `description`: string literal of the description of the kernel module.
135///   - `license`: ASCII string literal of the license of the kernel module (required).
136///   - `alias`: array of ASCII string literals of the alias names of the kernel module.
137///   - `firmware`: array of ASCII string literals of the firmware files of
138///     the kernel module.
139#[proc_macro]
140pub fn module(input: TokenStream) -> TokenStream {
141    module::module(parse_macro_input!(input))
142        .unwrap_or_else(|e| e.into_compile_error())
143        .into()
144}
145
146/// Declares or implements a vtable trait.
147///
148/// Linux's use of pure vtables is very close to Rust traits, but they differ
149/// in how unimplemented functions are represented. In Rust, traits can provide
150/// default implementation for all non-required methods (and the default
151/// implementation could just return `Error::EINVAL`); Linux typically use C
152/// `NULL` pointers to represent these functions.
153///
154/// This attribute closes that gap. A trait can be annotated with the
155/// `#[vtable]` attribute. Implementers of the trait will then also have to
156/// annotate the trait with `#[vtable]`. This attribute generates a `HAS_*`
157/// associated constant bool for each method in the trait that is set to true if
158/// the implementer has overridden the associated method.
159///
160/// For a trait method to be optional, it must have a default implementation.
161/// This is also the case for traits annotated with `#[vtable]`, but in this
162/// case the default implementation will never be executed. The reason for this
163/// is that the functions will be called through function pointers installed in
164/// C side vtables. When an optional method is not implemented on a `#[vtable]`
165/// trait, a `NULL` entry is installed in the vtable. Thus the default
166/// implementation is never called. Since these traits are not designed to be
167/// used on the Rust side, it should not be possible to call the default
168/// implementation. This is done to ensure that we call the vtable methods
169/// through the C vtable, and not through the Rust vtable. Therefore, the
170/// default implementation should call `build_error!`, which prevents
171/// calls to this function at compile time:
172///
173/// ```compile_fail
174/// # // Intentionally missing `use`s to simplify `rusttest`.
175/// build_error!(VTABLE_DEFAULT_ERROR)
176/// ```
177///
178/// Note that you might need to import [`kernel::error::VTABLE_DEFAULT_ERROR`].
179///
180/// This macro should not be used when all functions are required.
181///
182/// Additionally, this macro automatically handles the `OwnerModule`
183/// associated type: on the trait side, `type OwnerModule: ModuleMetadata;`
184/// is added as a required associated type if not already defined; on the
185/// impl side, `type OwnerModule = LocalModule;` is automatically inserted
186/// if not explicitly defined.
187///
188/// # Examples
189///
190/// ```
191/// use kernel::error::VTABLE_DEFAULT_ERROR;
192/// use kernel::prelude::*;
193///
194/// # struct LocalModule;
195/// # impl kernel::ModuleMetadata for LocalModule {
196/// #     const NAME: &'static kernel::str::CStr = c"vtable_doctest";
197/// #
198/// #     // SAFETY: This doctest runs on the host: there is no `THIS_MODULE`.
199/// #     const THIS_MODULE: kernel::ThisModule = unsafe {
200/// #         kernel::ThisModule::from_ptr(core::ptr::null_mut())
201/// #     };
202/// # }
203/// #
204/// # fn main() {
205/// // Declares a `#[vtable]` trait
206/// #[vtable]
207/// pub trait Operations: Send + Sync + Sized {
208///     fn foo(&self) -> Result<()> {
209///         build_error!(VTABLE_DEFAULT_ERROR)
210///     }
211///
212///     fn bar(&self) -> Result<()> {
213///         build_error!(VTABLE_DEFAULT_ERROR)
214///     }
215/// }
216///
217/// struct Foo;
218///
219/// // Implements the `#[vtable]` trait
220/// #[vtable]
221/// impl Operations for Foo {
222///     fn foo(&self) -> Result<()> {
223/// #        Err(EINVAL)
224///         // ...
225///     }
226/// }
227///
228/// assert_eq!(<Foo as Operations>::HAS_FOO, true);
229/// assert_eq!(<Foo as Operations>::HAS_BAR, false);
230/// # }
231/// ```
232///
233/// [`kernel::error::VTABLE_DEFAULT_ERROR`]: ../kernel/error/constant.VTABLE_DEFAULT_ERROR.html
234#[proc_macro_attribute]
235pub fn vtable(attr: TokenStream, input: TokenStream) -> TokenStream {
236    parse_macro_input!(attr as syn::parse::Nothing);
237    vtable::vtable(parse_macro_input!(input))
238        .unwrap_or_else(|e| e.into_compile_error())
239        .into()
240}
241
242/// Export a function so that C code can call it via a header file.
243///
244/// Functions exported using this macro can be called from C code using the declaration in the
245/// appropriate header file. It should only be used in cases where C calls the function through a
246/// header file; cases where C calls into Rust via a function pointer in a vtable (such as
247/// `file_operations`) should not use this macro.
248///
249/// This macro has the following effect:
250///
251/// * Disables name mangling for this function.
252/// * Verifies at compile-time that the function signature matches the declaration in the header
253///   file.
254///
255/// You must declare the signature of the Rust function in a header file that is included by
256/// `rust/bindings/bindings_helper.h`.
257///
258/// This macro is *not* the same as the C macros `EXPORT_SYMBOL_*`. All Rust symbols are currently
259/// automatically exported with `EXPORT_SYMBOL_GPL`.
260#[proc_macro_attribute]
261pub fn export(attr: TokenStream, input: TokenStream) -> TokenStream {
262    parse_macro_input!(attr as syn::parse::Nothing);
263    export::export(parse_macro_input!(input)).into()
264}
265
266/// Like [`core::format_args!`], but automatically wraps arguments in [`kernel::fmt::Adapter`].
267///
268/// This macro allows generating `fmt::Arguments` while ensuring that each argument is wrapped with
269/// `::kernel::fmt::Adapter`, which customizes formatting behavior for kernel logging.
270///
271/// Named arguments used in the format string (e.g. `{foo}`) are detected and resolved from local
272/// bindings. All positional and named arguments are automatically wrapped.
273///
274/// This macro is an implementation detail of other kernel logging macros like [`pr_info!`] and
275/// should not typically be used directly.
276///
277/// [`kernel::fmt::Adapter`]: ../kernel/fmt/struct.Adapter.html
278/// [`pr_info!`]: ../kernel/macro.pr_info.html
279#[proc_macro]
280pub fn fmt(input: TokenStream) -> TokenStream {
281    fmt::fmt(input.into()).into()
282}
283
284/// Concatenate two identifiers.
285///
286/// This is useful in macros that need to declare or reference items with names
287/// starting with a fixed prefix and ending in a user specified name. The resulting
288/// identifier has the span of the second argument.
289///
290/// # Examples
291///
292/// ```
293/// # const binder_driver_return_protocol_BR_OK: u32 = 0;
294/// # const binder_driver_return_protocol_BR_ERROR: u32 = 1;
295/// # const binder_driver_return_protocol_BR_TRANSACTION: u32 = 2;
296/// # const binder_driver_return_protocol_BR_REPLY: u32 = 3;
297/// # const binder_driver_return_protocol_BR_DEAD_REPLY: u32 = 4;
298/// # const binder_driver_return_protocol_BR_TRANSACTION_COMPLETE: u32 = 5;
299/// # const binder_driver_return_protocol_BR_INCREFS: u32 = 6;
300/// # const binder_driver_return_protocol_BR_ACQUIRE: u32 = 7;
301/// # const binder_driver_return_protocol_BR_RELEASE: u32 = 8;
302/// # const binder_driver_return_protocol_BR_DECREFS: u32 = 9;
303/// # const binder_driver_return_protocol_BR_NOOP: u32 = 10;
304/// # const binder_driver_return_protocol_BR_SPAWN_LOOPER: u32 = 11;
305/// # const binder_driver_return_protocol_BR_DEAD_BINDER: u32 = 12;
306/// # const binder_driver_return_protocol_BR_CLEAR_DEATH_NOTIFICATION_DONE: u32 = 13;
307/// # const binder_driver_return_protocol_BR_FAILED_REPLY: u32 = 14;
308/// use kernel::macros::concat_idents;
309///
310/// macro_rules! pub_no_prefix {
311///     ($prefix:ident, $($newname:ident),+) => {
312///         $(pub(crate) const $newname: u32 = concat_idents!($prefix, $newname);)+
313///     };
314/// }
315///
316/// pub_no_prefix!(
317///     binder_driver_return_protocol_,
318///     BR_OK,
319///     BR_ERROR,
320///     BR_TRANSACTION,
321///     BR_REPLY,
322///     BR_DEAD_REPLY,
323///     BR_TRANSACTION_COMPLETE,
324///     BR_INCREFS,
325///     BR_ACQUIRE,
326///     BR_RELEASE,
327///     BR_DECREFS,
328///     BR_NOOP,
329///     BR_SPAWN_LOOPER,
330///     BR_DEAD_BINDER,
331///     BR_CLEAR_DEATH_NOTIFICATION_DONE,
332///     BR_FAILED_REPLY
333/// );
334///
335/// assert_eq!(BR_OK, binder_driver_return_protocol_BR_OK);
336/// ```
337#[proc_macro]
338pub fn concat_idents(input: TokenStream) -> TokenStream {
339    concat_idents::concat_idents(parse_macro_input!(input)).into()
340}
341
342/// Paste identifiers together.
343///
344/// Within the `paste!` macro, identifiers inside `[<` and `>]` are concatenated together to form a
345/// single identifier.
346///
347/// This is similar to the [`paste`] crate, but with pasting feature limited to identifiers and
348/// literals (lifetimes and documentation strings are not supported). There is a difference in
349/// supported modifiers as well.
350///
351/// # Examples
352///
353/// ```
354/// # const binder_driver_return_protocol_BR_OK: u32 = 0;
355/// # const binder_driver_return_protocol_BR_ERROR: u32 = 1;
356/// # const binder_driver_return_protocol_BR_TRANSACTION: u32 = 2;
357/// # const binder_driver_return_protocol_BR_REPLY: u32 = 3;
358/// # const binder_driver_return_protocol_BR_DEAD_REPLY: u32 = 4;
359/// # const binder_driver_return_protocol_BR_TRANSACTION_COMPLETE: u32 = 5;
360/// # const binder_driver_return_protocol_BR_INCREFS: u32 = 6;
361/// # const binder_driver_return_protocol_BR_ACQUIRE: u32 = 7;
362/// # const binder_driver_return_protocol_BR_RELEASE: u32 = 8;
363/// # const binder_driver_return_protocol_BR_DECREFS: u32 = 9;
364/// # const binder_driver_return_protocol_BR_NOOP: u32 = 10;
365/// # const binder_driver_return_protocol_BR_SPAWN_LOOPER: u32 = 11;
366/// # const binder_driver_return_protocol_BR_DEAD_BINDER: u32 = 12;
367/// # const binder_driver_return_protocol_BR_CLEAR_DEATH_NOTIFICATION_DONE: u32 = 13;
368/// # const binder_driver_return_protocol_BR_FAILED_REPLY: u32 = 14;
369/// macro_rules! pub_no_prefix {
370///     ($prefix:ident, $($newname:ident),+) => {
371///         ::kernel::macros::paste! {
372///             $(pub(crate) const $newname: u32 = [<$prefix $newname>];)+
373///         }
374///     };
375/// }
376///
377/// pub_no_prefix!(
378///     binder_driver_return_protocol_,
379///     BR_OK,
380///     BR_ERROR,
381///     BR_TRANSACTION,
382///     BR_REPLY,
383///     BR_DEAD_REPLY,
384///     BR_TRANSACTION_COMPLETE,
385///     BR_INCREFS,
386///     BR_ACQUIRE,
387///     BR_RELEASE,
388///     BR_DECREFS,
389///     BR_NOOP,
390///     BR_SPAWN_LOOPER,
391///     BR_DEAD_BINDER,
392///     BR_CLEAR_DEATH_NOTIFICATION_DONE,
393///     BR_FAILED_REPLY
394/// );
395///
396/// assert_eq!(BR_OK, binder_driver_return_protocol_BR_OK);
397/// ```
398///
399/// # Modifiers
400///
401/// For each identifier, it is possible to attach one or multiple modifiers to
402/// it.
403///
404/// Currently supported modifiers are:
405/// * `span`: change the span of concatenated identifier to the span of the specified token. By
406///   default the span of the `[< >]` group is used.
407/// * `lower`: change the identifier to lower case.
408/// * `upper`: change the identifier to upper case.
409///
410/// ```
411/// # const binder_driver_return_protocol_BR_OK: u32 = 0;
412/// # const binder_driver_return_protocol_BR_ERROR: u32 = 1;
413/// # const binder_driver_return_protocol_BR_TRANSACTION: u32 = 2;
414/// # const binder_driver_return_protocol_BR_REPLY: u32 = 3;
415/// # const binder_driver_return_protocol_BR_DEAD_REPLY: u32 = 4;
416/// # const binder_driver_return_protocol_BR_TRANSACTION_COMPLETE: u32 = 5;
417/// # const binder_driver_return_protocol_BR_INCREFS: u32 = 6;
418/// # const binder_driver_return_protocol_BR_ACQUIRE: u32 = 7;
419/// # const binder_driver_return_protocol_BR_RELEASE: u32 = 8;
420/// # const binder_driver_return_protocol_BR_DECREFS: u32 = 9;
421/// # const binder_driver_return_protocol_BR_NOOP: u32 = 10;
422/// # const binder_driver_return_protocol_BR_SPAWN_LOOPER: u32 = 11;
423/// # const binder_driver_return_protocol_BR_DEAD_BINDER: u32 = 12;
424/// # const binder_driver_return_protocol_BR_CLEAR_DEATH_NOTIFICATION_DONE: u32 = 13;
425/// # const binder_driver_return_protocol_BR_FAILED_REPLY: u32 = 14;
426/// macro_rules! pub_no_prefix {
427///     ($prefix:ident, $($newname:ident),+) => {
428///         ::kernel::macros::paste! {
429///             $(pub(crate) const fn [<$newname:lower:span>]() -> u32 { [<$prefix $newname:span>] })+
430///         }
431///     };
432/// }
433///
434/// pub_no_prefix!(
435///     binder_driver_return_protocol_,
436///     BR_OK,
437///     BR_ERROR,
438///     BR_TRANSACTION,
439///     BR_REPLY,
440///     BR_DEAD_REPLY,
441///     BR_TRANSACTION_COMPLETE,
442///     BR_INCREFS,
443///     BR_ACQUIRE,
444///     BR_RELEASE,
445///     BR_DECREFS,
446///     BR_NOOP,
447///     BR_SPAWN_LOOPER,
448///     BR_DEAD_BINDER,
449///     BR_CLEAR_DEATH_NOTIFICATION_DONE,
450///     BR_FAILED_REPLY
451/// );
452///
453/// assert_eq!(br_ok(), binder_driver_return_protocol_BR_OK);
454/// ```
455///
456/// # Literals
457///
458/// Literals can also be concatenated with other identifiers:
459///
460/// ```
461/// macro_rules! create_numbered_fn {
462///     ($name:literal, $val:literal) => {
463///         ::kernel::macros::paste! {
464///             fn [<some_ $name _fn $val>]() -> u32 { $val }
465///         }
466///     };
467/// }
468///
469/// create_numbered_fn!("foo", 100);
470///
471/// assert_eq!(some_foo_fn100(), 100)
472/// ```
473///
474/// [`paste`]: https://docs.rs/paste/
475#[proc_macro]
476pub fn paste(input: TokenStream) -> TokenStream {
477    let mut tokens = proc_macro2::TokenStream::from(input).into_iter().collect();
478    paste::expand(&mut tokens);
479    tokens
480        .into_iter()
481        .collect::<proc_macro2::TokenStream>()
482        .into()
483}
484
485#[doc(hidden)] // Documented in `kernel` crate.
486#[proc_macro]
487pub fn register(input: TokenStream) -> TokenStream {
488    io::register::register(parse_macro_input!(input))
489        .unwrap_or_else(|e| e.into_compile_error())
490        .into()
491}
492
493/// Registers a KUnit test suite and its test cases using a user-space like syntax.
494///
495/// This macro should be used on modules. If `CONFIG_KUNIT` (in `.config`) is `n`, the target module
496/// is ignored.
497///
498/// # Examples
499///
500/// ```ignore
501/// # use kernel::prelude::*;
502/// #[kunit_tests(kunit_test_suit_name)]
503/// mod tests {
504///     #[test]
505///     fn foo() {
506///         assert_eq!(1, 1);
507///     }
508///
509///     #[test]
510///     fn bar() {
511///         assert_eq!(2, 2);
512///     }
513/// }
514/// ```
515#[proc_macro_attribute]
516pub fn kunit_tests(attr: TokenStream, input: TokenStream) -> TokenStream {
517    kunit::kunit_tests(parse_macro_input!(attr), parse_macro_input!(input))
518        .unwrap_or_else(|e| e.into_compile_error())
519        .into()
520}
521
522/// Obtain a type that implements [`ForLt`] for the given higher-ranked type.
523///
524/// Please refer to the documentation of the [`ForLt`] trait.
525///
526/// [`ForLt`]: trait.ForLt.html
527#[proc_macro]
528#[allow(non_snake_case)]
529pub fn ForLt(input: TokenStream) -> TokenStream {
530    for_lt::for_lt(parse_macro_input!(input)).into()
531}
532
533/// Obtain a type that implements [`CovariantForLt`] (and [`ForLt`]) for the given higher-ranked
534/// type.
535///
536/// Unlike [`ForLt!`], this macro additionally proves that the type is covariant over the lifetime,
537/// providing a safe [`CovariantForLt::cast_ref`] method.
538///
539/// Please refer to the documentation of the [`CovariantForLt`] trait.
540///
541/// [`CovariantForLt`]: trait.CovariantForLt.html
542/// [`CovariantForLt::cast_ref`]: trait.CovariantForLt.html#method.cast_ref
543/// [`ForLt`]: trait.ForLt.html
544#[proc_macro]
545#[allow(non_snake_case)]
546pub fn CovariantForLt(input: TokenStream) -> TokenStream {
547    for_lt::covariant_for_lt(parse_macro_input!(input)).into()
548}