macros/
module.rs

1// SPDX-License-Identifier: GPL-2.0
2
3use crate::helpers::*;
4use proc_macro::{token_stream, Delimiter, Literal, TokenStream, TokenTree};
5use std::fmt::Write;
6
7fn 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
25struct ModInfoBuilder<'a> {
26    module: &'a str,
27    counter: usize,
28    buffer: String,
29}
30
31impl<'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")
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)]
93struct 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
104impl 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!("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
174pub(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 name_identifier = info.name.replace('-', "_");
181    let mut modinfo = ModInfoBuilder::new(name_identifier.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                    pub extern \"C\" fn cleanup_module() {{
284                        // SAFETY:
285                        // - This function is inaccessible to the outside due to the double
286                        //   module wrapping it. It is called exactly once by the C side via its
287                        //   unique name,
288                        // - furthermore it is only called after `init_module` has returned `0`
289                        //   (which delegates to `__init`).
290                        unsafe {{ __exit() }}
291                    }}
292
293                    #[cfg(MODULE)]
294                    #[doc(hidden)]
295                    #[used]
296                    #[link_section = \".exit.data\"]
297                    static __UNIQUE_ID___addressable_cleanup_module: extern \"C\" fn() = cleanup_module;
298
299                    // Built-in modules are initialized through an initcall pointer
300                    // and the identifiers need to be unique.
301                    #[cfg(not(MODULE))]
302                    #[cfg(not(CONFIG_HAVE_ARCH_PREL32_RELOCATIONS))]
303                    #[doc(hidden)]
304                    #[link_section = \"{initcall_section}\"]
305                    #[used]
306                    pub static __{name_identifier}_initcall: extern \"C\" fn() ->
307                        kernel::ffi::c_int = __{name_identifier}_init;
308
309                    #[cfg(not(MODULE))]
310                    #[cfg(CONFIG_HAVE_ARCH_PREL32_RELOCATIONS)]
311                    core::arch::global_asm!(
312                        r#\".section \"{initcall_section}\", \"a\"
313                        __{name_identifier}_initcall:
314                            .long   __{name_identifier}_init - .
315                            .previous
316                        \"#
317                    );
318
319                    #[cfg(not(MODULE))]
320                    #[doc(hidden)]
321                    #[no_mangle]
322                    pub extern \"C\" fn __{name_identifier}_init() -> kernel::ffi::c_int {{
323                        // SAFETY: This function is inaccessible to the outside due to the double
324                        // module wrapping it. It is called exactly once by the C side via its
325                        // placement above in the initcall section.
326                        unsafe {{ __init() }}
327                    }}
328
329                    #[cfg(not(MODULE))]
330                    #[doc(hidden)]
331                    #[no_mangle]
332                    pub extern \"C\" fn __{name_identifier}_exit() {{
333                        // SAFETY:
334                        // - This function is inaccessible to the outside due to the double
335                        //   module wrapping it. It is called exactly once by the C side via its
336                        //   unique name,
337                        // - furthermore it is only called after `__{name_identifier}_init` has
338                        //   returned `0` (which delegates to `__init`).
339                        unsafe {{ __exit() }}
340                    }}
341
342                    /// # Safety
343                    ///
344                    /// This function must only be called once.
345                    unsafe fn __init() -> kernel::ffi::c_int {{
346                        let initer =
347                            <{type_} as kernel::InPlaceModule>::init(&super::super::THIS_MODULE);
348                        // SAFETY: No data race, since `__MOD` can only be accessed by this module
349                        // and there only `__init` and `__exit` access it. These functions are only
350                        // called once and `__exit` cannot be called before or during `__init`.
351                        match unsafe {{ initer.__pinned_init(__MOD.as_mut_ptr()) }} {{
352                            Ok(m) => 0,
353                            Err(e) => e.to_errno(),
354                        }}
355                    }}
356
357                    /// # Safety
358                    ///
359                    /// This function must
360                    /// - only be called once,
361                    /// - be called after `__init` has been called and returned `0`.
362                    unsafe fn __exit() {{
363                        // SAFETY: No data race, since `__MOD` can only be accessed by this module
364                        // and there only `__init` and `__exit` access it. These functions are only
365                        // called once and `__init` was already called.
366                        unsafe {{
367                            // Invokes `drop()` on `__MOD`, which should be used for cleanup.
368                            __MOD.assume_init_drop();
369                        }}
370                    }}
371
372                    {modinfo}
373                }}
374            }}
375        ",
376        type_ = info.type_,
377        name = info.name,
378        name_identifier = name_identifier,
379        modinfo = modinfo.buffer,
380        initcall_section = ".initcall6.init"
381    )
382    .parse()
383    .expect("Error parsing formatted string into token stream.")
384}