lib.rs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488
  1. // SPDX-License-Identifier: GPL-2.0
  2. //! Crate for all kernel procedural macros.
  3. // When fixdep scans this, it will find this string `CONFIG_RUSTC_VERSION_TEXT`
  4. // and thus add a dependency on `include/config/RUSTC_VERSION_TEXT`, which is
  5. // touched by Kconfig when the version string from the compiler changes.
  6. // Stable since Rust 1.88.0 under a different name, `proc_macro_span_file`,
  7. // which was added in Rust 1.88.0. This is why `cfg_attr` is used here, i.e.
  8. // to avoid depending on the full `proc_macro_span` on Rust >= 1.88.0.
  9. #![cfg_attr(not(CONFIG_RUSTC_HAS_SPAN_FILE), feature(proc_macro_span))]
  10. mod concat_idents;
  11. mod export;
  12. mod fmt;
  13. mod helpers;
  14. mod kunit;
  15. mod module;
  16. mod paste;
  17. mod vtable;
  18. use proc_macro::TokenStream;
  19. use syn::parse_macro_input;
  20. /// Declares a kernel module.
  21. ///
  22. /// The `type` argument should be a type which implements the [`Module`]
  23. /// trait. Also accepts various forms of kernel metadata.
  24. ///
  25. /// The `params` field describe module parameters. Each entry has the form
  26. ///
  27. /// ```ignore
  28. /// parameter_name: type {
  29. /// default: default_value,
  30. /// description: "Description",
  31. /// }
  32. /// ```
  33. ///
  34. /// `type` may be one of
  35. ///
  36. /// - [`i8`]
  37. /// - [`u8`]
  38. /// - [`i8`]
  39. /// - [`u8`]
  40. /// - [`i16`]
  41. /// - [`u16`]
  42. /// - [`i32`]
  43. /// - [`u32`]
  44. /// - [`i64`]
  45. /// - [`u64`]
  46. /// - [`isize`]
  47. /// - [`usize`]
  48. ///
  49. /// C header: [`include/linux/moduleparam.h`](srctree/include/linux/moduleparam.h)
  50. ///
  51. /// [`Module`]: ../kernel/trait.Module.html
  52. ///
  53. /// # Examples
  54. ///
  55. /// ```ignore
  56. /// use kernel::prelude::*;
  57. ///
  58. /// module!{
  59. /// type: MyModule,
  60. /// name: "my_kernel_module",
  61. /// authors: ["Rust for Linux Contributors"],
  62. /// description: "My very own kernel module!",
  63. /// license: "GPL",
  64. /// alias: ["alternate_module_name"],
  65. /// params: {
  66. /// my_parameter: i64 {
  67. /// default: 1,
  68. /// description: "This parameter has a default of 1",
  69. /// },
  70. /// },
  71. /// }
  72. ///
  73. /// struct MyModule(i32);
  74. ///
  75. /// impl kernel::Module for MyModule {
  76. /// fn init(_module: &'static ThisModule) -> Result<Self> {
  77. /// let foo: i32 = 42;
  78. /// pr_info!("I contain: {}\n", foo);
  79. /// pr_info!("i32 param is: {}\n", module_parameters::my_parameter.read());
  80. /// Ok(Self(foo))
  81. /// }
  82. /// }
  83. /// # fn main() {}
  84. /// ```
  85. ///
  86. /// ## Firmware
  87. ///
  88. /// The following example shows how to declare a kernel module that needs
  89. /// to load binary firmware files. You need to specify the file names of
  90. /// the firmware in the `firmware` field. The information is embedded
  91. /// in the `modinfo` section of the kernel module. For example, a tool to
  92. /// build an initramfs uses this information to put the firmware files into
  93. /// the initramfs image.
  94. ///
  95. /// ```
  96. /// use kernel::prelude::*;
  97. ///
  98. /// module!{
  99. /// type: MyDeviceDriverModule,
  100. /// name: "my_device_driver_module",
  101. /// authors: ["Rust for Linux Contributors"],
  102. /// description: "My device driver requires firmware",
  103. /// license: "GPL",
  104. /// firmware: ["my_device_firmware1.bin", "my_device_firmware2.bin"],
  105. /// }
  106. ///
  107. /// struct MyDeviceDriverModule;
  108. ///
  109. /// impl kernel::Module for MyDeviceDriverModule {
  110. /// fn init(_module: &'static ThisModule) -> Result<Self> {
  111. /// Ok(Self)
  112. /// }
  113. /// }
  114. /// # fn main() {}
  115. /// ```
  116. ///
  117. /// # Supported argument types
  118. /// - `type`: type which implements the [`Module`] trait (required).
  119. /// - `name`: ASCII string literal of the name of the kernel module (required).
  120. /// - `authors`: array of ASCII string literals of the authors of the kernel module.
  121. /// - `description`: string literal of the description of the kernel module.
  122. /// - `license`: ASCII string literal of the license of the kernel module (required).
  123. /// - `alias`: array of ASCII string literals of the alias names of the kernel module.
  124. /// - `firmware`: array of ASCII string literals of the firmware files of
  125. /// the kernel module.
  126. #[proc_macro]
  127. pub fn module(input: TokenStream) -> TokenStream {
  128. module::module(parse_macro_input!(input))
  129. .unwrap_or_else(|e| e.into_compile_error())
  130. .into()
  131. }
  132. /// Declares or implements a vtable trait.
  133. ///
  134. /// Linux's use of pure vtables is very close to Rust traits, but they differ
  135. /// in how unimplemented functions are represented. In Rust, traits can provide
  136. /// default implementation for all non-required methods (and the default
  137. /// implementation could just return `Error::EINVAL`); Linux typically use C
  138. /// `NULL` pointers to represent these functions.
  139. ///
  140. /// This attribute closes that gap. A trait can be annotated with the
  141. /// `#[vtable]` attribute. Implementers of the trait will then also have to
  142. /// annotate the trait with `#[vtable]`. This attribute generates a `HAS_*`
  143. /// associated constant bool for each method in the trait that is set to true if
  144. /// the implementer has overridden the associated method.
  145. ///
  146. /// For a trait method to be optional, it must have a default implementation.
  147. /// This is also the case for traits annotated with `#[vtable]`, but in this
  148. /// case the default implementation will never be executed. The reason for this
  149. /// is that the functions will be called through function pointers installed in
  150. /// C side vtables. When an optional method is not implemented on a `#[vtable]`
  151. /// trait, a `NULL` entry is installed in the vtable. Thus the default
  152. /// implementation is never called. Since these traits are not designed to be
  153. /// used on the Rust side, it should not be possible to call the default
  154. /// implementation. This is done to ensure that we call the vtable methods
  155. /// through the C vtable, and not through the Rust vtable. Therefore, the
  156. /// default implementation should call `build_error!`, which prevents
  157. /// calls to this function at compile time:
  158. ///
  159. /// ```compile_fail
  160. /// # // Intentionally missing `use`s to simplify `rusttest`.
  161. /// build_error!(VTABLE_DEFAULT_ERROR)
  162. /// ```
  163. ///
  164. /// Note that you might need to import [`kernel::error::VTABLE_DEFAULT_ERROR`].
  165. ///
  166. /// This macro should not be used when all functions are required.
  167. ///
  168. /// # Examples
  169. ///
  170. /// ```
  171. /// use kernel::error::VTABLE_DEFAULT_ERROR;
  172. /// use kernel::prelude::*;
  173. ///
  174. /// // Declares a `#[vtable]` trait
  175. /// #[vtable]
  176. /// pub trait Operations: Send + Sync + Sized {
  177. /// fn foo(&self) -> Result<()> {
  178. /// build_error!(VTABLE_DEFAULT_ERROR)
  179. /// }
  180. ///
  181. /// fn bar(&self) -> Result<()> {
  182. /// build_error!(VTABLE_DEFAULT_ERROR)
  183. /// }
  184. /// }
  185. ///
  186. /// struct Foo;
  187. ///
  188. /// // Implements the `#[vtable]` trait
  189. /// #[vtable]
  190. /// impl Operations for Foo {
  191. /// fn foo(&self) -> Result<()> {
  192. /// # Err(EINVAL)
  193. /// // ...
  194. /// }
  195. /// }
  196. ///
  197. /// assert_eq!(<Foo as Operations>::HAS_FOO, true);
  198. /// assert_eq!(<Foo as Operations>::HAS_BAR, false);
  199. /// ```
  200. ///
  201. /// [`kernel::error::VTABLE_DEFAULT_ERROR`]: ../kernel/error/constant.VTABLE_DEFAULT_ERROR.html
  202. #[proc_macro_attribute]
  203. pub fn vtable(attr: TokenStream, input: TokenStream) -> TokenStream {
  204. parse_macro_input!(attr as syn::parse::Nothing);
  205. vtable::vtable(parse_macro_input!(input))
  206. .unwrap_or_else(|e| e.into_compile_error())
  207. .into()
  208. }
  209. /// Export a function so that C code can call it via a header file.
  210. ///
  211. /// Functions exported using this macro can be called from C code using the declaration in the
  212. /// appropriate header file. It should only be used in cases where C calls the function through a
  213. /// header file; cases where C calls into Rust via a function pointer in a vtable (such as
  214. /// `file_operations`) should not use this macro.
  215. ///
  216. /// This macro has the following effect:
  217. ///
  218. /// * Disables name mangling for this function.
  219. /// * Verifies at compile-time that the function signature matches the declaration in the header
  220. /// file.
  221. ///
  222. /// You must declare the signature of the Rust function in a header file that is included by
  223. /// `rust/bindings/bindings_helper.h`.
  224. ///
  225. /// This macro is *not* the same as the C macros `EXPORT_SYMBOL_*`. All Rust symbols are currently
  226. /// automatically exported with `EXPORT_SYMBOL_GPL`.
  227. #[proc_macro_attribute]
  228. pub fn export(attr: TokenStream, input: TokenStream) -> TokenStream {
  229. parse_macro_input!(attr as syn::parse::Nothing);
  230. export::export(parse_macro_input!(input)).into()
  231. }
  232. /// Like [`core::format_args!`], but automatically wraps arguments in [`kernel::fmt::Adapter`].
  233. ///
  234. /// This macro allows generating `fmt::Arguments` while ensuring that each argument is wrapped with
  235. /// `::kernel::fmt::Adapter`, which customizes formatting behavior for kernel logging.
  236. ///
  237. /// Named arguments used in the format string (e.g. `{foo}`) are detected and resolved from local
  238. /// bindings. All positional and named arguments are automatically wrapped.
  239. ///
  240. /// This macro is an implementation detail of other kernel logging macros like [`pr_info!`] and
  241. /// should not typically be used directly.
  242. ///
  243. /// [`kernel::fmt::Adapter`]: ../kernel/fmt/struct.Adapter.html
  244. /// [`pr_info!`]: ../kernel/macro.pr_info.html
  245. #[proc_macro]
  246. pub fn fmt(input: TokenStream) -> TokenStream {
  247. fmt::fmt(input.into()).into()
  248. }
  249. /// Concatenate two identifiers.
  250. ///
  251. /// This is useful in macros that need to declare or reference items with names
  252. /// starting with a fixed prefix and ending in a user specified name. The resulting
  253. /// identifier has the span of the second argument.
  254. ///
  255. /// # Examples
  256. ///
  257. /// ```
  258. /// # const binder_driver_return_protocol_BR_OK: u32 = 0;
  259. /// # const binder_driver_return_protocol_BR_ERROR: u32 = 1;
  260. /// # const binder_driver_return_protocol_BR_TRANSACTION: u32 = 2;
  261. /// # const binder_driver_return_protocol_BR_REPLY: u32 = 3;
  262. /// # const binder_driver_return_protocol_BR_DEAD_REPLY: u32 = 4;
  263. /// # const binder_driver_return_protocol_BR_TRANSACTION_COMPLETE: u32 = 5;
  264. /// # const binder_driver_return_protocol_BR_INCREFS: u32 = 6;
  265. /// # const binder_driver_return_protocol_BR_ACQUIRE: u32 = 7;
  266. /// # const binder_driver_return_protocol_BR_RELEASE: u32 = 8;
  267. /// # const binder_driver_return_protocol_BR_DECREFS: u32 = 9;
  268. /// # const binder_driver_return_protocol_BR_NOOP: u32 = 10;
  269. /// # const binder_driver_return_protocol_BR_SPAWN_LOOPER: u32 = 11;
  270. /// # const binder_driver_return_protocol_BR_DEAD_BINDER: u32 = 12;
  271. /// # const binder_driver_return_protocol_BR_CLEAR_DEATH_NOTIFICATION_DONE: u32 = 13;
  272. /// # const binder_driver_return_protocol_BR_FAILED_REPLY: u32 = 14;
  273. /// use kernel::macros::concat_idents;
  274. ///
  275. /// macro_rules! pub_no_prefix {
  276. /// ($prefix:ident, $($newname:ident),+) => {
  277. /// $(pub(crate) const $newname: u32 = concat_idents!($prefix, $newname);)+
  278. /// };
  279. /// }
  280. ///
  281. /// pub_no_prefix!(
  282. /// binder_driver_return_protocol_,
  283. /// BR_OK,
  284. /// BR_ERROR,
  285. /// BR_TRANSACTION,
  286. /// BR_REPLY,
  287. /// BR_DEAD_REPLY,
  288. /// BR_TRANSACTION_COMPLETE,
  289. /// BR_INCREFS,
  290. /// BR_ACQUIRE,
  291. /// BR_RELEASE,
  292. /// BR_DECREFS,
  293. /// BR_NOOP,
  294. /// BR_SPAWN_LOOPER,
  295. /// BR_DEAD_BINDER,
  296. /// BR_CLEAR_DEATH_NOTIFICATION_DONE,
  297. /// BR_FAILED_REPLY
  298. /// );
  299. ///
  300. /// assert_eq!(BR_OK, binder_driver_return_protocol_BR_OK);
  301. /// ```
  302. #[proc_macro]
  303. pub fn concat_idents(input: TokenStream) -> TokenStream {
  304. concat_idents::concat_idents(parse_macro_input!(input)).into()
  305. }
  306. /// Paste identifiers together.
  307. ///
  308. /// Within the `paste!` macro, identifiers inside `[<` and `>]` are concatenated together to form a
  309. /// single identifier.
  310. ///
  311. /// This is similar to the [`paste`] crate, but with pasting feature limited to identifiers and
  312. /// literals (lifetimes and documentation strings are not supported). There is a difference in
  313. /// supported modifiers as well.
  314. ///
  315. /// # Examples
  316. ///
  317. /// ```
  318. /// # const binder_driver_return_protocol_BR_OK: u32 = 0;
  319. /// # const binder_driver_return_protocol_BR_ERROR: u32 = 1;
  320. /// # const binder_driver_return_protocol_BR_TRANSACTION: u32 = 2;
  321. /// # const binder_driver_return_protocol_BR_REPLY: u32 = 3;
  322. /// # const binder_driver_return_protocol_BR_DEAD_REPLY: u32 = 4;
  323. /// # const binder_driver_return_protocol_BR_TRANSACTION_COMPLETE: u32 = 5;
  324. /// # const binder_driver_return_protocol_BR_INCREFS: u32 = 6;
  325. /// # const binder_driver_return_protocol_BR_ACQUIRE: u32 = 7;
  326. /// # const binder_driver_return_protocol_BR_RELEASE: u32 = 8;
  327. /// # const binder_driver_return_protocol_BR_DECREFS: u32 = 9;
  328. /// # const binder_driver_return_protocol_BR_NOOP: u32 = 10;
  329. /// # const binder_driver_return_protocol_BR_SPAWN_LOOPER: u32 = 11;
  330. /// # const binder_driver_return_protocol_BR_DEAD_BINDER: u32 = 12;
  331. /// # const binder_driver_return_protocol_BR_CLEAR_DEATH_NOTIFICATION_DONE: u32 = 13;
  332. /// # const binder_driver_return_protocol_BR_FAILED_REPLY: u32 = 14;
  333. /// macro_rules! pub_no_prefix {
  334. /// ($prefix:ident, $($newname:ident),+) => {
  335. /// ::kernel::macros::paste! {
  336. /// $(pub(crate) const $newname: u32 = [<$prefix $newname>];)+
  337. /// }
  338. /// };
  339. /// }
  340. ///
  341. /// pub_no_prefix!(
  342. /// binder_driver_return_protocol_,
  343. /// BR_OK,
  344. /// BR_ERROR,
  345. /// BR_TRANSACTION,
  346. /// BR_REPLY,
  347. /// BR_DEAD_REPLY,
  348. /// BR_TRANSACTION_COMPLETE,
  349. /// BR_INCREFS,
  350. /// BR_ACQUIRE,
  351. /// BR_RELEASE,
  352. /// BR_DECREFS,
  353. /// BR_NOOP,
  354. /// BR_SPAWN_LOOPER,
  355. /// BR_DEAD_BINDER,
  356. /// BR_CLEAR_DEATH_NOTIFICATION_DONE,
  357. /// BR_FAILED_REPLY
  358. /// );
  359. ///
  360. /// assert_eq!(BR_OK, binder_driver_return_protocol_BR_OK);
  361. /// ```
  362. ///
  363. /// # Modifiers
  364. ///
  365. /// For each identifier, it is possible to attach one or multiple modifiers to
  366. /// it.
  367. ///
  368. /// Currently supported modifiers are:
  369. /// * `span`: change the span of concatenated identifier to the span of the specified token. By
  370. /// default the span of the `[< >]` group is used.
  371. /// * `lower`: change the identifier to lower case.
  372. /// * `upper`: change the identifier to upper case.
  373. ///
  374. /// ```
  375. /// # const binder_driver_return_protocol_BR_OK: u32 = 0;
  376. /// # const binder_driver_return_protocol_BR_ERROR: u32 = 1;
  377. /// # const binder_driver_return_protocol_BR_TRANSACTION: u32 = 2;
  378. /// # const binder_driver_return_protocol_BR_REPLY: u32 = 3;
  379. /// # const binder_driver_return_protocol_BR_DEAD_REPLY: u32 = 4;
  380. /// # const binder_driver_return_protocol_BR_TRANSACTION_COMPLETE: u32 = 5;
  381. /// # const binder_driver_return_protocol_BR_INCREFS: u32 = 6;
  382. /// # const binder_driver_return_protocol_BR_ACQUIRE: u32 = 7;
  383. /// # const binder_driver_return_protocol_BR_RELEASE: u32 = 8;
  384. /// # const binder_driver_return_protocol_BR_DECREFS: u32 = 9;
  385. /// # const binder_driver_return_protocol_BR_NOOP: u32 = 10;
  386. /// # const binder_driver_return_protocol_BR_SPAWN_LOOPER: u32 = 11;
  387. /// # const binder_driver_return_protocol_BR_DEAD_BINDER: u32 = 12;
  388. /// # const binder_driver_return_protocol_BR_CLEAR_DEATH_NOTIFICATION_DONE: u32 = 13;
  389. /// # const binder_driver_return_protocol_BR_FAILED_REPLY: u32 = 14;
  390. /// macro_rules! pub_no_prefix {
  391. /// ($prefix:ident, $($newname:ident),+) => {
  392. /// ::kernel::macros::paste! {
  393. /// $(pub(crate) const fn [<$newname:lower:span>]() -> u32 { [<$prefix $newname:span>] })+
  394. /// }
  395. /// };
  396. /// }
  397. ///
  398. /// pub_no_prefix!(
  399. /// binder_driver_return_protocol_,
  400. /// BR_OK,
  401. /// BR_ERROR,
  402. /// BR_TRANSACTION,
  403. /// BR_REPLY,
  404. /// BR_DEAD_REPLY,
  405. /// BR_TRANSACTION_COMPLETE,
  406. /// BR_INCREFS,
  407. /// BR_ACQUIRE,
  408. /// BR_RELEASE,
  409. /// BR_DECREFS,
  410. /// BR_NOOP,
  411. /// BR_SPAWN_LOOPER,
  412. /// BR_DEAD_BINDER,
  413. /// BR_CLEAR_DEATH_NOTIFICATION_DONE,
  414. /// BR_FAILED_REPLY
  415. /// );
  416. ///
  417. /// assert_eq!(br_ok(), binder_driver_return_protocol_BR_OK);
  418. /// ```
  419. ///
  420. /// # Literals
  421. ///
  422. /// Literals can also be concatenated with other identifiers:
  423. ///
  424. /// ```
  425. /// macro_rules! create_numbered_fn {
  426. /// ($name:literal, $val:literal) => {
  427. /// ::kernel::macros::paste! {
  428. /// fn [<some_ $name _fn $val>]() -> u32 { $val }
  429. /// }
  430. /// };
  431. /// }
  432. ///
  433. /// create_numbered_fn!("foo", 100);
  434. ///
  435. /// assert_eq!(some_foo_fn100(), 100)
  436. /// ```
  437. ///
  438. /// [`paste`]: https://docs.rs/paste/
  439. #[proc_macro]
  440. pub fn paste(input: TokenStream) -> TokenStream {
  441. let mut tokens = proc_macro2::TokenStream::from(input).into_iter().collect();
  442. paste::expand(&mut tokens);
  443. tokens
  444. .into_iter()
  445. .collect::<proc_macro2::TokenStream>()
  446. .into()
  447. }
  448. /// Registers a KUnit test suite and its test cases using a user-space like syntax.
  449. ///
  450. /// This macro should be used on modules. If `CONFIG_KUNIT` (in `.config`) is `n`, the target module
  451. /// is ignored.
  452. ///
  453. /// # Examples
  454. ///
  455. /// ```ignore
  456. /// # use kernel::prelude::*;
  457. /// #[kunit_tests(kunit_test_suit_name)]
  458. /// mod tests {
  459. /// #[test]
  460. /// fn foo() {
  461. /// assert_eq!(1, 1);
  462. /// }
  463. ///
  464. /// #[test]
  465. /// fn bar() {
  466. /// assert_eq!(2, 2);
  467. /// }
  468. /// }
  469. /// ```
  470. #[proc_macro_attribute]
  471. pub fn kunit_tests(attr: TokenStream, input: TokenStream) -> TokenStream {
  472. kunit::kunit_tests(parse_macro_input!(attr), parse_macro_input!(input))
  473. .unwrap_or_else(|e| e.into_compile_error())
  474. .into()
  475. }