xref: /linux/rust/macros/lib.rs (revision 808c999fc9e7c366fd47da564e69d579c1dc8279)
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 #[macro_use]
15 mod quote;
16 mod concat_idents;
17 mod export;
18 mod fmt;
19 mod helpers;
20 mod kunit;
21 mod module;
22 mod paste;
23 mod vtable;
24 
25 use proc_macro::TokenStream;
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 /// C header: [`include/linux/moduleparam.h`](srctree/include/linux/moduleparam.h)
33 ///
34 /// [`Module`]: ../kernel/trait.Module.html
35 ///
36 /// # Examples
37 ///
38 /// ```
39 /// use kernel::prelude::*;
40 ///
41 /// module!{
42 ///     type: MyModule,
43 ///     name: "my_kernel_module",
44 ///     authors: ["Rust for Linux Contributors"],
45 ///     description: "My very own kernel module!",
46 ///     license: "GPL",
47 ///     alias: ["alternate_module_name"],
48 /// }
49 ///
50 /// struct MyModule(i32);
51 ///
52 /// impl kernel::Module for MyModule {
53 ///     fn init(_module: &'static ThisModule) -> Result<Self> {
54 ///         let foo: i32 = 42;
55 ///         pr_info!("I contain:  {}\n", foo);
56 ///         Ok(Self(foo))
57 ///     }
58 /// }
59 /// # fn main() {}
60 /// ```
61 ///
62 /// ## Firmware
63 ///
64 /// The following example shows how to declare a kernel module that needs
65 /// to load binary firmware files. You need to specify the file names of
66 /// the firmware in the `firmware` field. The information is embedded
67 /// in the `modinfo` section of the kernel module. For example, a tool to
68 /// build an initramfs uses this information to put the firmware files into
69 /// the initramfs image.
70 ///
71 /// ```
72 /// use kernel::prelude::*;
73 ///
74 /// module!{
75 ///     type: MyDeviceDriverModule,
76 ///     name: "my_device_driver_module",
77 ///     authors: ["Rust for Linux Contributors"],
78 ///     description: "My device driver requires firmware",
79 ///     license: "GPL",
80 ///     firmware: ["my_device_firmware1.bin", "my_device_firmware2.bin"],
81 /// }
82 ///
83 /// struct MyDeviceDriverModule;
84 ///
85 /// impl kernel::Module for MyDeviceDriverModule {
86 ///     fn init(_module: &'static ThisModule) -> Result<Self> {
87 ///         Ok(Self)
88 ///     }
89 /// }
90 /// # fn main() {}
91 /// ```
92 ///
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 ///   - `authors`: array of ASCII string literals of the authors 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.
102 #[proc_macro]
103 pub fn module(ts: TokenStream) -> TokenStream {
104     module::module(ts)
105 }
106 
107 /// Declares or implements a vtable trait.
108 ///
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.
114 ///
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.
120 ///
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 `build_error!`, which prevents
132 /// calls to this function at compile time:
133 ///
134 /// ```compile_fail
135 /// # // Intentionally missing `use`s to simplify `rusttest`.
136 /// build_error!(VTABLE_DEFAULT_ERROR)
137 /// ```
138 ///
139 /// Note that you might need to import [`kernel::error::VTABLE_DEFAULT_ERROR`].
140 ///
141 /// This macro should not be used when all functions are required.
142 ///
143 /// # Examples
144 ///
145 /// ```
146 /// use kernel::error::VTABLE_DEFAULT_ERROR;
147 /// use kernel::prelude::*;
148 ///
149 /// // Declares a `#[vtable]` trait
150 /// #[vtable]
151 /// pub trait Operations: Send + Sync + Sized {
152 ///     fn foo(&self) -> Result<()> {
153 ///         build_error!(VTABLE_DEFAULT_ERROR)
154 ///     }
155 ///
156 ///     fn bar(&self) -> Result<()> {
157 ///         build_error!(VTABLE_DEFAULT_ERROR)
158 ///     }
159 /// }
160 ///
161 /// struct Foo;
162 ///
163 /// // Implements the `#[vtable]` trait
164 /// #[vtable]
165 /// impl Operations for Foo {
166 ///     fn foo(&self) -> Result<()> {
167 /// #        Err(EINVAL)
168 ///         // ...
169 ///     }
170 /// }
171 ///
172 /// assert_eq!(<Foo as Operations>::HAS_FOO, true);
173 /// assert_eq!(<Foo as Operations>::HAS_BAR, false);
174 /// ```
175 ///
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)
180 }
181 
182 /// Export a function so that C code can call it via a header file.
183 ///
184 /// Functions exported using this macro can be called from C code using the declaration in the
185 /// appropriate header file. It should only be used in cases where C calls the function through a
186 /// header file; cases where C calls into Rust via a function pointer in a vtable (such as
187 /// `file_operations`) should not use this macro.
188 ///
189 /// This macro has the following effect:
190 ///
191 /// * Disables name mangling for this function.
192 /// * Verifies at compile-time that the function signature matches the declaration in the header
193 ///   file.
194 ///
195 /// You must declare the signature of the Rust function in a header file that is included by
196 /// `rust/bindings/bindings_helper.h`.
197 ///
198 /// This macro is *not* the same as the C macros `EXPORT_SYMBOL_*`. All Rust symbols are currently
199 /// automatically exported with `EXPORT_SYMBOL_GPL`.
200 #[proc_macro_attribute]
201 pub fn export(attr: TokenStream, ts: TokenStream) -> TokenStream {
202     export::export(attr, ts)
203 }
204 
205 /// Like [`core::format_args!`], but automatically wraps arguments in [`kernel::fmt::Adapter`].
206 ///
207 /// This macro allows generating `fmt::Arguments` while ensuring that each argument is wrapped with
208 /// `::kernel::fmt::Adapter`, which customizes formatting behavior for kernel logging.
209 ///
210 /// Named arguments used in the format string (e.g. `{foo}`) are detected and resolved from local
211 /// bindings. All positional and named arguments are automatically wrapped.
212 ///
213 /// This macro is an implementation detail of other kernel logging macros like [`pr_info!`] and
214 /// should not typically be used directly.
215 ///
216 /// [`kernel::fmt::Adapter`]: ../kernel/fmt/struct.Adapter.html
217 /// [`pr_info!`]: ../kernel/macro.pr_info.html
218 #[proc_macro]
219 pub fn fmt(input: TokenStream) -> TokenStream {
220     fmt::fmt(input)
221 }
222 
223 /// Concatenate two identifiers.
224 ///
225 /// This is useful in macros that need to declare or reference items with names
226 /// starting with a fixed prefix and ending in a user specified name. The resulting
227 /// identifier has the span of the second argument.
228 ///
229 /// # Examples
230 ///
231 /// ```
232 /// # const binder_driver_return_protocol_BR_OK: u32 = 0;
233 /// # const binder_driver_return_protocol_BR_ERROR: u32 = 1;
234 /// # const binder_driver_return_protocol_BR_TRANSACTION: u32 = 2;
235 /// # const binder_driver_return_protocol_BR_REPLY: u32 = 3;
236 /// # const binder_driver_return_protocol_BR_DEAD_REPLY: u32 = 4;
237 /// # const binder_driver_return_protocol_BR_TRANSACTION_COMPLETE: u32 = 5;
238 /// # const binder_driver_return_protocol_BR_INCREFS: u32 = 6;
239 /// # const binder_driver_return_protocol_BR_ACQUIRE: u32 = 7;
240 /// # const binder_driver_return_protocol_BR_RELEASE: u32 = 8;
241 /// # const binder_driver_return_protocol_BR_DECREFS: u32 = 9;
242 /// # const binder_driver_return_protocol_BR_NOOP: u32 = 10;
243 /// # const binder_driver_return_protocol_BR_SPAWN_LOOPER: u32 = 11;
244 /// # const binder_driver_return_protocol_BR_DEAD_BINDER: u32 = 12;
245 /// # const binder_driver_return_protocol_BR_CLEAR_DEATH_NOTIFICATION_DONE: u32 = 13;
246 /// # const binder_driver_return_protocol_BR_FAILED_REPLY: u32 = 14;
247 /// use kernel::macros::concat_idents;
248 ///
249 /// macro_rules! pub_no_prefix {
250 ///     ($prefix:ident, $($newname:ident),+) => {
251 ///         $(pub(crate) const $newname: u32 = concat_idents!($prefix, $newname);)+
252 ///     };
253 /// }
254 ///
255 /// pub_no_prefix!(
256 ///     binder_driver_return_protocol_,
257 ///     BR_OK,
258 ///     BR_ERROR,
259 ///     BR_TRANSACTION,
260 ///     BR_REPLY,
261 ///     BR_DEAD_REPLY,
262 ///     BR_TRANSACTION_COMPLETE,
263 ///     BR_INCREFS,
264 ///     BR_ACQUIRE,
265 ///     BR_RELEASE,
266 ///     BR_DECREFS,
267 ///     BR_NOOP,
268 ///     BR_SPAWN_LOOPER,
269 ///     BR_DEAD_BINDER,
270 ///     BR_CLEAR_DEATH_NOTIFICATION_DONE,
271 ///     BR_FAILED_REPLY
272 /// );
273 ///
274 /// assert_eq!(BR_OK, binder_driver_return_protocol_BR_OK);
275 /// ```
276 #[proc_macro]
277 pub fn concat_idents(ts: TokenStream) -> TokenStream {
278     concat_idents::concat_idents(ts)
279 }
280 
281 /// Paste identifiers together.
282 ///
283 /// Within the `paste!` macro, identifiers inside `[<` and `>]` are concatenated together to form a
284 /// single identifier.
285 ///
286 /// This is similar to the [`paste`] crate, but with pasting feature limited to identifiers and
287 /// literals (lifetimes and documentation strings are not supported). There is a difference in
288 /// supported modifiers as well.
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 /// macro_rules! pub_no_prefix {
309 ///     ($prefix:ident, $($newname:ident),+) => {
310 ///         ::kernel::macros::paste! {
311 ///             $(pub(crate) const $newname: u32 = [<$prefix $newname>];)+
312 ///         }
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 ///
338 /// # Modifiers
339 ///
340 /// For each identifier, it is possible to attach one or multiple modifiers to
341 /// it.
342 ///
343 /// Currently supported modifiers are:
344 /// * `span`: change the span of concatenated identifier to the span of the specified token. By
345 ///   default the span of the `[< >]` group is used.
346 /// * `lower`: change the identifier to lower case.
347 /// * `upper`: change the identifier to upper case.
348 ///
349 /// ```
350 /// # const binder_driver_return_protocol_BR_OK: u32 = 0;
351 /// # const binder_driver_return_protocol_BR_ERROR: u32 = 1;
352 /// # const binder_driver_return_protocol_BR_TRANSACTION: u32 = 2;
353 /// # const binder_driver_return_protocol_BR_REPLY: u32 = 3;
354 /// # const binder_driver_return_protocol_BR_DEAD_REPLY: u32 = 4;
355 /// # const binder_driver_return_protocol_BR_TRANSACTION_COMPLETE: u32 = 5;
356 /// # const binder_driver_return_protocol_BR_INCREFS: u32 = 6;
357 /// # const binder_driver_return_protocol_BR_ACQUIRE: u32 = 7;
358 /// # const binder_driver_return_protocol_BR_RELEASE: u32 = 8;
359 /// # const binder_driver_return_protocol_BR_DECREFS: u32 = 9;
360 /// # const binder_driver_return_protocol_BR_NOOP: u32 = 10;
361 /// # const binder_driver_return_protocol_BR_SPAWN_LOOPER: u32 = 11;
362 /// # const binder_driver_return_protocol_BR_DEAD_BINDER: u32 = 12;
363 /// # const binder_driver_return_protocol_BR_CLEAR_DEATH_NOTIFICATION_DONE: u32 = 13;
364 /// # const binder_driver_return_protocol_BR_FAILED_REPLY: u32 = 14;
365 /// macro_rules! pub_no_prefix {
366 ///     ($prefix:ident, $($newname:ident),+) => {
367 ///         ::kernel::macros::paste! {
368 ///             $(pub(crate) const fn [<$newname:lower:span>]() -> u32 { [<$prefix $newname:span>] })+
369 ///         }
370 ///     };
371 /// }
372 ///
373 /// pub_no_prefix!(
374 ///     binder_driver_return_protocol_,
375 ///     BR_OK,
376 ///     BR_ERROR,
377 ///     BR_TRANSACTION,
378 ///     BR_REPLY,
379 ///     BR_DEAD_REPLY,
380 ///     BR_TRANSACTION_COMPLETE,
381 ///     BR_INCREFS,
382 ///     BR_ACQUIRE,
383 ///     BR_RELEASE,
384 ///     BR_DECREFS,
385 ///     BR_NOOP,
386 ///     BR_SPAWN_LOOPER,
387 ///     BR_DEAD_BINDER,
388 ///     BR_CLEAR_DEATH_NOTIFICATION_DONE,
389 ///     BR_FAILED_REPLY
390 /// );
391 ///
392 /// assert_eq!(br_ok(), binder_driver_return_protocol_BR_OK);
393 /// ```
394 ///
395 /// # Literals
396 ///
397 /// Literals can also be concatenated with other identifiers:
398 ///
399 /// ```
400 /// macro_rules! create_numbered_fn {
401 ///     ($name:literal, $val:literal) => {
402 ///         ::kernel::macros::paste! {
403 ///             fn [<some_ $name _fn $val>]() -> u32 { $val }
404 ///         }
405 ///     };
406 /// }
407 ///
408 /// create_numbered_fn!("foo", 100);
409 ///
410 /// assert_eq!(some_foo_fn100(), 100)
411 /// ```
412 ///
413 /// [`paste`]: https://docs.rs/paste/
414 #[proc_macro]
415 pub fn paste(input: TokenStream) -> TokenStream {
416     let mut tokens = input.into_iter().collect();
417     paste::expand(&mut tokens);
418     tokens.into_iter().collect()
419 }
420 
421 /// Registers a KUnit test suite and its test cases using a user-space like syntax.
422 ///
423 /// This macro should be used on modules. If `CONFIG_KUNIT` (in `.config`) is `n`, the target module
424 /// is ignored.
425 ///
426 /// # Examples
427 ///
428 /// ```ignore
429 /// # use kernel::prelude::*;
430 /// #[kunit_tests(kunit_test_suit_name)]
431 /// mod tests {
432 ///     #[test]
433 ///     fn foo() {
434 ///         assert_eq!(1, 1);
435 ///     }
436 ///
437 ///     #[test]
438 ///     fn bar() {
439 ///         assert_eq!(2, 2);
440 ///     }
441 /// }
442 /// ```
443 #[proc_macro_attribute]
444 pub fn kunit_tests(attr: TokenStream, ts: TokenStream) -> TokenStream {
445     kunit::kunit_tests(attr, ts)
446 }
447