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