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", 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)]
93struct 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
103impl 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
180pub(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                extern \"C\" {{
221                    static __this_module: kernel::types::Opaque<kernel::bindings::module>;
222                }}
223
224                kernel::ThisModule::from_ptr(__this_module.get())
225            }};
226            #[cfg(not(MODULE))]
227            static THIS_MODULE: kernel::ThisModule = unsafe {{
228                kernel::ThisModule::from_ptr(core::ptr::null_mut())
229            }};
230
231            impl kernel::ModuleMetadata for {type_} {{
232                const NAME: &'static kernel::str::CStr = kernel::c_str!(\"{name}\");
233            }}
234
235            // Double nested modules, since then nobody can access the public items inside.
236            mod __module_init {{
237                mod __module_init {{
238                    use super::super::{type_};
239                    use kernel::init::PinInit;
240
241                    /// The \"Rust loadable module\" mark.
242                    //
243                    // This may be best done another way later on, e.g. as a new modinfo
244                    // key or a new section. For the moment, keep it simple.
245                    #[cfg(MODULE)]
246                    #[doc(hidden)]
247                    #[used]
248                    static __IS_RUST_MODULE: () = ();
249
250                    static mut __MOD: core::mem::MaybeUninit<{type_}> =
251                        core::mem::MaybeUninit::uninit();
252
253                    // Loadable modules need to export the `{{init,cleanup}}_module` identifiers.
254                    /// # Safety
255                    ///
256                    /// This function must not be called after module initialization, because it may be
257                    /// freed after that completes.
258                    #[cfg(MODULE)]
259                    #[doc(hidden)]
260                    #[no_mangle]
261                    #[link_section = \".init.text\"]
262                    pub unsafe extern \"C\" fn init_module() -> kernel::ffi::c_int {{
263                        // SAFETY: This function is inaccessible to the outside due to the double
264                        // module wrapping it. It is called exactly once by the C side via its
265                        // unique name.
266                        unsafe {{ __init() }}
267                    }}
268
269                    #[cfg(MODULE)]
270                    #[doc(hidden)]
271                    #[used]
272                    #[link_section = \".init.data\"]
273                    static __UNIQUE_ID___addressable_init_module: unsafe extern \"C\" fn() -> i32 = init_module;
274
275                    #[cfg(MODULE)]
276                    #[doc(hidden)]
277                    #[no_mangle]
278                    pub extern \"C\" fn cleanup_module() {{
279                        // SAFETY:
280                        // - This function is inaccessible to the outside due to the double
281                        //   module wrapping it. It is called exactly once by the C side via its
282                        //   unique name,
283                        // - furthermore it is only called after `init_module` has returned `0`
284                        //   (which delegates to `__init`).
285                        unsafe {{ __exit() }}
286                    }}
287
288                    #[cfg(MODULE)]
289                    #[doc(hidden)]
290                    #[used]
291                    #[link_section = \".exit.data\"]
292                    static __UNIQUE_ID___addressable_cleanup_module: extern \"C\" fn() = cleanup_module;
293
294                    // Built-in modules are initialized through an initcall pointer
295                    // and the identifiers need to be unique.
296                    #[cfg(not(MODULE))]
297                    #[cfg(not(CONFIG_HAVE_ARCH_PREL32_RELOCATIONS))]
298                    #[doc(hidden)]
299                    #[link_section = \"{initcall_section}\"]
300                    #[used]
301                    pub static __{name}_initcall: extern \"C\" fn() -> kernel::ffi::c_int = __{name}_init;
302
303                    #[cfg(not(MODULE))]
304                    #[cfg(CONFIG_HAVE_ARCH_PREL32_RELOCATIONS)]
305                    core::arch::global_asm!(
306                        r#\".section \"{initcall_section}\", \"a\"
307                        __{name}_initcall:
308                            .long   __{name}_init - .
309                            .previous
310                        \"#
311                    );
312
313                    #[cfg(not(MODULE))]
314                    #[doc(hidden)]
315                    #[no_mangle]
316                    pub extern \"C\" fn __{name}_init() -> kernel::ffi::c_int {{
317                        // SAFETY: This function is inaccessible to the outside due to the double
318                        // module wrapping it. It is called exactly once by the C side via its
319                        // placement above in the initcall section.
320                        unsafe {{ __init() }}
321                    }}
322
323                    #[cfg(not(MODULE))]
324                    #[doc(hidden)]
325                    #[no_mangle]
326                    pub extern \"C\" fn __{name}_exit() {{
327                        // SAFETY:
328                        // - This function is inaccessible to the outside due to the double
329                        //   module wrapping it. It is called exactly once by the C side via its
330                        //   unique name,
331                        // - furthermore it is only called after `__{name}_init` has returned `0`
332                        //   (which delegates to `__init`).
333                        unsafe {{ __exit() }}
334                    }}
335
336                    /// # Safety
337                    ///
338                    /// This function must only be called once.
339                    unsafe fn __init() -> kernel::ffi::c_int {{
340                        let initer =
341                            <{type_} as kernel::InPlaceModule>::init(&super::super::THIS_MODULE);
342                        // SAFETY: No data race, since `__MOD` can only be accessed by this module
343                        // and there only `__init` and `__exit` access it. These functions are only
344                        // called once and `__exit` cannot be called before or during `__init`.
345                        match unsafe {{ initer.__pinned_init(__MOD.as_mut_ptr()) }} {{
346                            Ok(m) => 0,
347                            Err(e) => e.to_errno(),
348                        }}
349                    }}
350
351                    /// # Safety
352                    ///
353                    /// This function must
354                    /// - only be called once,
355                    /// - be called after `__init` has been called and returned `0`.
356                    unsafe fn __exit() {{
357                        // SAFETY: No data race, since `__MOD` can only be accessed by this module
358                        // and there only `__init` and `__exit` access it. These functions are only
359                        // called once and `__init` was already called.
360                        unsafe {{
361                            // Invokes `drop()` on `__MOD`, which should be used for cleanup.
362                            __MOD.assume_init_drop();
363                        }}
364                    }}
365
366                    {modinfo}
367                }}
368            }}
369        ",
370        type_ = info.type_,
371        name = info.name,
372        modinfo = modinfo.buffer,
373        initcall_section = ".initcall6.init"
374    )
375    .parse()
376    .expect("Error parsing formatted string into token stream.")
377}