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