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