module.rs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  1. // SPDX-License-Identifier: GPL-2.0
  2. use crate::helpers::*;
  3. use proc_macro::{token_stream, Delimiter, Literal, TokenStream, TokenTree};
  4. use std::fmt::Write;
  5. fn expect_string_array(it: &mut token_stream::IntoIter) -> Vec<String> {
  6. let group = expect_group(it);
  7. assert_eq!(group.delimiter(), Delimiter::Bracket);
  8. let mut values = Vec::new();
  9. let mut it = group.stream().into_iter();
  10. while let Some(val) = try_string(&mut it) {
  11. assert!(val.is_ascii(), "Expected ASCII string");
  12. values.push(val);
  13. match it.next() {
  14. Some(TokenTree::Punct(punct)) => assert_eq!(punct.as_char(), ','),
  15. None => break,
  16. _ => panic!("Expected ',' or end of array"),
  17. }
  18. }
  19. values
  20. }
  21. struct ModInfoBuilder<'a> {
  22. module: &'a str,
  23. counter: usize,
  24. buffer: String,
  25. }
  26. impl<'a> ModInfoBuilder<'a> {
  27. fn new(module: &'a str) -> Self {
  28. ModInfoBuilder {
  29. module,
  30. counter: 0,
  31. buffer: String::new(),
  32. }
  33. }
  34. fn emit_base(&mut self, field: &str, content: &str, builtin: bool) {
  35. let string = if builtin {
  36. // Built-in modules prefix their modinfo strings by `module.`.
  37. format!(
  38. "{module}.{field}={content}\0",
  39. module = self.module,
  40. field = field,
  41. content = content
  42. )
  43. } else {
  44. // Loadable modules' modinfo strings go as-is.
  45. format!("{field}={content}\0")
  46. };
  47. write!(
  48. &mut self.buffer,
  49. "
  50. {cfg}
  51. #[doc(hidden)]
  52. #[link_section = \".modinfo\"]
  53. #[used(compiler)]
  54. pub static __{module}_{counter}: [u8; {length}] = *{string};
  55. ",
  56. cfg = if builtin {
  57. "#[cfg(not(MODULE))]"
  58. } else {
  59. "#[cfg(MODULE)]"
  60. },
  61. module = self.module.to_uppercase(),
  62. counter = self.counter,
  63. length = string.len(),
  64. string = Literal::byte_string(string.as_bytes()),
  65. )
  66. .unwrap();
  67. self.counter += 1;
  68. }
  69. fn emit_only_builtin(&mut self, field: &str, content: &str) {
  70. self.emit_base(field, content, true)
  71. }
  72. fn emit_only_loadable(&mut self, field: &str, content: &str) {
  73. self.emit_base(field, content, false)
  74. }
  75. fn emit(&mut self, field: &str, content: &str) {
  76. self.emit_only_builtin(field, content);
  77. self.emit_only_loadable(field, content);
  78. }
  79. }
  80. #[derive(Debug, Default)]
  81. struct ModuleInfo {
  82. type_: String,
  83. license: String,
  84. name: String,
  85. author: Option<String>,
  86. description: Option<String>,
  87. alias: Option<Vec<String>>,
  88. firmware: Option<Vec<String>>,
  89. }
  90. impl ModuleInfo {
  91. fn parse(it: &mut token_stream::IntoIter) -> Self {
  92. let mut info = ModuleInfo::default();
  93. const EXPECTED_KEYS: &[&str] = &[
  94. "type",
  95. "name",
  96. "author",
  97. "description",
  98. "license",
  99. "alias",
  100. "firmware",
  101. ];
  102. const REQUIRED_KEYS: &[&str] = &["type", "name", "license"];
  103. let mut seen_keys = Vec::new();
  104. loop {
  105. let key = match it.next() {
  106. Some(TokenTree::Ident(ident)) => ident.to_string(),
  107. Some(_) => panic!("Expected Ident or end"),
  108. None => break,
  109. };
  110. if seen_keys.contains(&key) {
  111. panic!("Duplicated key \"{key}\". Keys can only be specified once.");
  112. }
  113. assert_eq!(expect_punct(it), ':');
  114. match key.as_str() {
  115. "type" => info.type_ = expect_ident(it),
  116. "name" => info.name = expect_string_ascii(it),
  117. "author" => info.author = Some(expect_string(it)),
  118. "description" => info.description = Some(expect_string(it)),
  119. "license" => info.license = expect_string_ascii(it),
  120. "alias" => info.alias = Some(expect_string_array(it)),
  121. "firmware" => info.firmware = Some(expect_string_array(it)),
  122. _ => panic!("Unknown key \"{key}\". Valid keys are: {EXPECTED_KEYS:?}."),
  123. }
  124. assert_eq!(expect_punct(it), ',');
  125. seen_keys.push(key);
  126. }
  127. expect_end(it);
  128. for key in REQUIRED_KEYS {
  129. if !seen_keys.iter().any(|e| e == key) {
  130. panic!("Missing required key \"{key}\".");
  131. }
  132. }
  133. let mut ordered_keys: Vec<&str> = Vec::new();
  134. for key in EXPECTED_KEYS {
  135. if seen_keys.iter().any(|e| e == key) {
  136. ordered_keys.push(key);
  137. }
  138. }
  139. if seen_keys != ordered_keys {
  140. panic!("Keys are not ordered as expected. Order them like: {ordered_keys:?}.");
  141. }
  142. info
  143. }
  144. }
  145. pub(crate) fn module(ts: TokenStream) -> TokenStream {
  146. let mut it = ts.into_iter();
  147. let info = ModuleInfo::parse(&mut it);
  148. let mut modinfo = ModInfoBuilder::new(info.name.as_ref());
  149. if let Some(author) = info.author {
  150. modinfo.emit("author", &author);
  151. }
  152. if let Some(description) = info.description {
  153. modinfo.emit("description", &description);
  154. }
  155. modinfo.emit("license", &info.license);
  156. if let Some(aliases) = info.alias {
  157. for alias in aliases {
  158. modinfo.emit("alias", &alias);
  159. }
  160. }
  161. if let Some(firmware) = info.firmware {
  162. for fw in firmware {
  163. modinfo.emit("firmware", &fw);
  164. }
  165. }
  166. // Built-in modules also export the `file` modinfo string.
  167. let file =
  168. std::env::var("RUST_MODFILE").expect("Unable to fetch RUST_MODFILE environmental variable");
  169. modinfo.emit_only_builtin("file", &file);
  170. format!(
  171. "
  172. /// The module name.
  173. ///
  174. /// Used by the printing macros, e.g. [`info!`].
  175. const __LOG_PREFIX: &[u8] = b\"{name}\\0\";
  176. // SAFETY: `__this_module` is constructed by the kernel at load time and will not be
  177. // freed until the module is unloaded.
  178. #[cfg(MODULE)]
  179. static THIS_MODULE: kernel::ThisModule = unsafe {{
  180. extern \"C\" {{
  181. static __this_module: kernel::types::Opaque<kernel::bindings::module>;
  182. }}
  183. kernel::ThisModule::from_ptr(__this_module.get())
  184. }};
  185. #[cfg(not(MODULE))]
  186. static THIS_MODULE: kernel::ThisModule = unsafe {{
  187. kernel::ThisModule::from_ptr(core::ptr::null_mut())
  188. }};
  189. // Double nested modules, since then nobody can access the public items inside.
  190. mod __module_init {{
  191. mod __module_init {{
  192. use super::super::{type_};
  193. /// The \"Rust loadable module\" mark.
  194. //
  195. // This may be best done another way later on, e.g. as a new modinfo
  196. // key or a new section. For the moment, keep it simple.
  197. #[cfg(MODULE)]
  198. #[doc(hidden)]
  199. #[used(compiler)]
  200. static __IS_RUST_MODULE: () = ();
  201. static mut __MOD: Option<{type_}> = None;
  202. // Loadable modules need to export the `{{init,cleanup}}_module` identifiers.
  203. /// # Safety
  204. ///
  205. /// This function must not be called after module initialization, because it may be
  206. /// freed after that completes.
  207. #[cfg(MODULE)]
  208. #[doc(hidden)]
  209. #[no_mangle]
  210. #[link_section = \".init.text\"]
  211. pub unsafe extern \"C\" fn init_module() -> kernel::ffi::c_int {{
  212. // SAFETY: This function is inaccessible to the outside due to the double
  213. // module wrapping it. It is called exactly once by the C side via its
  214. // unique name.
  215. unsafe {{ __init() }}
  216. }}
  217. #[cfg(MODULE)]
  218. #[doc(hidden)]
  219. #[used(compiler)]
  220. #[link_section = \".init.data\"]
  221. static __UNIQUE_ID___addressable_init_module: unsafe extern \"C\" fn() -> i32 = init_module;
  222. #[cfg(MODULE)]
  223. #[doc(hidden)]
  224. #[no_mangle]
  225. #[link_section = \".exit.text\"]
  226. pub extern \"C\" fn cleanup_module() {{
  227. // SAFETY:
  228. // - This function is inaccessible to the outside due to the double
  229. // module wrapping it. It is called exactly once by the C side via its
  230. // unique name,
  231. // - furthermore it is only called after `init_module` has returned `0`
  232. // (which delegates to `__init`).
  233. unsafe {{ __exit() }}
  234. }}
  235. #[cfg(MODULE)]
  236. #[doc(hidden)]
  237. #[used(compiler)]
  238. #[link_section = \".exit.data\"]
  239. static __UNIQUE_ID___addressable_cleanup_module: extern \"C\" fn() = cleanup_module;
  240. // Built-in modules are initialized through an initcall pointer
  241. // and the identifiers need to be unique.
  242. #[cfg(not(MODULE))]
  243. #[cfg(not(CONFIG_HAVE_ARCH_PREL32_RELOCATIONS))]
  244. #[doc(hidden)]
  245. #[link_section = \"{initcall_section}\"]
  246. #[used(compiler)]
  247. pub static __{name}_initcall: extern \"C\" fn() -> kernel::ffi::c_int = __{name}_init;
  248. #[cfg(not(MODULE))]
  249. #[cfg(CONFIG_HAVE_ARCH_PREL32_RELOCATIONS)]
  250. core::arch::global_asm!(
  251. r#\".section \"{initcall_section}\", \"a\"
  252. __{name}_initcall:
  253. .long __{name}_init - .
  254. .previous
  255. \"#
  256. );
  257. #[cfg(not(MODULE))]
  258. #[doc(hidden)]
  259. #[no_mangle]
  260. pub extern \"C\" fn __{name}_init() -> kernel::ffi::c_int {{
  261. // SAFETY: This function is inaccessible to the outside due to the double
  262. // module wrapping it. It is called exactly once by the C side via its
  263. // placement above in the initcall section.
  264. unsafe {{ __init() }}
  265. }}
  266. #[cfg(not(MODULE))]
  267. #[doc(hidden)]
  268. #[no_mangle]
  269. pub extern \"C\" fn __{name}_exit() {{
  270. // SAFETY:
  271. // - This function is inaccessible to the outside due to the double
  272. // module wrapping it. It is called exactly once by the C side via its
  273. // unique name,
  274. // - furthermore it is only called after `__{name}_init` has returned `0`
  275. // (which delegates to `__init`).
  276. unsafe {{ __exit() }}
  277. }}
  278. /// # Safety
  279. ///
  280. /// This function must only be called once.
  281. unsafe fn __init() -> kernel::ffi::c_int {{
  282. match <{type_} as kernel::Module>::init(&super::super::THIS_MODULE) {{
  283. Ok(m) => {{
  284. // SAFETY: No data race, since `__MOD` can only be accessed by this
  285. // module and there only `__init` and `__exit` access it. These
  286. // functions are only called once and `__exit` cannot be called
  287. // before or during `__init`.
  288. unsafe {{
  289. __MOD = Some(m);
  290. }}
  291. return 0;
  292. }}
  293. Err(e) => {{
  294. return e.to_errno();
  295. }}
  296. }}
  297. }}
  298. /// # Safety
  299. ///
  300. /// This function must
  301. /// - only be called once,
  302. /// - be called after `__init` has been called and returned `0`.
  303. unsafe fn __exit() {{
  304. // SAFETY: No data race, since `__MOD` can only be accessed by this module
  305. // and there only `__init` and `__exit` access it. These functions are only
  306. // called once and `__init` was already called.
  307. unsafe {{
  308. // Invokes `drop()` on `__MOD`, which should be used for cleanup.
  309. __MOD = None;
  310. }}
  311. }}
  312. {modinfo}
  313. }}
  314. }}
  315. ",
  316. type_ = info.type_,
  317. name = info.name,
  318. modinfo = modinfo.buffer,
  319. initcall_section = ".initcall6.init"
  320. )
  321. .parse()
  322. .expect("Error parsing formatted string into token stream.")
  323. }