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