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 /// # Supported argument types 60 /// - `type`: type which implements the [`Module`] trait (required). 61 /// - `name`: byte array of the name of the kernel module (required). 62 /// - `author`: byte array of the author of the kernel module. 63 /// - `description`: byte array of the description of the kernel module. 64 /// - `license`: byte array of the license of the kernel module (required). 65 /// - `alias`: byte array of alias name of the kernel module. 66 #[proc_macro] 67 pub fn module(ts: TokenStream) -> TokenStream { 68 module::module(ts) 69 } 70 71 /// Declares or implements a vtable trait. 72 /// 73 /// Linux's use of pure vtables is very close to Rust traits, but they differ 74 /// in how unimplemented functions are represented. In Rust, traits can provide 75 /// default implementation for all non-required methods (and the default 76 /// implementation could just return `Error::EINVAL`); Linux typically use C 77 /// `NULL` pointers to represent these functions. 78 /// 79 /// This attribute closes that gap. A trait can be annotated with the 80 /// `#[vtable]` attribute. Implementers of the trait will then also have to 81 /// annotate the trait with `#[vtable]`. This attribute generates a `HAS_*` 82 /// associated constant bool for each method in the trait that is set to true if 83 /// the implementer has overridden the associated method. 84 /// 85 /// For a trait method to be optional, it must have a default implementation. 86 /// This is also the case for traits annotated with `#[vtable]`, but in this 87 /// case the default implementation will never be executed. The reason for this 88 /// is that the functions will be called through function pointers installed in 89 /// C side vtables. When an optional method is not implemented on a `#[vtable]` 90 /// trait, a NULL entry is installed in the vtable. Thus the default 91 /// implementation is never called. Since these traits are not designed to be 92 /// used on the Rust side, it should not be possible to call the default 93 /// implementation. This is done to ensure that we call the vtable methods 94 /// through the C vtable, and not through the Rust vtable. Therefore, the 95 /// default implementation should call `kernel::build_error`, which prevents 96 /// calls to this function at compile time: 97 /// 98 /// ```compile_fail 99 /// # use kernel::error::VTABLE_DEFAULT_ERROR; 100 /// kernel::build_error(VTABLE_DEFAULT_ERROR) 101 /// ``` 102 /// 103 /// Note that you might need to import [`kernel::error::VTABLE_DEFAULT_ERROR`]. 104 /// 105 /// This macro should not be used when all functions are required. 106 /// 107 /// # Examples 108 /// 109 /// ```ignore 110 /// use kernel::error::VTABLE_DEFAULT_ERROR; 111 /// use kernel::prelude::*; 112 /// 113 /// // Declares a `#[vtable]` trait 114 /// #[vtable] 115 /// pub trait Operations: Send + Sync + Sized { 116 /// fn foo(&self) -> Result<()> { 117 /// kernel::build_error(VTABLE_DEFAULT_ERROR) 118 /// } 119 /// 120 /// fn bar(&self) -> Result<()> { 121 /// kernel::build_error(VTABLE_DEFAULT_ERROR) 122 /// } 123 /// } 124 /// 125 /// struct Foo; 126 /// 127 /// // Implements the `#[vtable]` trait 128 /// #[vtable] 129 /// impl Operations for Foo { 130 /// fn foo(&self) -> Result<()> { 131 /// # Err(EINVAL) 132 /// // ... 133 /// } 134 /// } 135 /// 136 /// assert_eq!(<Foo as Operations>::HAS_FOO, true); 137 /// assert_eq!(<Foo as Operations>::HAS_BAR, false); 138 /// ``` 139 /// 140 /// [`kernel::error::VTABLE_DEFAULT_ERROR`]: ../kernel/error/constant.VTABLE_DEFAULT_ERROR.html 141 #[proc_macro_attribute] 142 pub fn vtable(attr: TokenStream, ts: TokenStream) -> TokenStream { 143 vtable::vtable(attr, ts) 144 } 145 146 /// Concatenate two identifiers. 147 /// 148 /// This is useful in macros that need to declare or reference items with names 149 /// starting with a fixed prefix and ending in a user specified name. The resulting 150 /// identifier has the span of the second argument. 151 /// 152 /// # Examples 153 /// 154 /// ```ignore 155 /// use kernel::macro::concat_idents; 156 /// 157 /// macro_rules! pub_no_prefix { 158 /// ($prefix:ident, $($newname:ident),+) => { 159 /// $(pub(crate) const $newname: u32 = kernel::macros::concat_idents!($prefix, $newname);)+ 160 /// }; 161 /// } 162 /// 163 /// pub_no_prefix!( 164 /// binder_driver_return_protocol_, 165 /// BR_OK, 166 /// BR_ERROR, 167 /// BR_TRANSACTION, 168 /// BR_REPLY, 169 /// BR_DEAD_REPLY, 170 /// BR_TRANSACTION_COMPLETE, 171 /// BR_INCREFS, 172 /// BR_ACQUIRE, 173 /// BR_RELEASE, 174 /// BR_DECREFS, 175 /// BR_NOOP, 176 /// BR_SPAWN_LOOPER, 177 /// BR_DEAD_BINDER, 178 /// BR_CLEAR_DEATH_NOTIFICATION_DONE, 179 /// BR_FAILED_REPLY 180 /// ); 181 /// 182 /// assert_eq!(BR_OK, binder_driver_return_protocol_BR_OK); 183 /// ``` 184 #[proc_macro] 185 pub fn concat_idents(ts: TokenStream) -> TokenStream { 186 concat_idents::concat_idents(ts) 187 } 188 189 /// Used to specify the pinning information of the fields of a struct. 190 /// 191 /// This is somewhat similar in purpose as 192 /// [pin-project-lite](https://crates.io/crates/pin-project-lite). 193 /// Place this macro on a struct definition and then `#[pin]` in front of the attributes of each 194 /// field you want to structurally pin. 195 /// 196 /// This macro enables the use of the [`pin_init!`] macro. When pin-initializing a `struct`, 197 /// then `#[pin]` directs the type of initializer that is required. 198 /// 199 /// If your `struct` implements `Drop`, then you need to add `PinnedDrop` as arguments to this 200 /// macro, and change your `Drop` implementation to `PinnedDrop` annotated with 201 /// `#[`[`macro@pinned_drop`]`]`, since dropping pinned values requires extra care. 202 /// 203 /// # Examples 204 /// 205 /// ```rust,ignore 206 /// #[pin_data] 207 /// struct DriverData { 208 /// #[pin] 209 /// queue: Mutex<Vec<Command>>, 210 /// buf: Box<[u8; 1024 * 1024]>, 211 /// } 212 /// ``` 213 /// 214 /// ```rust,ignore 215 /// #[pin_data(PinnedDrop)] 216 /// struct DriverData { 217 /// #[pin] 218 /// queue: Mutex<Vec<Command>>, 219 /// buf: Box<[u8; 1024 * 1024]>, 220 /// raw_info: *mut Info, 221 /// } 222 /// 223 /// #[pinned_drop] 224 /// impl PinnedDrop for DriverData { 225 /// fn drop(self: Pin<&mut Self>) { 226 /// unsafe { bindings::destroy_info(self.raw_info) }; 227 /// } 228 /// } 229 /// ``` 230 /// 231 /// [`pin_init!`]: ../kernel/macro.pin_init.html 232 // ^ cannot use direct link, since `kernel` is not a dependency of `macros`. 233 #[proc_macro_attribute] 234 pub fn pin_data(inner: TokenStream, item: TokenStream) -> TokenStream { 235 pin_data::pin_data(inner, item) 236 } 237 238 /// Used to implement `PinnedDrop` safely. 239 /// 240 /// Only works on structs that are annotated via `#[`[`macro@pin_data`]`]`. 241 /// 242 /// # Examples 243 /// 244 /// ```rust,ignore 245 /// #[pin_data(PinnedDrop)] 246 /// struct DriverData { 247 /// #[pin] 248 /// queue: Mutex<Vec<Command>>, 249 /// buf: Box<[u8; 1024 * 1024]>, 250 /// raw_info: *mut Info, 251 /// } 252 /// 253 /// #[pinned_drop] 254 /// impl PinnedDrop for DriverData { 255 /// fn drop(self: Pin<&mut Self>) { 256 /// unsafe { bindings::destroy_info(self.raw_info) }; 257 /// } 258 /// } 259 /// ``` 260 #[proc_macro_attribute] 261 pub fn pinned_drop(args: TokenStream, input: TokenStream) -> TokenStream { 262 pinned_drop::pinned_drop(args, input) 263 } 264 265 /// Paste identifiers together. 266 /// 267 /// Within the `paste!` macro, identifiers inside `[<` and `>]` are concatenated together to form a 268 /// single identifier. 269 /// 270 /// This is similar to the [`paste`] crate, but with pasting feature limited to identifiers and 271 /// literals (lifetimes and documentation strings are not supported). There is a difference in 272 /// supported modifiers as well. 273 /// 274 /// # Example 275 /// 276 /// ```ignore 277 /// use kernel::macro::paste; 278 /// 279 /// macro_rules! pub_no_prefix { 280 /// ($prefix:ident, $($newname:ident),+) => { 281 /// paste! { 282 /// $(pub(crate) const $newname: u32 = [<$prefix $newname>];)+ 283 /// } 284 /// }; 285 /// } 286 /// 287 /// pub_no_prefix!( 288 /// binder_driver_return_protocol_, 289 /// BR_OK, 290 /// BR_ERROR, 291 /// BR_TRANSACTION, 292 /// BR_REPLY, 293 /// BR_DEAD_REPLY, 294 /// BR_TRANSACTION_COMPLETE, 295 /// BR_INCREFS, 296 /// BR_ACQUIRE, 297 /// BR_RELEASE, 298 /// BR_DECREFS, 299 /// BR_NOOP, 300 /// BR_SPAWN_LOOPER, 301 /// BR_DEAD_BINDER, 302 /// BR_CLEAR_DEATH_NOTIFICATION_DONE, 303 /// BR_FAILED_REPLY 304 /// ); 305 /// 306 /// assert_eq!(BR_OK, binder_driver_return_protocol_BR_OK); 307 /// ``` 308 /// 309 /// # Modifiers 310 /// 311 /// For each identifier, it is possible to attach one or multiple modifiers to 312 /// it. 313 /// 314 /// Currently supported modifiers are: 315 /// * `span`: change the span of concatenated identifier to the span of the specified token. By 316 /// default the span of the `[< >]` group is used. 317 /// * `lower`: change the identifier to lower case. 318 /// * `upper`: change the identifier to upper case. 319 /// 320 /// ```ignore 321 /// use kernel::macro::paste; 322 /// 323 /// macro_rules! pub_no_prefix { 324 /// ($prefix:ident, $($newname:ident),+) => { 325 /// kernel::macros::paste! { 326 /// $(pub(crate) const fn [<$newname:lower:span>]: u32 = [<$prefix $newname:span>];)+ 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 /// # Literals 354 /// 355 /// Literals can also be concatenated with other identifiers: 356 /// 357 /// ```ignore 358 /// macro_rules! create_numbered_fn { 359 /// ($name:literal, $val:literal) => { 360 /// kernel::macros::paste! { 361 /// fn [<some_ $name _fn $val>]() -> u32 { $val } 362 /// } 363 /// }; 364 /// } 365 /// 366 /// create_numbered_fn!("foo", 100); 367 /// 368 /// assert_eq!(some_foo_fn100(), 100) 369 /// ``` 370 /// 371 /// [`paste`]: https://docs.rs/paste/ 372 #[proc_macro] 373 pub fn paste(input: TokenStream) -> TokenStream { 374 let mut tokens = input.into_iter().collect(); 375 paste::expand(&mut tokens); 376 tokens.into_iter().collect() 377 } 378 379 /// Derives the [`Zeroable`] trait for the given struct. 380 /// 381 /// This can only be used for structs where every field implements the [`Zeroable`] trait. 382 /// 383 /// # Examples 384 /// 385 /// ```rust,ignore 386 /// #[derive(Zeroable)] 387 /// pub struct DriverData { 388 /// id: i64, 389 /// buf_ptr: *mut u8, 390 /// len: usize, 391 /// } 392 /// ``` 393 #[proc_macro_derive(Zeroable)] 394 pub fn derive_zeroable(input: TokenStream) -> TokenStream { 395 zeroable::derive(input) 396 } 397