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