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 module; 14 mod paste; 15 mod pin_data; 16 mod pinned_drop; 17 mod vtable; 18 mod zeroable; 19 20 use proc_macro::TokenStream; 21 22 /// Declares a kernel module. 23 /// 24 /// The `type` argument should be a type which implements the [`Module`] 25 /// trait. Also accepts various forms of kernel metadata. 26 /// 27 /// C header: [`include/linux/moduleparam.h`](srctree/include/linux/moduleparam.h) 28 /// 29 /// [`Module`]: ../kernel/trait.Module.html 30 /// 31 /// # Examples 32 /// 33 /// ```ignore 34 /// use kernel::prelude::*; 35 /// 36 /// module!{ 37 /// type: MyModule, 38 /// name: "my_kernel_module", 39 /// author: "Rust for Linux Contributors", 40 /// description: "My very own kernel module!", 41 /// license: "GPL", 42 /// alias: ["alternate_module_name"], 43 /// } 44 /// 45 /// struct MyModule; 46 /// 47 /// impl kernel::Module for MyModule { 48 /// fn init() -> Result<Self> { 49 /// // If the parameter is writeable, then the kparam lock must be 50 /// // taken to read the parameter: 51 /// { 52 /// let lock = THIS_MODULE.kernel_param_lock(); 53 /// pr_info!("i32 param is: {}\n", writeable_i32.read(&lock)); 54 /// } 55 /// // If the parameter is read only, it can be read without locking 56 /// // the kernel parameters: 57 /// pr_info!("i32 param is: {}\n", my_i32.read()); 58 /// Ok(Self) 59 /// } 60 /// } 61 /// ``` 62 /// 63 /// ## Firmware 64 /// 65 /// The following example shows how to declare a kernel module that needs 66 /// to load binary firmware files. You need to specify the file names of 67 /// the firmware in the `firmware` field. The information is embedded 68 /// in the `modinfo` section of the kernel module. For example, a tool to 69 /// build an initramfs uses this information to put the firmware files into 70 /// the initramfs image. 71 /// 72 /// ```ignore 73 /// use kernel::prelude::*; 74 /// 75 /// module!{ 76 /// type: MyDeviceDriverModule, 77 /// name: "my_device_driver_module", 78 /// author: "Rust for Linux Contributors", 79 /// description: "My device driver requires firmware", 80 /// license: "GPL", 81 /// firmware: ["my_device_firmware1.bin", "my_device_firmware2.bin"], 82 /// } 83 /// 84 /// struct MyDeviceDriverModule; 85 /// 86 /// impl kernel::Module for MyDeviceDriverModule { 87 /// fn init() -> Result<Self> { 88 /// Ok(Self) 89 /// } 90 /// } 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 /// - `author`: string literal of the author 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 `kernel::build_error`, which prevents 132 /// calls to this function at compile time: 133 /// 134 /// ```compile_fail 135 /// # use kernel::error::VTABLE_DEFAULT_ERROR; 136 /// kernel::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 /// ```ignore 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 /// kernel::build_error(VTABLE_DEFAULT_ERROR) 154 /// } 155 /// 156 /// fn bar(&self) -> Result<()> { 157 /// kernel::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 /// Concatenate two identifiers. 183 /// 184 /// This is useful in macros that need to declare or reference items with names 185 /// starting with a fixed prefix and ending in a user specified name. The resulting 186 /// identifier has the span of the second argument. 187 /// 188 /// # Examples 189 /// 190 /// ```ignore 191 /// use kernel::macro::concat_idents; 192 /// 193 /// macro_rules! pub_no_prefix { 194 /// ($prefix:ident, $($newname:ident),+) => { 195 /// $(pub(crate) const $newname: u32 = kernel::macros::concat_idents!($prefix, $newname);)+ 196 /// }; 197 /// } 198 /// 199 /// pub_no_prefix!( 200 /// binder_driver_return_protocol_, 201 /// BR_OK, 202 /// BR_ERROR, 203 /// BR_TRANSACTION, 204 /// BR_REPLY, 205 /// BR_DEAD_REPLY, 206 /// BR_TRANSACTION_COMPLETE, 207 /// BR_INCREFS, 208 /// BR_ACQUIRE, 209 /// BR_RELEASE, 210 /// BR_DECREFS, 211 /// BR_NOOP, 212 /// BR_SPAWN_LOOPER, 213 /// BR_DEAD_BINDER, 214 /// BR_CLEAR_DEATH_NOTIFICATION_DONE, 215 /// BR_FAILED_REPLY 216 /// ); 217 /// 218 /// assert_eq!(BR_OK, binder_driver_return_protocol_BR_OK); 219 /// ``` 220 #[proc_macro] 221 pub fn concat_idents(ts: TokenStream) -> TokenStream { 222 concat_idents::concat_idents(ts) 223 } 224 225 /// Used to specify the pinning information of the fields of a struct. 226 /// 227 /// This is somewhat similar in purpose as 228 /// [pin-project-lite](https://crates.io/crates/pin-project-lite). 229 /// Place this macro on a struct definition and then `#[pin]` in front of the attributes of each 230 /// field you want to structurally pin. 231 /// 232 /// This macro enables the use of the [`pin_init!`] macro. When pin-initializing a `struct`, 233 /// then `#[pin]` directs the type of initializer that is required. 234 /// 235 /// If your `struct` implements `Drop`, then you need to add `PinnedDrop` as arguments to this 236 /// macro, and change your `Drop` implementation to `PinnedDrop` annotated with 237 /// `#[`[`macro@pinned_drop`]`]`, since dropping pinned values requires extra care. 238 /// 239 /// # Examples 240 /// 241 /// ```rust,ignore 242 /// #[pin_data] 243 /// struct DriverData { 244 /// #[pin] 245 /// queue: Mutex<Vec<Command>>, 246 /// buf: Box<[u8; 1024 * 1024]>, 247 /// } 248 /// ``` 249 /// 250 /// ```rust,ignore 251 /// #[pin_data(PinnedDrop)] 252 /// struct DriverData { 253 /// #[pin] 254 /// queue: Mutex<Vec<Command>>, 255 /// buf: Box<[u8; 1024 * 1024]>, 256 /// raw_info: *mut Info, 257 /// } 258 /// 259 /// #[pinned_drop] 260 /// impl PinnedDrop for DriverData { 261 /// fn drop(self: Pin<&mut Self>) { 262 /// unsafe { bindings::destroy_info(self.raw_info) }; 263 /// } 264 /// } 265 /// ``` 266 /// 267 /// [`pin_init!`]: ../kernel/macro.pin_init.html 268 // ^ cannot use direct link, since `kernel` is not a dependency of `macros`. 269 #[proc_macro_attribute] 270 pub fn pin_data(inner: TokenStream, item: TokenStream) -> TokenStream { 271 pin_data::pin_data(inner, item) 272 } 273 274 /// Used to implement `PinnedDrop` safely. 275 /// 276 /// Only works on structs that are annotated via `#[`[`macro@pin_data`]`]`. 277 /// 278 /// # Examples 279 /// 280 /// ```rust,ignore 281 /// #[pin_data(PinnedDrop)] 282 /// struct DriverData { 283 /// #[pin] 284 /// queue: Mutex<Vec<Command>>, 285 /// buf: Box<[u8; 1024 * 1024]>, 286 /// raw_info: *mut Info, 287 /// } 288 /// 289 /// #[pinned_drop] 290 /// impl PinnedDrop for DriverData { 291 /// fn drop(self: Pin<&mut Self>) { 292 /// unsafe { bindings::destroy_info(self.raw_info) }; 293 /// } 294 /// } 295 /// ``` 296 #[proc_macro_attribute] 297 pub fn pinned_drop(args: TokenStream, input: TokenStream) -> TokenStream { 298 pinned_drop::pinned_drop(args, input) 299 } 300 301 /// Paste identifiers together. 302 /// 303 /// Within the `paste!` macro, identifiers inside `[<` and `>]` are concatenated together to form a 304 /// single identifier. 305 /// 306 /// This is similar to the [`paste`] crate, but with pasting feature limited to identifiers and 307 /// literals (lifetimes and documentation strings are not supported). There is a difference in 308 /// supported modifiers as well. 309 /// 310 /// # Example 311 /// 312 /// ```ignore 313 /// use kernel::macro::paste; 314 /// 315 /// macro_rules! pub_no_prefix { 316 /// ($prefix:ident, $($newname:ident),+) => { 317 /// paste! { 318 /// $(pub(crate) const $newname: u32 = [<$prefix $newname>];)+ 319 /// } 320 /// }; 321 /// } 322 /// 323 /// pub_no_prefix!( 324 /// binder_driver_return_protocol_, 325 /// BR_OK, 326 /// BR_ERROR, 327 /// BR_TRANSACTION, 328 /// BR_REPLY, 329 /// BR_DEAD_REPLY, 330 /// BR_TRANSACTION_COMPLETE, 331 /// BR_INCREFS, 332 /// BR_ACQUIRE, 333 /// BR_RELEASE, 334 /// BR_DECREFS, 335 /// BR_NOOP, 336 /// BR_SPAWN_LOOPER, 337 /// BR_DEAD_BINDER, 338 /// BR_CLEAR_DEATH_NOTIFICATION_DONE, 339 /// BR_FAILED_REPLY 340 /// ); 341 /// 342 /// assert_eq!(BR_OK, binder_driver_return_protocol_BR_OK); 343 /// ``` 344 /// 345 /// # Modifiers 346 /// 347 /// For each identifier, it is possible to attach one or multiple modifiers to 348 /// it. 349 /// 350 /// Currently supported modifiers are: 351 /// * `span`: change the span of concatenated identifier to the span of the specified token. By 352 /// default the span of the `[< >]` group is used. 353 /// * `lower`: change the identifier to lower case. 354 /// * `upper`: change the identifier to upper case. 355 /// 356 /// ```ignore 357 /// use kernel::macro::paste; 358 /// 359 /// macro_rules! pub_no_prefix { 360 /// ($prefix:ident, $($newname:ident),+) => { 361 /// kernel::macros::paste! { 362 /// $(pub(crate) const fn [<$newname:lower:span>]: u32 = [<$prefix $newname:span>];)+ 363 /// } 364 /// }; 365 /// } 366 /// 367 /// pub_no_prefix!( 368 /// binder_driver_return_protocol_, 369 /// BR_OK, 370 /// BR_ERROR, 371 /// BR_TRANSACTION, 372 /// BR_REPLY, 373 /// BR_DEAD_REPLY, 374 /// BR_TRANSACTION_COMPLETE, 375 /// BR_INCREFS, 376 /// BR_ACQUIRE, 377 /// BR_RELEASE, 378 /// BR_DECREFS, 379 /// BR_NOOP, 380 /// BR_SPAWN_LOOPER, 381 /// BR_DEAD_BINDER, 382 /// BR_CLEAR_DEATH_NOTIFICATION_DONE, 383 /// BR_FAILED_REPLY 384 /// ); 385 /// 386 /// assert_eq!(br_ok(), binder_driver_return_protocol_BR_OK); 387 /// ``` 388 /// 389 /// # Literals 390 /// 391 /// Literals can also be concatenated with other identifiers: 392 /// 393 /// ```ignore 394 /// macro_rules! create_numbered_fn { 395 /// ($name:literal, $val:literal) => { 396 /// kernel::macros::paste! { 397 /// fn [<some_ $name _fn $val>]() -> u32 { $val } 398 /// } 399 /// }; 400 /// } 401 /// 402 /// create_numbered_fn!("foo", 100); 403 /// 404 /// assert_eq!(some_foo_fn100(), 100) 405 /// ``` 406 /// 407 /// [`paste`]: https://docs.rs/paste/ 408 #[proc_macro] 409 pub fn paste(input: TokenStream) -> TokenStream { 410 let mut tokens = input.into_iter().collect(); 411 paste::expand(&mut tokens); 412 tokens.into_iter().collect() 413 } 414 415 /// Derives the [`Zeroable`] trait for the given struct. 416 /// 417 /// This can only be used for structs where every field implements the [`Zeroable`] trait. 418 /// 419 /// # Examples 420 /// 421 /// ```rust,ignore 422 /// #[derive(Zeroable)] 423 /// pub struct DriverData { 424 /// id: i64, 425 /// buf_ptr: *mut u8, 426 /// len: usize, 427 /// } 428 /// ``` 429 #[proc_macro_derive(Zeroable)] 430 pub fn derive_zeroable(input: TokenStream) -> TokenStream { 431 zeroable::derive(input) 432 } 433