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