xref: /linux/rust/macros/module.rs (revision 7a9b709e7cc5ce1ffb84ce07bf6d157e1de758df)
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                 #[cfg_attr(not(target_os = \"macos\"), 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     authors: Option<Vec<String>>,
99     description: Option<String>,
100     alias: Option<Vec<String>>,
101     firmware: Option<Vec<String>>,
102 }
103 
104 impl ModuleInfo {
105     fn parse(it: &mut token_stream::IntoIter) -> Self {
106         let mut info = ModuleInfo::default();
107 
108         const EXPECTED_KEYS: &[&str] = &[
109             "type",
110             "name",
111             "author",
112             "authors",
113             "description",
114             "license",
115             "alias",
116             "firmware",
117         ];
118         const REQUIRED_KEYS: &[&str] = &["type", "name", "license"];
119         let mut seen_keys = Vec::new();
120 
121         loop {
122             let key = match it.next() {
123                 Some(TokenTree::Ident(ident)) => ident.to_string(),
124                 Some(_) => panic!("Expected Ident or end"),
125                 None => break,
126             };
127 
128             if seen_keys.contains(&key) {
129                 panic!(
130                     "Duplicated key \"{}\". Keys can only be specified once.",
131                     key
132                 );
133             }
134 
135             assert_eq!(expect_punct(it), ':');
136 
137             match key.as_str() {
138                 "type" => info.type_ = expect_ident(it),
139                 "name" => info.name = expect_string_ascii(it),
140                 "author" => info.author = Some(expect_string(it)),
141                 "authors" => info.authors = Some(expect_string_array(it)),
142                 "description" => info.description = Some(expect_string(it)),
143                 "license" => info.license = expect_string_ascii(it),
144                 "alias" => info.alias = Some(expect_string_array(it)),
145                 "firmware" => info.firmware = Some(expect_string_array(it)),
146                 _ => panic!(
147                     "Unknown key \"{}\". Valid keys are: {:?}.",
148                     key, EXPECTED_KEYS
149                 ),
150             }
151 
152             assert_eq!(expect_punct(it), ',');
153 
154             seen_keys.push(key);
155         }
156 
157         expect_end(it);
158 
159         for key in REQUIRED_KEYS {
160             if !seen_keys.iter().any(|e| e == key) {
161                 panic!("Missing required key \"{}\".", key);
162             }
163         }
164 
165         let mut ordered_keys: Vec<&str> = Vec::new();
166         for key in EXPECTED_KEYS {
167             if seen_keys.iter().any(|e| e == key) {
168                 ordered_keys.push(key);
169             }
170         }
171 
172         if seen_keys != ordered_keys {
173             panic!(
174                 "Keys are not ordered as expected. Order them like: {:?}.",
175                 ordered_keys
176             );
177         }
178 
179         info
180     }
181 }
182 
183 pub(crate) fn module(ts: TokenStream) -> TokenStream {
184     let mut it = ts.into_iter();
185 
186     let info = ModuleInfo::parse(&mut it);
187 
188     let mut modinfo = ModInfoBuilder::new(info.name.as_ref());
189     if let Some(author) = info.author {
190         modinfo.emit("author", &author);
191     }
192     if let Some(authors) = info.authors {
193         for author in authors {
194             modinfo.emit("author", &author);
195         }
196     }
197     if let Some(description) = info.description {
198         modinfo.emit("description", &description);
199     }
200     modinfo.emit("license", &info.license);
201     if let Some(aliases) = info.alias {
202         for alias in aliases {
203             modinfo.emit("alias", &alias);
204         }
205     }
206     if let Some(firmware) = info.firmware {
207         for fw in firmware {
208             modinfo.emit("firmware", &fw);
209         }
210     }
211 
212     // Built-in modules also export the `file` modinfo string.
213     let file =
214         std::env::var("RUST_MODFILE").expect("Unable to fetch RUST_MODFILE environmental variable");
215     modinfo.emit_only_builtin("file", &file);
216 
217     format!(
218         "
219             /// The module name.
220             ///
221             /// Used by the printing macros, e.g. [`info!`].
222             const __LOG_PREFIX: &[u8] = b\"{name}\\0\";
223 
224             // SAFETY: `__this_module` is constructed by the kernel at load time and will not be
225             // freed until the module is unloaded.
226             #[cfg(MODULE)]
227             static THIS_MODULE: kernel::ThisModule = unsafe {{
228                 extern \"C\" {{
229                     static __this_module: kernel::types::Opaque<kernel::bindings::module>;
230                 }}
231 
232                 kernel::ThisModule::from_ptr(__this_module.get())
233             }};
234             #[cfg(not(MODULE))]
235             static THIS_MODULE: kernel::ThisModule = unsafe {{
236                 kernel::ThisModule::from_ptr(core::ptr::null_mut())
237             }};
238 
239             /// The `LocalModule` type is the type of the module created by `module!`,
240             /// `module_pci_driver!`, `module_platform_driver!`, etc.
241             type LocalModule = {type_};
242 
243             impl kernel::ModuleMetadata for {type_} {{
244                 const NAME: &'static kernel::str::CStr = kernel::c_str!(\"{name}\");
245             }}
246 
247             // Double nested modules, since then nobody can access the public items inside.
248             mod __module_init {{
249                 mod __module_init {{
250                     use super::super::{type_};
251                     use pin_init::PinInit;
252 
253                     /// The \"Rust loadable module\" mark.
254                     //
255                     // This may be best done another way later on, e.g. as a new modinfo
256                     // key or a new section. For the moment, keep it simple.
257                     #[cfg(MODULE)]
258                     #[doc(hidden)]
259                     #[used]
260                     static __IS_RUST_MODULE: () = ();
261 
262                     static mut __MOD: core::mem::MaybeUninit<{type_}> =
263                         core::mem::MaybeUninit::uninit();
264 
265                     // Loadable modules need to export the `{{init,cleanup}}_module` identifiers.
266                     /// # Safety
267                     ///
268                     /// This function must not be called after module initialization, because it may be
269                     /// freed after that completes.
270                     #[cfg(MODULE)]
271                     #[doc(hidden)]
272                     #[no_mangle]
273                     #[link_section = \".init.text\"]
274                     pub unsafe extern \"C\" fn init_module() -> kernel::ffi::c_int {{
275                         // SAFETY: This function is inaccessible to the outside due to the double
276                         // module wrapping it. It is called exactly once by the C side via its
277                         // unique name.
278                         unsafe {{ __init() }}
279                     }}
280 
281                     #[cfg(MODULE)]
282                     #[doc(hidden)]
283                     #[used]
284                     #[link_section = \".init.data\"]
285                     static __UNIQUE_ID___addressable_init_module: unsafe extern \"C\" fn() -> i32 = init_module;
286 
287                     #[cfg(MODULE)]
288                     #[doc(hidden)]
289                     #[no_mangle]
290                     pub extern \"C\" fn cleanup_module() {{
291                         // SAFETY:
292                         // - This function is inaccessible to the outside due to the double
293                         //   module wrapping it. It is called exactly once by the C side via its
294                         //   unique name,
295                         // - furthermore it is only called after `init_module` has returned `0`
296                         //   (which delegates to `__init`).
297                         unsafe {{ __exit() }}
298                     }}
299 
300                     #[cfg(MODULE)]
301                     #[doc(hidden)]
302                     #[used]
303                     #[link_section = \".exit.data\"]
304                     static __UNIQUE_ID___addressable_cleanup_module: extern \"C\" fn() = cleanup_module;
305 
306                     // Built-in modules are initialized through an initcall pointer
307                     // and the identifiers need to be unique.
308                     #[cfg(not(MODULE))]
309                     #[cfg(not(CONFIG_HAVE_ARCH_PREL32_RELOCATIONS))]
310                     #[doc(hidden)]
311                     #[link_section = \"{initcall_section}\"]
312                     #[used]
313                     pub static __{name}_initcall: extern \"C\" fn() -> kernel::ffi::c_int = __{name}_init;
314 
315                     #[cfg(not(MODULE))]
316                     #[cfg(CONFIG_HAVE_ARCH_PREL32_RELOCATIONS)]
317                     core::arch::global_asm!(
318                         r#\".section \"{initcall_section}\", \"a\"
319                         __{name}_initcall:
320                             .long   __{name}_init - .
321                             .previous
322                         \"#
323                     );
324 
325                     #[cfg(not(MODULE))]
326                     #[doc(hidden)]
327                     #[no_mangle]
328                     pub extern \"C\" fn __{name}_init() -> kernel::ffi::c_int {{
329                         // SAFETY: This function is inaccessible to the outside due to the double
330                         // module wrapping it. It is called exactly once by the C side via its
331                         // placement above in the initcall section.
332                         unsafe {{ __init() }}
333                     }}
334 
335                     #[cfg(not(MODULE))]
336                     #[doc(hidden)]
337                     #[no_mangle]
338                     pub extern \"C\" fn __{name}_exit() {{
339                         // SAFETY:
340                         // - This function is inaccessible to the outside due to the double
341                         //   module wrapping it. It is called exactly once by the C side via its
342                         //   unique name,
343                         // - furthermore it is only called after `__{name}_init` has returned `0`
344                         //   (which delegates to `__init`).
345                         unsafe {{ __exit() }}
346                     }}
347 
348                     /// # Safety
349                     ///
350                     /// This function must only be called once.
351                     unsafe fn __init() -> kernel::ffi::c_int {{
352                         let initer =
353                             <{type_} as kernel::InPlaceModule>::init(&super::super::THIS_MODULE);
354                         // SAFETY: No data race, since `__MOD` can only be accessed by this module
355                         // and there only `__init` and `__exit` access it. These functions are only
356                         // called once and `__exit` cannot be called before or during `__init`.
357                         match unsafe {{ initer.__pinned_init(__MOD.as_mut_ptr()) }} {{
358                             Ok(m) => 0,
359                             Err(e) => e.to_errno(),
360                         }}
361                     }}
362 
363                     /// # Safety
364                     ///
365                     /// This function must
366                     /// - only be called once,
367                     /// - be called after `__init` has been called and returned `0`.
368                     unsafe fn __exit() {{
369                         // SAFETY: No data race, since `__MOD` can only be accessed by this module
370                         // and there only `__init` and `__exit` access it. These functions are only
371                         // called once and `__init` was already called.
372                         unsafe {{
373                             // Invokes `drop()` on `__MOD`, which should be used for cleanup.
374                             __MOD.assume_init_drop();
375                         }}
376                     }}
377 
378                     {modinfo}
379                 }}
380             }}
381         ",
382         type_ = info.type_,
383         name = info.name,
384         modinfo = modinfo.buffer,
385         initcall_section = ".initcall6.init"
386     )
387     .parse()
388     .expect("Error parsing formatted string into token stream.")
389 }
390