• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 helpers;
13 mod kunit;
14 mod module;
15 mod paste;
16 mod pin_data;
17 mod pinned_drop;
18 mod vtable;
19 mod zeroable;
20 
21 use proc_macro::TokenStream;
22 
23 /// Declares a kernel module.
24 ///
25 /// The `type` argument should be a type which implements the [`Module`]
26 /// trait. Also accepts various forms of kernel metadata.
27 ///
28 /// C header: [`include/linux/moduleparam.h`](srctree/include/linux/moduleparam.h)
29 ///
30 /// [`Module`]: ../kernel/trait.Module.html
31 ///
32 /// # Examples
33 ///
34 /// ```ignore
35 /// use kernel::prelude::*;
36 ///
37 /// module!{
38 ///     type: MyModule,
39 ///     name: "my_kernel_module",
40 ///     author: "Rust for Linux Contributors",
41 ///     description: "My very own kernel module!",
42 ///     license: "GPL",
43 ///     alias: ["alternate_module_name"],
44 /// }
45 ///
46 /// struct MyModule;
47 ///
48 /// impl kernel::Module for MyModule {
49 ///     fn init() -> Result<Self> {
50 ///         // If the parameter is writeable, then the kparam lock must be
51 ///         // taken to read the parameter:
52 ///         {
53 ///             let lock = THIS_MODULE.kernel_param_lock();
54 ///             pr_info!("i32 param is:  {}\n", writeable_i32.read(&lock));
55 ///         }
56 ///         // If the parameter is read only, it can be read without locking
57 ///         // the kernel parameters:
58 ///         pr_info!("i32 param is:  {}\n", my_i32.read());
59 ///         Ok(Self)
60 ///     }
61 /// }
62 /// ```
63 ///
64 /// ## Firmware
65 ///
66 /// The following example shows how to declare a kernel module that needs
67 /// to load binary firmware files. You need to specify the file names of
68 /// the firmware in the `firmware` field. The information is embedded
69 /// in the `modinfo` section of the kernel module. For example, a tool to
70 /// build an initramfs uses this information to put the firmware files into
71 /// the initramfs image.
72 ///
73 /// ```ignore
74 /// use kernel::prelude::*;
75 ///
76 /// module!{
77 ///     type: MyDeviceDriverModule,
78 ///     name: "my_device_driver_module",
79 ///     author: "Rust for Linux Contributors",
80 ///     description: "My device driver requires firmware",
81 ///     license: "GPL",
82 ///     firmware: ["my_device_firmware1.bin", "my_device_firmware2.bin"],
83 /// }
84 ///
85 /// struct MyDeviceDriverModule;
86 ///
87 /// impl kernel::Module for MyDeviceDriverModule {
88 ///     fn init() -> Result<Self> {
89 ///         Ok(Self)
90 ///     }
91 /// }
92 /// ```
93 ///
94 /// # Supported argument types
95 ///   - `type`: type which implements the [`Module`] trait (required).
96 ///   - `name`: ASCII string literal of the name of the kernel module (required).
97 ///   - `author`: string literal of the author of the kernel module.
98 ///   - `description`: string literal of the description of the kernel module.
99 ///   - `license`: ASCII string literal of the license of the kernel module (required).
100 ///   - `alias`: array of ASCII string literals of the alias names of the kernel module.
101 ///   - `firmware`: array of ASCII string literals of the firmware files of
102 ///     the kernel module.
103 #[proc_macro]
module(ts: TokenStream) -> TokenStream104 pub fn module(ts: TokenStream) -> TokenStream {
105     module::module(ts)
106 }
107 
108 /// Declares or implements a vtable trait.
109 ///
110 /// Linux's use of pure vtables is very close to Rust traits, but they differ
111 /// in how unimplemented functions are represented. In Rust, traits can provide
112 /// default implementation for all non-required methods (and the default
113 /// implementation could just return `Error::EINVAL`); Linux typically use C
114 /// `NULL` pointers to represent these functions.
115 ///
116 /// This attribute closes that gap. A trait can be annotated with the
117 /// `#[vtable]` attribute. Implementers of the trait will then also have to
118 /// annotate the trait with `#[vtable]`. This attribute generates a `HAS_*`
119 /// associated constant bool for each method in the trait that is set to true if
120 /// the implementer has overridden the associated method.
121 ///
122 /// For a trait method to be optional, it must have a default implementation.
123 /// This is also the case for traits annotated with `#[vtable]`, but in this
124 /// case the default implementation will never be executed. The reason for this
125 /// is that the functions will be called through function pointers installed in
126 /// C side vtables. When an optional method is not implemented on a `#[vtable]`
127 /// trait, a NULL entry is installed in the vtable. Thus the default
128 /// implementation is never called. Since these traits are not designed to be
129 /// used on the Rust side, it should not be possible to call the default
130 /// implementation. This is done to ensure that we call the vtable methods
131 /// through the C vtable, and not through the Rust vtable. Therefore, the
132 /// default implementation should call `kernel::build_error`, which prevents
133 /// calls to this function at compile time:
134 ///
135 /// ```compile_fail
136 /// # // Intentionally missing `use`s to simplify `rusttest`.
137 /// kernel::build_error(VTABLE_DEFAULT_ERROR)
138 /// ```
139 ///
140 /// Note that you might need to import [`kernel::error::VTABLE_DEFAULT_ERROR`].
141 ///
142 /// This macro should not be used when all functions are required.
143 ///
144 /// # Examples
145 ///
146 /// ```ignore
147 /// use kernel::error::VTABLE_DEFAULT_ERROR;
148 /// use kernel::prelude::*;
149 ///
150 /// // Declares a `#[vtable]` trait
151 /// #[vtable]
152 /// pub trait Operations: Send + Sync + Sized {
153 ///     fn foo(&self) -> Result<()> {
154 ///         kernel::build_error(VTABLE_DEFAULT_ERROR)
155 ///     }
156 ///
157 ///     fn bar(&self) -> Result<()> {
158 ///         kernel::build_error(VTABLE_DEFAULT_ERROR)
159 ///     }
160 /// }
161 ///
162 /// struct Foo;
163 ///
164 /// // Implements the `#[vtable]` trait
165 /// #[vtable]
166 /// impl Operations for Foo {
167 ///     fn foo(&self) -> Result<()> {
168 /// #        Err(EINVAL)
169 ///         // ...
170 ///     }
171 /// }
172 ///
173 /// assert_eq!(<Foo as Operations>::HAS_FOO, true);
174 /// assert_eq!(<Foo as Operations>::HAS_BAR, false);
175 /// ```
176 ///
177 /// [`kernel::error::VTABLE_DEFAULT_ERROR`]: ../kernel/error/constant.VTABLE_DEFAULT_ERROR.html
178 #[proc_macro_attribute]
vtable(attr: TokenStream, ts: TokenStream) -> TokenStream179 pub fn vtable(attr: TokenStream, ts: TokenStream) -> TokenStream {
180     vtable::vtable(attr, ts)
181 }
182 
183 /// Concatenate two identifiers.
184 ///
185 /// This is useful in macros that need to declare or reference items with names
186 /// starting with a fixed prefix and ending in a user specified name. The resulting
187 /// identifier has the span of the second argument.
188 ///
189 /// # Examples
190 ///
191 /// ```ignore
192 /// use kernel::macro::concat_idents;
193 ///
194 /// macro_rules! pub_no_prefix {
195 ///     ($prefix:ident, $($newname:ident),+) => {
196 ///         $(pub(crate) const $newname: u32 = kernel::macros::concat_idents!($prefix, $newname);)+
197 ///     };
198 /// }
199 ///
200 /// pub_no_prefix!(
201 ///     binder_driver_return_protocol_,
202 ///     BR_OK,
203 ///     BR_ERROR,
204 ///     BR_TRANSACTION,
205 ///     BR_REPLY,
206 ///     BR_DEAD_REPLY,
207 ///     BR_TRANSACTION_COMPLETE,
208 ///     BR_INCREFS,
209 ///     BR_ACQUIRE,
210 ///     BR_RELEASE,
211 ///     BR_DECREFS,
212 ///     BR_NOOP,
213 ///     BR_SPAWN_LOOPER,
214 ///     BR_DEAD_BINDER,
215 ///     BR_CLEAR_DEATH_NOTIFICATION_DONE,
216 ///     BR_FAILED_REPLY
217 /// );
218 ///
219 /// assert_eq!(BR_OK, binder_driver_return_protocol_BR_OK);
220 /// ```
221 #[proc_macro]
concat_idents(ts: TokenStream) -> TokenStream222 pub fn concat_idents(ts: TokenStream) -> TokenStream {
223     concat_idents::concat_idents(ts)
224 }
225 
226 /// Used to specify the pinning information of the fields of a struct.
227 ///
228 /// This is somewhat similar in purpose as
229 /// [pin-project-lite](https://crates.io/crates/pin-project-lite).
230 /// Place this macro on a struct definition and then `#[pin]` in front of the attributes of each
231 /// field you want to structurally pin.
232 ///
233 /// This macro enables the use of the [`pin_init!`] macro. When pin-initializing a `struct`,
234 /// then `#[pin]` directs the type of initializer that is required.
235 ///
236 /// If your `struct` implements `Drop`, then you need to add `PinnedDrop` as arguments to this
237 /// macro, and change your `Drop` implementation to `PinnedDrop` annotated with
238 /// `#[`[`macro@pinned_drop`]`]`, since dropping pinned values requires extra care.
239 ///
240 /// # Examples
241 ///
242 /// ```rust,ignore
243 /// #[pin_data]
244 /// struct DriverData {
245 ///     #[pin]
246 ///     queue: Mutex<KVec<Command>>,
247 ///     buf: KBox<[u8; 1024 * 1024]>,
248 /// }
249 /// ```
250 ///
251 /// ```rust,ignore
252 /// #[pin_data(PinnedDrop)]
253 /// struct DriverData {
254 ///     #[pin]
255 ///     queue: Mutex<KVec<Command>>,
256 ///     buf: KBox<[u8; 1024 * 1024]>,
257 ///     raw_info: *mut Info,
258 /// }
259 ///
260 /// #[pinned_drop]
261 /// impl PinnedDrop for DriverData {
262 ///     fn drop(self: Pin<&mut Self>) {
263 ///         unsafe { bindings::destroy_info(self.raw_info) };
264 ///     }
265 /// }
266 /// ```
267 ///
268 /// [`pin_init!`]: ../kernel/macro.pin_init.html
269 //  ^ cannot use direct link, since `kernel` is not a dependency of `macros`.
270 #[proc_macro_attribute]
pin_data(inner: TokenStream, item: TokenStream) -> TokenStream271 pub fn pin_data(inner: TokenStream, item: TokenStream) -> TokenStream {
272     pin_data::pin_data(inner, item)
273 }
274 
275 /// Used to implement `PinnedDrop` safely.
276 ///
277 /// Only works on structs that are annotated via `#[`[`macro@pin_data`]`]`.
278 ///
279 /// # Examples
280 ///
281 /// ```rust,ignore
282 /// #[pin_data(PinnedDrop)]
283 /// struct DriverData {
284 ///     #[pin]
285 ///     queue: Mutex<KVec<Command>>,
286 ///     buf: KBox<[u8; 1024 * 1024]>,
287 ///     raw_info: *mut Info,
288 /// }
289 ///
290 /// #[pinned_drop]
291 /// impl PinnedDrop for DriverData {
292 ///     fn drop(self: Pin<&mut Self>) {
293 ///         unsafe { bindings::destroy_info(self.raw_info) };
294 ///     }
295 /// }
296 /// ```
297 #[proc_macro_attribute]
pinned_drop(args: TokenStream, input: TokenStream) -> TokenStream298 pub fn pinned_drop(args: TokenStream, input: TokenStream) -> TokenStream {
299     pinned_drop::pinned_drop(args, input)
300 }
301 
302 /// Paste identifiers together.
303 ///
304 /// Within the `paste!` macro, identifiers inside `[<` and `>]` are concatenated together to form a
305 /// single identifier.
306 ///
307 /// This is similar to the [`paste`] crate, but with pasting feature limited to identifiers and
308 /// literals (lifetimes and documentation strings are not supported). There is a difference in
309 /// supported modifiers as well.
310 ///
311 /// # Example
312 ///
313 /// ```ignore
314 /// use kernel::macro::paste;
315 ///
316 /// macro_rules! pub_no_prefix {
317 ///     ($prefix:ident, $($newname:ident),+) => {
318 ///         paste! {
319 ///             $(pub(crate) const $newname: u32 = [<$prefix $newname>];)+
320 ///         }
321 ///     };
322 /// }
323 ///
324 /// pub_no_prefix!(
325 ///     binder_driver_return_protocol_,
326 ///     BR_OK,
327 ///     BR_ERROR,
328 ///     BR_TRANSACTION,
329 ///     BR_REPLY,
330 ///     BR_DEAD_REPLY,
331 ///     BR_TRANSACTION_COMPLETE,
332 ///     BR_INCREFS,
333 ///     BR_ACQUIRE,
334 ///     BR_RELEASE,
335 ///     BR_DECREFS,
336 ///     BR_NOOP,
337 ///     BR_SPAWN_LOOPER,
338 ///     BR_DEAD_BINDER,
339 ///     BR_CLEAR_DEATH_NOTIFICATION_DONE,
340 ///     BR_FAILED_REPLY
341 /// );
342 ///
343 /// assert_eq!(BR_OK, binder_driver_return_protocol_BR_OK);
344 /// ```
345 ///
346 /// # Modifiers
347 ///
348 /// For each identifier, it is possible to attach one or multiple modifiers to
349 /// it.
350 ///
351 /// Currently supported modifiers are:
352 /// * `span`: change the span of concatenated identifier to the span of the specified token. By
353 ///   default the span of the `[< >]` group is used.
354 /// * `lower`: change the identifier to lower case.
355 /// * `upper`: change the identifier to upper case.
356 ///
357 /// ```ignore
358 /// use kernel::macro::paste;
359 ///
360 /// macro_rules! pub_no_prefix {
361 ///     ($prefix:ident, $($newname:ident),+) => {
362 ///         kernel::macros::paste! {
363 ///             $(pub(crate) const fn [<$newname:lower:span>]() -> u32 { [<$prefix $newname:span>] })+
364 ///         }
365 ///     };
366 /// }
367 ///
368 /// pub_no_prefix!(
369 ///     binder_driver_return_protocol_,
370 ///     BR_OK,
371 ///     BR_ERROR,
372 ///     BR_TRANSACTION,
373 ///     BR_REPLY,
374 ///     BR_DEAD_REPLY,
375 ///     BR_TRANSACTION_COMPLETE,
376 ///     BR_INCREFS,
377 ///     BR_ACQUIRE,
378 ///     BR_RELEASE,
379 ///     BR_DECREFS,
380 ///     BR_NOOP,
381 ///     BR_SPAWN_LOOPER,
382 ///     BR_DEAD_BINDER,
383 ///     BR_CLEAR_DEATH_NOTIFICATION_DONE,
384 ///     BR_FAILED_REPLY
385 /// );
386 ///
387 /// assert_eq!(br_ok(), binder_driver_return_protocol_BR_OK);
388 /// ```
389 ///
390 /// # Literals
391 ///
392 /// Literals can also be concatenated with other identifiers:
393 ///
394 /// ```ignore
395 /// macro_rules! create_numbered_fn {
396 ///     ($name:literal, $val:literal) => {
397 ///         kernel::macros::paste! {
398 ///             fn [<some_ $name _fn $val>]() -> u32 { $val }
399 ///         }
400 ///     };
401 /// }
402 ///
403 /// create_numbered_fn!("foo", 100);
404 ///
405 /// assert_eq!(some_foo_fn100(), 100)
406 /// ```
407 ///
408 /// [`paste`]: https://docs.rs/paste/
409 #[proc_macro]
paste(input: TokenStream) -> TokenStream410 pub fn paste(input: TokenStream) -> TokenStream {
411     let mut tokens = input.into_iter().collect();
412     paste::expand(&mut tokens);
413     tokens.into_iter().collect()
414 }
415 
416 /// Derives the [`Zeroable`] trait for the given struct.
417 ///
418 /// This can only be used for structs where every field implements the [`Zeroable`] trait.
419 ///
420 /// # Examples
421 ///
422 /// ```rust,ignore
423 /// #[derive(Zeroable)]
424 /// pub struct DriverData {
425 ///     id: i64,
426 ///     buf_ptr: *mut u8,
427 ///     len: usize,
428 /// }
429 /// ```
430 #[proc_macro_derive(Zeroable)]
derive_zeroable(input: TokenStream) -> TokenStream431 pub fn derive_zeroable(input: TokenStream) -> TokenStream {
432     zeroable::derive(input)
433 }
434 
435 /// Registers a KUnit test suite and its test cases using a user-space like syntax.
436 ///
437 /// This macro should be used on modules. If `CONFIG_KUNIT` (in `.config`) is `n`, the target module
438 /// is ignored.
439 ///
440 /// # Examples
441 ///
442 /// ```ignore
443 /// # use macros::kunit_tests;
444 /// #[kunit_tests(kunit_test_suit_name)]
445 /// mod tests {
446 ///     #[test]
447 ///     fn foo() {
448 ///         assert_eq!(1, 1);
449 ///     }
450 ///
451 ///     #[test]
452 ///     fn bar() {
453 ///         assert_eq!(2, 2);
454 ///     }
455 /// }
456 /// ```
457 #[proc_macro_attribute]
kunit_tests(attr: TokenStream, ts: TokenStream) -> TokenStream458 pub fn kunit_tests(attr: TokenStream, ts: TokenStream) -> TokenStream {
459     kunit::kunit_tests(attr, ts)
460 }
461