xref: /linux/rust/macros/module.rs (revision f637bafe1ff15fa356c1e0576c32f077b9e6e46a)
1 // SPDX-License-Identifier: GPL-2.0
2 
3 use std::fmt::Write;
4 
5 use proc_macro2::{token_stream, Delimiter, Literal, TokenStream, TokenTree};
6 
7 use crate::helpers::*;
8 
9 fn expect_string_array(it: &mut token_stream::IntoIter) -> Vec<String> {
10     let group = expect_group(it);
11     assert_eq!(group.delimiter(), Delimiter::Bracket);
12     let mut values = Vec::new();
13     let mut it = group.stream().into_iter();
14 
15     while let Some(val) = try_string(&mut it) {
16         assert!(val.is_ascii(), "Expected ASCII string");
17         values.push(val);
18         match it.next() {
19             Some(TokenTree::Punct(punct)) => assert_eq!(punct.as_char(), ','),
20             None => break,
21             _ => panic!("Expected ',' or end of array"),
22         }
23     }
24     values
25 }
26 
27 struct ModInfoBuilder<'a> {
28     module: &'a str,
29     counter: usize,
30     buffer: String,
31     param_buffer: String,
32 }
33 
34 impl<'a> ModInfoBuilder<'a> {
35     fn new(module: &'a str) -> Self {
36         ModInfoBuilder {
37             module,
38             counter: 0,
39             buffer: String::new(),
40             param_buffer: String::new(),
41         }
42     }
43 
44     fn emit_base(&mut self, field: &str, content: &str, builtin: bool, param: bool) {
45         let string = if builtin {
46             // Built-in modules prefix their modinfo strings by `module.`.
47             format!(
48                 "{module}.{field}={content}\0",
49                 module = self.module,
50                 field = field,
51                 content = content
52             )
53         } else {
54             // Loadable modules' modinfo strings go as-is.
55             format!("{field}={content}\0")
56         };
57 
58         let buffer = if param {
59             &mut self.param_buffer
60         } else {
61             &mut self.buffer
62         };
63 
64         write!(
65             buffer,
66             "
67                 {cfg}
68                 #[doc(hidden)]
69                 #[cfg_attr(not(target_os = \"macos\"), link_section = \".modinfo\")]
70                 #[used(compiler)]
71                 pub static __{module}_{counter}: [u8; {length}] = *{string};
72             ",
73             cfg = if builtin {
74                 "#[cfg(not(MODULE))]"
75             } else {
76                 "#[cfg(MODULE)]"
77             },
78             module = self.module.to_uppercase(),
79             counter = self.counter,
80             length = string.len(),
81             string = Literal::byte_string(string.as_bytes()),
82         )
83         .unwrap();
84 
85         self.counter += 1;
86     }
87 
88     fn emit_only_builtin(&mut self, field: &str, content: &str, param: bool) {
89         self.emit_base(field, content, true, param)
90     }
91 
92     fn emit_only_loadable(&mut self, field: &str, content: &str, param: bool) {
93         self.emit_base(field, content, false, param)
94     }
95 
96     fn emit(&mut self, field: &str, content: &str) {
97         self.emit_internal(field, content, false);
98     }
99 
100     fn emit_internal(&mut self, field: &str, content: &str, param: bool) {
101         self.emit_only_builtin(field, content, param);
102         self.emit_only_loadable(field, content, param);
103     }
104 
105     fn emit_param(&mut self, field: &str, param: &str, content: &str) {
106         let content = format!("{param}:{content}", param = param, content = content);
107         self.emit_internal(field, &content, true);
108     }
109 
110     fn emit_params(&mut self, info: &ModuleInfo) {
111         let Some(params) = &info.params else {
112             return;
113         };
114 
115         for param in params {
116             let ops = param_ops_path(&param.ptype);
117 
118             // Note: The spelling of these fields is dictated by the user space
119             // tool `modinfo`.
120             self.emit_param("parmtype", &param.name, &param.ptype);
121             self.emit_param("parm", &param.name, &param.description);
122 
123             write!(
124                 self.param_buffer,
125                 "
126                 pub(crate) static {param_name}:
127                     ::kernel::module_param::ModuleParamAccess<{param_type}> =
128                         ::kernel::module_param::ModuleParamAccess::new({param_default});
129 
130                 const _: () = {{
131                     #[link_section = \"__param\"]
132                     #[used]
133                     static __{module_name}_{param_name}_struct:
134                         ::kernel::module_param::KernelParam =
135                         ::kernel::module_param::KernelParam::new(
136                             ::kernel::bindings::kernel_param {{
137                                 name: if ::core::cfg!(MODULE) {{
138                                     ::kernel::c_str!(\"{param_name}\").to_bytes_with_nul()
139                                 }} else {{
140                                     ::kernel::c_str!(\"{module_name}.{param_name}\")
141                                         .to_bytes_with_nul()
142                                 }}.as_ptr(),
143                                 // SAFETY: `__this_module` is constructed by the kernel at load
144                                 // time and will not be freed until the module is unloaded.
145                                 #[cfg(MODULE)]
146                                 mod_: unsafe {{
147                                     core::ptr::from_ref(&::kernel::bindings::__this_module)
148                                         .cast_mut()
149                                 }},
150                                 #[cfg(not(MODULE))]
151                                 mod_: ::core::ptr::null_mut(),
152                                 ops: core::ptr::from_ref(&{ops}),
153                                 perm: 0, // Will not appear in sysfs
154                                 level: -1,
155                                 flags: 0,
156                                 __bindgen_anon_1: ::kernel::bindings::kernel_param__bindgen_ty_1 {{
157                                     arg: {param_name}.as_void_ptr()
158                                 }},
159                             }}
160                         );
161                 }};
162                 ",
163                 module_name = info.name,
164                 param_type = param.ptype,
165                 param_default = param.default,
166                 param_name = param.name,
167                 ops = ops,
168             )
169             .unwrap();
170         }
171     }
172 }
173 
174 fn param_ops_path(param_type: &str) -> &'static str {
175     match param_type {
176         "i8" => "::kernel::module_param::PARAM_OPS_I8",
177         "u8" => "::kernel::module_param::PARAM_OPS_U8",
178         "i16" => "::kernel::module_param::PARAM_OPS_I16",
179         "u16" => "::kernel::module_param::PARAM_OPS_U16",
180         "i32" => "::kernel::module_param::PARAM_OPS_I32",
181         "u32" => "::kernel::module_param::PARAM_OPS_U32",
182         "i64" => "::kernel::module_param::PARAM_OPS_I64",
183         "u64" => "::kernel::module_param::PARAM_OPS_U64",
184         "isize" => "::kernel::module_param::PARAM_OPS_ISIZE",
185         "usize" => "::kernel::module_param::PARAM_OPS_USIZE",
186         t => panic!("Unsupported parameter type {}", t),
187     }
188 }
189 
190 fn expect_param_default(param_it: &mut token_stream::IntoIter) -> String {
191     assert_eq!(expect_ident(param_it), "default");
192     assert_eq!(expect_punct(param_it), ':');
193     let sign = try_sign(param_it);
194     let default = try_literal(param_it).expect("Expected default param value");
195     assert_eq!(expect_punct(param_it), ',');
196     let mut value = sign.map(String::from).unwrap_or_default();
197     value.push_str(&default);
198     value
199 }
200 
201 #[derive(Debug, Default)]
202 struct ModuleInfo {
203     type_: String,
204     license: String,
205     name: String,
206     authors: Option<Vec<String>>,
207     description: Option<String>,
208     alias: Option<Vec<String>>,
209     firmware: Option<Vec<String>>,
210     imports_ns: Option<Vec<String>>,
211     params: Option<Vec<Parameter>>,
212 }
213 
214 #[derive(Debug)]
215 struct Parameter {
216     name: String,
217     ptype: String,
218     default: String,
219     description: String,
220 }
221 
222 fn expect_params(it: &mut token_stream::IntoIter) -> Vec<Parameter> {
223     let params = expect_group(it);
224     assert_eq!(params.delimiter(), Delimiter::Brace);
225     let mut it = params.stream().into_iter();
226     let mut parsed = Vec::new();
227 
228     loop {
229         let param_name = match it.next() {
230             Some(TokenTree::Ident(ident)) => ident.to_string(),
231             Some(_) => panic!("Expected Ident or end"),
232             None => break,
233         };
234 
235         assert_eq!(expect_punct(&mut it), ':');
236         let param_type = expect_ident(&mut it);
237         let group = expect_group(&mut it);
238         assert_eq!(group.delimiter(), Delimiter::Brace);
239         assert_eq!(expect_punct(&mut it), ',');
240 
241         let mut param_it = group.stream().into_iter();
242         let param_default = expect_param_default(&mut param_it);
243         let param_description = expect_string_field(&mut param_it, "description");
244         expect_end(&mut param_it);
245 
246         parsed.push(Parameter {
247             name: param_name,
248             ptype: param_type,
249             default: param_default,
250             description: param_description,
251         })
252     }
253 
254     parsed
255 }
256 
257 impl ModuleInfo {
258     fn parse(it: &mut token_stream::IntoIter) -> Self {
259         let mut info = ModuleInfo::default();
260 
261         const EXPECTED_KEYS: &[&str] = &[
262             "type",
263             "name",
264             "authors",
265             "description",
266             "license",
267             "alias",
268             "firmware",
269             "imports_ns",
270             "params",
271         ];
272         const REQUIRED_KEYS: &[&str] = &["type", "name", "license"];
273         let mut seen_keys = Vec::new();
274 
275         loop {
276             let key = match it.next() {
277                 Some(TokenTree::Ident(ident)) => ident.to_string(),
278                 Some(_) => panic!("Expected Ident or end"),
279                 None => break,
280             };
281 
282             if seen_keys.contains(&key) {
283                 panic!("Duplicated key \"{key}\". Keys can only be specified once.");
284             }
285 
286             assert_eq!(expect_punct(it), ':');
287 
288             match key.as_str() {
289                 "type" => info.type_ = expect_ident(it),
290                 "name" => info.name = expect_string_ascii(it),
291                 "authors" => info.authors = Some(expect_string_array(it)),
292                 "description" => info.description = Some(expect_string(it)),
293                 "license" => info.license = expect_string_ascii(it),
294                 "alias" => info.alias = Some(expect_string_array(it)),
295                 "firmware" => info.firmware = Some(expect_string_array(it)),
296                 "imports_ns" => info.imports_ns = Some(expect_string_array(it)),
297                 "params" => info.params = Some(expect_params(it)),
298                 _ => panic!("Unknown key \"{key}\". Valid keys are: {EXPECTED_KEYS:?}."),
299             }
300 
301             assert_eq!(expect_punct(it), ',');
302 
303             seen_keys.push(key);
304         }
305 
306         expect_end(it);
307 
308         for key in REQUIRED_KEYS {
309             if !seen_keys.iter().any(|e| e == key) {
310                 panic!("Missing required key \"{key}\".");
311             }
312         }
313 
314         let mut ordered_keys: Vec<&str> = Vec::new();
315         for key in EXPECTED_KEYS {
316             if seen_keys.iter().any(|e| e == key) {
317                 ordered_keys.push(key);
318             }
319         }
320 
321         if seen_keys != ordered_keys {
322             panic!("Keys are not ordered as expected. Order them like: {ordered_keys:?}.");
323         }
324 
325         info
326     }
327 }
328 
329 pub(crate) fn module(ts: TokenStream) -> TokenStream {
330     let mut it = ts.into_iter();
331 
332     let info = ModuleInfo::parse(&mut it);
333 
334     // Rust does not allow hyphens in identifiers, use underscore instead.
335     let ident = info.name.replace('-', "_");
336     let mut modinfo = ModInfoBuilder::new(ident.as_ref());
337     if let Some(authors) = &info.authors {
338         for author in authors {
339             modinfo.emit("author", author);
340         }
341     }
342     if let Some(description) = &info.description {
343         modinfo.emit("description", description);
344     }
345     modinfo.emit("license", &info.license);
346     if let Some(aliases) = &info.alias {
347         for alias in aliases {
348             modinfo.emit("alias", alias);
349         }
350     }
351     if let Some(firmware) = &info.firmware {
352         for fw in firmware {
353             modinfo.emit("firmware", fw);
354         }
355     }
356     if let Some(imports) = &info.imports_ns {
357         for ns in imports {
358             modinfo.emit("import_ns", ns);
359         }
360     }
361 
362     // Built-in modules also export the `file` modinfo string.
363     let file =
364         std::env::var("RUST_MODFILE").expect("Unable to fetch RUST_MODFILE environmental variable");
365     modinfo.emit_only_builtin("file", &file, false);
366 
367     modinfo.emit_params(&info);
368 
369     format!(
370         "
371             /// The module name.
372             ///
373             /// Used by the printing macros, e.g. [`info!`].
374             const __LOG_PREFIX: &[u8] = b\"{name}\\0\";
375 
376             // SAFETY: `__this_module` is constructed by the kernel at load time and will not be
377             // freed until the module is unloaded.
378             #[cfg(MODULE)]
379             static THIS_MODULE: ::kernel::ThisModule = unsafe {{
380                 extern \"C\" {{
381                     static __this_module: ::kernel::types::Opaque<::kernel::bindings::module>;
382                 }}
383 
384                 ::kernel::ThisModule::from_ptr(__this_module.get())
385             }};
386             #[cfg(not(MODULE))]
387             static THIS_MODULE: ::kernel::ThisModule = unsafe {{
388                 ::kernel::ThisModule::from_ptr(::core::ptr::null_mut())
389             }};
390 
391             /// The `LocalModule` type is the type of the module created by `module!`,
392             /// `module_pci_driver!`, `module_platform_driver!`, etc.
393             type LocalModule = {type_};
394 
395             impl ::kernel::ModuleMetadata for {type_} {{
396                 const NAME: &'static ::kernel::str::CStr = c\"{name}\";
397             }}
398 
399             // Double nested modules, since then nobody can access the public items inside.
400             mod __module_init {{
401                 mod __module_init {{
402                     use super::super::{type_};
403                     use pin_init::PinInit;
404 
405                     /// The \"Rust loadable module\" mark.
406                     //
407                     // This may be best done another way later on, e.g. as a new modinfo
408                     // key or a new section. For the moment, keep it simple.
409                     #[cfg(MODULE)]
410                     #[doc(hidden)]
411                     #[used(compiler)]
412                     static __IS_RUST_MODULE: () = ();
413 
414                     static mut __MOD: ::core::mem::MaybeUninit<{type_}> =
415                         ::core::mem::MaybeUninit::uninit();
416 
417                     // Loadable modules need to export the `{{init,cleanup}}_module` identifiers.
418                     /// # Safety
419                     ///
420                     /// This function must not be called after module initialization, because it may be
421                     /// freed after that completes.
422                     #[cfg(MODULE)]
423                     #[doc(hidden)]
424                     #[no_mangle]
425                     #[link_section = \".init.text\"]
426                     pub unsafe extern \"C\" fn init_module() -> ::kernel::ffi::c_int {{
427                         // SAFETY: This function is inaccessible to the outside due to the double
428                         // module wrapping it. It is called exactly once by the C side via its
429                         // unique name.
430                         unsafe {{ __init() }}
431                     }}
432 
433                     #[cfg(MODULE)]
434                     #[doc(hidden)]
435                     #[used(compiler)]
436                     #[link_section = \".init.data\"]
437                     static __UNIQUE_ID___addressable_init_module: unsafe extern \"C\" fn() -> i32 = init_module;
438 
439                     #[cfg(MODULE)]
440                     #[doc(hidden)]
441                     #[no_mangle]
442                     #[link_section = \".exit.text\"]
443                     pub extern \"C\" fn cleanup_module() {{
444                         // SAFETY:
445                         // - This function is inaccessible to the outside due to the double
446                         //   module wrapping it. It is called exactly once by the C side via its
447                         //   unique name,
448                         // - furthermore it is only called after `init_module` has returned `0`
449                         //   (which delegates to `__init`).
450                         unsafe {{ __exit() }}
451                     }}
452 
453                     #[cfg(MODULE)]
454                     #[doc(hidden)]
455                     #[used(compiler)]
456                     #[link_section = \".exit.data\"]
457                     static __UNIQUE_ID___addressable_cleanup_module: extern \"C\" fn() = cleanup_module;
458 
459                     // Built-in modules are initialized through an initcall pointer
460                     // and the identifiers need to be unique.
461                     #[cfg(not(MODULE))]
462                     #[cfg(not(CONFIG_HAVE_ARCH_PREL32_RELOCATIONS))]
463                     #[doc(hidden)]
464                     #[link_section = \"{initcall_section}\"]
465                     #[used(compiler)]
466                     pub static __{ident}_initcall: extern \"C\" fn() ->
467                         ::kernel::ffi::c_int = __{ident}_init;
468 
469                     #[cfg(not(MODULE))]
470                     #[cfg(CONFIG_HAVE_ARCH_PREL32_RELOCATIONS)]
471                     ::core::arch::global_asm!(
472                         r#\".section \"{initcall_section}\", \"a\"
473                         __{ident}_initcall:
474                             .long   __{ident}_init - .
475                             .previous
476                         \"#
477                     );
478 
479                     #[cfg(not(MODULE))]
480                     #[doc(hidden)]
481                     #[no_mangle]
482                     pub extern \"C\" fn __{ident}_init() -> ::kernel::ffi::c_int {{
483                         // SAFETY: This function is inaccessible to the outside due to the double
484                         // module wrapping it. It is called exactly once by the C side via its
485                         // placement above in the initcall section.
486                         unsafe {{ __init() }}
487                     }}
488 
489                     #[cfg(not(MODULE))]
490                     #[doc(hidden)]
491                     #[no_mangle]
492                     pub extern \"C\" fn __{ident}_exit() {{
493                         // SAFETY:
494                         // - This function is inaccessible to the outside due to the double
495                         //   module wrapping it. It is called exactly once by the C side via its
496                         //   unique name,
497                         // - furthermore it is only called after `__{ident}_init` has
498                         //   returned `0` (which delegates to `__init`).
499                         unsafe {{ __exit() }}
500                     }}
501 
502                     /// # Safety
503                     ///
504                     /// This function must only be called once.
505                     unsafe fn __init() -> ::kernel::ffi::c_int {{
506                         let initer =
507                             <{type_} as ::kernel::InPlaceModule>::init(&super::super::THIS_MODULE);
508                         // SAFETY: No data race, since `__MOD` can only be accessed by this module
509                         // and there only `__init` and `__exit` access it. These functions are only
510                         // called once and `__exit` cannot be called before or during `__init`.
511                         match unsafe {{ initer.__pinned_init(__MOD.as_mut_ptr()) }} {{
512                             Ok(m) => 0,
513                             Err(e) => e.to_errno(),
514                         }}
515                     }}
516 
517                     /// # Safety
518                     ///
519                     /// This function must
520                     /// - only be called once,
521                     /// - be called after `__init` has been called and returned `0`.
522                     unsafe fn __exit() {{
523                         // SAFETY: No data race, since `__MOD` can only be accessed by this module
524                         // and there only `__init` and `__exit` access it. These functions are only
525                         // called once and `__init` was already called.
526                         unsafe {{
527                             // Invokes `drop()` on `__MOD`, which should be used for cleanup.
528                             __MOD.assume_init_drop();
529                         }}
530                     }}
531                     {modinfo}
532                 }}
533             }}
534             mod module_parameters {{
535                 {params}
536             }}
537         ",
538         type_ = info.type_,
539         name = info.name,
540         ident = ident,
541         modinfo = modinfo.buffer,
542         params = modinfo.param_buffer,
543         initcall_section = ".initcall6.init"
544     )
545     .parse()
546     .expect("Error parsing formatted string into token stream.")
547 }
548