xref: /linux/rust/macros/lib.rs (revision 5f160950a5cdc36f222299905e09a72f67ebfcd4)
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 /// ```
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(ts: TokenStream) -> TokenStream {
135     module::module(ts.into()).into()
136 }
137 
138 /// Declares or implements a vtable trait.
139 ///
140 /// Linux's use of pure vtables is very close to Rust traits, but they differ
141 /// in how unimplemented functions are represented. In Rust, traits can provide
142 /// default implementation for all non-required methods (and the default
143 /// implementation could just return `Error::EINVAL`); Linux typically use C
144 /// `NULL` pointers to represent these functions.
145 ///
146 /// This attribute closes that gap. A trait can be annotated with the
147 /// `#[vtable]` attribute. Implementers of the trait will then also have to
148 /// annotate the trait with `#[vtable]`. This attribute generates a `HAS_*`
149 /// associated constant bool for each method in the trait that is set to true if
150 /// the implementer has overridden the associated method.
151 ///
152 /// For a trait method to be optional, it must have a default implementation.
153 /// This is also the case for traits annotated with `#[vtable]`, but in this
154 /// case the default implementation will never be executed. The reason for this
155 /// is that the functions will be called through function pointers installed in
156 /// C side vtables. When an optional method is not implemented on a `#[vtable]`
157 /// trait, a `NULL` entry is installed in the vtable. Thus the default
158 /// implementation is never called. Since these traits are not designed to be
159 /// used on the Rust side, it should not be possible to call the default
160 /// implementation. This is done to ensure that we call the vtable methods
161 /// through the C vtable, and not through the Rust vtable. Therefore, the
162 /// default implementation should call `build_error!`, which prevents
163 /// calls to this function at compile time:
164 ///
165 /// ```compile_fail
166 /// # // Intentionally missing `use`s to simplify `rusttest`.
167 /// build_error!(VTABLE_DEFAULT_ERROR)
168 /// ```
169 ///
170 /// Note that you might need to import [`kernel::error::VTABLE_DEFAULT_ERROR`].
171 ///
172 /// This macro should not be used when all functions are required.
173 ///
174 /// # Examples
175 ///
176 /// ```
177 /// use kernel::error::VTABLE_DEFAULT_ERROR;
178 /// use kernel::prelude::*;
179 ///
180 /// // Declares a `#[vtable]` trait
181 /// #[vtable]
182 /// pub trait Operations: Send + Sync + Sized {
183 ///     fn foo(&self) -> Result<()> {
184 ///         build_error!(VTABLE_DEFAULT_ERROR)
185 ///     }
186 ///
187 ///     fn bar(&self) -> Result<()> {
188 ///         build_error!(VTABLE_DEFAULT_ERROR)
189 ///     }
190 /// }
191 ///
192 /// struct Foo;
193 ///
194 /// // Implements the `#[vtable]` trait
195 /// #[vtable]
196 /// impl Operations for Foo {
197 ///     fn foo(&self) -> Result<()> {
198 /// #        Err(EINVAL)
199 ///         // ...
200 ///     }
201 /// }
202 ///
203 /// assert_eq!(<Foo as Operations>::HAS_FOO, true);
204 /// assert_eq!(<Foo as Operations>::HAS_BAR, false);
205 /// ```
206 ///
207 /// [`kernel::error::VTABLE_DEFAULT_ERROR`]: ../kernel/error/constant.VTABLE_DEFAULT_ERROR.html
208 #[proc_macro_attribute]
209 pub fn vtable(attr: TokenStream, input: TokenStream) -> TokenStream {
210     parse_macro_input!(attr as syn::parse::Nothing);
211     vtable::vtable(parse_macro_input!(input))
212         .unwrap_or_else(|e| e.into_compile_error())
213         .into()
214 }
215 
216 /// Export a function so that C code can call it via a header file.
217 ///
218 /// Functions exported using this macro can be called from C code using the declaration in the
219 /// appropriate header file. It should only be used in cases where C calls the function through a
220 /// header file; cases where C calls into Rust via a function pointer in a vtable (such as
221 /// `file_operations`) should not use this macro.
222 ///
223 /// This macro has the following effect:
224 ///
225 /// * Disables name mangling for this function.
226 /// * Verifies at compile-time that the function signature matches the declaration in the header
227 ///   file.
228 ///
229 /// You must declare the signature of the Rust function in a header file that is included by
230 /// `rust/bindings/bindings_helper.h`.
231 ///
232 /// This macro is *not* the same as the C macros `EXPORT_SYMBOL_*`. All Rust symbols are currently
233 /// automatically exported with `EXPORT_SYMBOL_GPL`.
234 #[proc_macro_attribute]
235 pub fn export(attr: TokenStream, ts: TokenStream) -> TokenStream {
236     export::export(attr.into(), ts.into()).into()
237 }
238 
239 /// Like [`core::format_args!`], but automatically wraps arguments in [`kernel::fmt::Adapter`].
240 ///
241 /// This macro allows generating `fmt::Arguments` while ensuring that each argument is wrapped with
242 /// `::kernel::fmt::Adapter`, which customizes formatting behavior for kernel logging.
243 ///
244 /// Named arguments used in the format string (e.g. `{foo}`) are detected and resolved from local
245 /// bindings. All positional and named arguments are automatically wrapped.
246 ///
247 /// This macro is an implementation detail of other kernel logging macros like [`pr_info!`] and
248 /// should not typically be used directly.
249 ///
250 /// [`kernel::fmt::Adapter`]: ../kernel/fmt/struct.Adapter.html
251 /// [`pr_info!`]: ../kernel/macro.pr_info.html
252 #[proc_macro]
253 pub fn fmt(input: TokenStream) -> TokenStream {
254     fmt::fmt(input.into()).into()
255 }
256 
257 /// Concatenate two identifiers.
258 ///
259 /// This is useful in macros that need to declare or reference items with names
260 /// starting with a fixed prefix and ending in a user specified name. The resulting
261 /// identifier has the span of the second argument.
262 ///
263 /// # Examples
264 ///
265 /// ```
266 /// # const binder_driver_return_protocol_BR_OK: u32 = 0;
267 /// # const binder_driver_return_protocol_BR_ERROR: u32 = 1;
268 /// # const binder_driver_return_protocol_BR_TRANSACTION: u32 = 2;
269 /// # const binder_driver_return_protocol_BR_REPLY: u32 = 3;
270 /// # const binder_driver_return_protocol_BR_DEAD_REPLY: u32 = 4;
271 /// # const binder_driver_return_protocol_BR_TRANSACTION_COMPLETE: u32 = 5;
272 /// # const binder_driver_return_protocol_BR_INCREFS: u32 = 6;
273 /// # const binder_driver_return_protocol_BR_ACQUIRE: u32 = 7;
274 /// # const binder_driver_return_protocol_BR_RELEASE: u32 = 8;
275 /// # const binder_driver_return_protocol_BR_DECREFS: u32 = 9;
276 /// # const binder_driver_return_protocol_BR_NOOP: u32 = 10;
277 /// # const binder_driver_return_protocol_BR_SPAWN_LOOPER: u32 = 11;
278 /// # const binder_driver_return_protocol_BR_DEAD_BINDER: u32 = 12;
279 /// # const binder_driver_return_protocol_BR_CLEAR_DEATH_NOTIFICATION_DONE: u32 = 13;
280 /// # const binder_driver_return_protocol_BR_FAILED_REPLY: u32 = 14;
281 /// use kernel::macros::concat_idents;
282 ///
283 /// macro_rules! pub_no_prefix {
284 ///     ($prefix:ident, $($newname:ident),+) => {
285 ///         $(pub(crate) const $newname: u32 = concat_idents!($prefix, $newname);)+
286 ///     };
287 /// }
288 ///
289 /// pub_no_prefix!(
290 ///     binder_driver_return_protocol_,
291 ///     BR_OK,
292 ///     BR_ERROR,
293 ///     BR_TRANSACTION,
294 ///     BR_REPLY,
295 ///     BR_DEAD_REPLY,
296 ///     BR_TRANSACTION_COMPLETE,
297 ///     BR_INCREFS,
298 ///     BR_ACQUIRE,
299 ///     BR_RELEASE,
300 ///     BR_DECREFS,
301 ///     BR_NOOP,
302 ///     BR_SPAWN_LOOPER,
303 ///     BR_DEAD_BINDER,
304 ///     BR_CLEAR_DEATH_NOTIFICATION_DONE,
305 ///     BR_FAILED_REPLY
306 /// );
307 ///
308 /// assert_eq!(BR_OK, binder_driver_return_protocol_BR_OK);
309 /// ```
310 #[proc_macro]
311 pub fn concat_idents(ts: TokenStream) -> TokenStream {
312     concat_idents::concat_idents(ts.into()).into()
313 }
314 
315 /// Paste identifiers together.
316 ///
317 /// Within the `paste!` macro, identifiers inside `[<` and `>]` are concatenated together to form a
318 /// single identifier.
319 ///
320 /// This is similar to the [`paste`] crate, but with pasting feature limited to identifiers and
321 /// literals (lifetimes and documentation strings are not supported). There is a difference in
322 /// supported modifiers as well.
323 ///
324 /// # Examples
325 ///
326 /// ```
327 /// # const binder_driver_return_protocol_BR_OK: u32 = 0;
328 /// # const binder_driver_return_protocol_BR_ERROR: u32 = 1;
329 /// # const binder_driver_return_protocol_BR_TRANSACTION: u32 = 2;
330 /// # const binder_driver_return_protocol_BR_REPLY: u32 = 3;
331 /// # const binder_driver_return_protocol_BR_DEAD_REPLY: u32 = 4;
332 /// # const binder_driver_return_protocol_BR_TRANSACTION_COMPLETE: u32 = 5;
333 /// # const binder_driver_return_protocol_BR_INCREFS: u32 = 6;
334 /// # const binder_driver_return_protocol_BR_ACQUIRE: u32 = 7;
335 /// # const binder_driver_return_protocol_BR_RELEASE: u32 = 8;
336 /// # const binder_driver_return_protocol_BR_DECREFS: u32 = 9;
337 /// # const binder_driver_return_protocol_BR_NOOP: u32 = 10;
338 /// # const binder_driver_return_protocol_BR_SPAWN_LOOPER: u32 = 11;
339 /// # const binder_driver_return_protocol_BR_DEAD_BINDER: u32 = 12;
340 /// # const binder_driver_return_protocol_BR_CLEAR_DEATH_NOTIFICATION_DONE: u32 = 13;
341 /// # const binder_driver_return_protocol_BR_FAILED_REPLY: u32 = 14;
342 /// macro_rules! pub_no_prefix {
343 ///     ($prefix:ident, $($newname:ident),+) => {
344 ///         ::kernel::macros::paste! {
345 ///             $(pub(crate) const $newname: u32 = [<$prefix $newname>];)+
346 ///         }
347 ///     };
348 /// }
349 ///
350 /// pub_no_prefix!(
351 ///     binder_driver_return_protocol_,
352 ///     BR_OK,
353 ///     BR_ERROR,
354 ///     BR_TRANSACTION,
355 ///     BR_REPLY,
356 ///     BR_DEAD_REPLY,
357 ///     BR_TRANSACTION_COMPLETE,
358 ///     BR_INCREFS,
359 ///     BR_ACQUIRE,
360 ///     BR_RELEASE,
361 ///     BR_DECREFS,
362 ///     BR_NOOP,
363 ///     BR_SPAWN_LOOPER,
364 ///     BR_DEAD_BINDER,
365 ///     BR_CLEAR_DEATH_NOTIFICATION_DONE,
366 ///     BR_FAILED_REPLY
367 /// );
368 ///
369 /// assert_eq!(BR_OK, binder_driver_return_protocol_BR_OK);
370 /// ```
371 ///
372 /// # Modifiers
373 ///
374 /// For each identifier, it is possible to attach one or multiple modifiers to
375 /// it.
376 ///
377 /// Currently supported modifiers are:
378 /// * `span`: change the span of concatenated identifier to the span of the specified token. By
379 ///   default the span of the `[< >]` group is used.
380 /// * `lower`: change the identifier to lower case.
381 /// * `upper`: change the identifier to upper case.
382 ///
383 /// ```
384 /// # const binder_driver_return_protocol_BR_OK: u32 = 0;
385 /// # const binder_driver_return_protocol_BR_ERROR: u32 = 1;
386 /// # const binder_driver_return_protocol_BR_TRANSACTION: u32 = 2;
387 /// # const binder_driver_return_protocol_BR_REPLY: u32 = 3;
388 /// # const binder_driver_return_protocol_BR_DEAD_REPLY: u32 = 4;
389 /// # const binder_driver_return_protocol_BR_TRANSACTION_COMPLETE: u32 = 5;
390 /// # const binder_driver_return_protocol_BR_INCREFS: u32 = 6;
391 /// # const binder_driver_return_protocol_BR_ACQUIRE: u32 = 7;
392 /// # const binder_driver_return_protocol_BR_RELEASE: u32 = 8;
393 /// # const binder_driver_return_protocol_BR_DECREFS: u32 = 9;
394 /// # const binder_driver_return_protocol_BR_NOOP: u32 = 10;
395 /// # const binder_driver_return_protocol_BR_SPAWN_LOOPER: u32 = 11;
396 /// # const binder_driver_return_protocol_BR_DEAD_BINDER: u32 = 12;
397 /// # const binder_driver_return_protocol_BR_CLEAR_DEATH_NOTIFICATION_DONE: u32 = 13;
398 /// # const binder_driver_return_protocol_BR_FAILED_REPLY: u32 = 14;
399 /// macro_rules! pub_no_prefix {
400 ///     ($prefix:ident, $($newname:ident),+) => {
401 ///         ::kernel::macros::paste! {
402 ///             $(pub(crate) const fn [<$newname:lower:span>]() -> u32 { [<$prefix $newname:span>] })+
403 ///         }
404 ///     };
405 /// }
406 ///
407 /// pub_no_prefix!(
408 ///     binder_driver_return_protocol_,
409 ///     BR_OK,
410 ///     BR_ERROR,
411 ///     BR_TRANSACTION,
412 ///     BR_REPLY,
413 ///     BR_DEAD_REPLY,
414 ///     BR_TRANSACTION_COMPLETE,
415 ///     BR_INCREFS,
416 ///     BR_ACQUIRE,
417 ///     BR_RELEASE,
418 ///     BR_DECREFS,
419 ///     BR_NOOP,
420 ///     BR_SPAWN_LOOPER,
421 ///     BR_DEAD_BINDER,
422 ///     BR_CLEAR_DEATH_NOTIFICATION_DONE,
423 ///     BR_FAILED_REPLY
424 /// );
425 ///
426 /// assert_eq!(br_ok(), binder_driver_return_protocol_BR_OK);
427 /// ```
428 ///
429 /// # Literals
430 ///
431 /// Literals can also be concatenated with other identifiers:
432 ///
433 /// ```
434 /// macro_rules! create_numbered_fn {
435 ///     ($name:literal, $val:literal) => {
436 ///         ::kernel::macros::paste! {
437 ///             fn [<some_ $name _fn $val>]() -> u32 { $val }
438 ///         }
439 ///     };
440 /// }
441 ///
442 /// create_numbered_fn!("foo", 100);
443 ///
444 /// assert_eq!(some_foo_fn100(), 100)
445 /// ```
446 ///
447 /// [`paste`]: https://docs.rs/paste/
448 #[proc_macro]
449 pub fn paste(input: TokenStream) -> TokenStream {
450     let mut tokens = proc_macro2::TokenStream::from(input).into_iter().collect();
451     paste::expand(&mut tokens);
452     tokens
453         .into_iter()
454         .collect::<proc_macro2::TokenStream>()
455         .into()
456 }
457 
458 /// Registers a KUnit test suite and its test cases using a user-space like syntax.
459 ///
460 /// This macro should be used on modules. If `CONFIG_KUNIT` (in `.config`) is `n`, the target module
461 /// is ignored.
462 ///
463 /// # Examples
464 ///
465 /// ```ignore
466 /// # use kernel::prelude::*;
467 /// #[kunit_tests(kunit_test_suit_name)]
468 /// mod tests {
469 ///     #[test]
470 ///     fn foo() {
471 ///         assert_eq!(1, 1);
472 ///     }
473 ///
474 ///     #[test]
475 ///     fn bar() {
476 ///         assert_eq!(2, 2);
477 ///     }
478 /// }
479 /// ```
480 #[proc_macro_attribute]
481 pub fn kunit_tests(attr: TokenStream, ts: TokenStream) -> TokenStream {
482     kunit::kunit_tests(attr.into(), ts.into()).into()
483 }
484