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