1 // SPDX-License-Identifier: GPL-2.0
4 use proc_macro::{token_stream, Literal, TokenStream, TokenTree};
7 struct ModInfoBuilder<'a> {
13 impl<'a> ModInfoBuilder<'a> {
14 fn new(module: &'a str) -> Self {
18 buffer: String::new(),
22 fn emit_base(&mut self, field: &str, content: &str, builtin: bool) {
23 let string = if builtin {
24 // Built-in modules prefix their modinfo strings by `module.`.
26 "{module}.{field}={content}\0",
32 // Loadable modules' modinfo strings go as-is.
33 format!("{field}={content}\0", field = field, content = content)
41 #[link_section = \".modinfo\"]
43 pub static __{module}_{counter}: [u8; {length}] = *{string};
50 module = self.module.to_uppercase(),
51 counter = self.counter,
52 length = string.len(),
53 string = Literal::byte_string(string.as_bytes()),
60 fn emit_only_builtin(&mut self, field: &str, content: &str) {
61 self.emit_base(field, content, true)
64 fn emit_only_loadable(&mut self, field: &str, content: &str) {
65 self.emit_base(field, content, false)
68 fn emit(&mut self, field: &str, content: &str) {
69 self.emit_only_builtin(field, content);
70 self.emit_only_loadable(field, content);
74 #[derive(Debug, Default)]
79 author: Option<String>,
80 description: Option<String>,
81 alias: Option<String>,
85 fn parse(it: &mut token_stream::IntoIter) -> Self {
86 let mut info = ModuleInfo::default();
88 const EXPECTED_KEYS: &[&str] =
89 &["type", "name", "author", "description", "license", "alias"];
90 const REQUIRED_KEYS: &[&str] = &["type", "name", "license"];
91 let mut seen_keys = Vec::new();
94 let key = match it.next() {
95 Some(TokenTree::Ident(ident)) => ident.to_string(),
96 Some(_) => panic!("Expected Ident or end"),
100 if seen_keys.contains(&key) {
102 "Duplicated key \"{}\". Keys can only be specified once.",
107 assert_eq!(expect_punct(it), ':');
110 "type" => info.type_ = expect_ident(it),
111 "name" => info.name = expect_byte_string(it),
112 "author" => info.author = Some(expect_byte_string(it)),
113 "description" => info.description = Some(expect_byte_string(it)),
114 "license" => info.license = expect_byte_string(it),
115 "alias" => info.alias = Some(expect_byte_string(it)),
117 "Unknown key \"{}\". Valid keys are: {:?}.",
122 assert_eq!(expect_punct(it), ',');
129 for key in REQUIRED_KEYS {
130 if !seen_keys.iter().any(|e| e == key) {
131 panic!("Missing required key \"{}\".", key);
135 let mut ordered_keys: Vec<&str> = Vec::new();
136 for key in EXPECTED_KEYS {
137 if seen_keys.iter().any(|e| e == key) {
138 ordered_keys.push(key);
142 if seen_keys != ordered_keys {
144 "Keys are not ordered as expected. Order them like: {:?}.",
153 pub(crate) fn module(ts: TokenStream) -> TokenStream {
154 let mut it = ts.into_iter();
156 let info = ModuleInfo::parse(&mut it);
158 let mut modinfo = ModInfoBuilder::new(info.name.as_ref());
159 if let Some(author) = info.author {
160 modinfo.emit("author", &author);
162 if let Some(description) = info.description {
163 modinfo.emit("description", &description);
165 modinfo.emit("license", &info.license);
166 if let Some(alias) = info.alias {
167 modinfo.emit("alias", &alias);
170 // Built-in modules also export the `file` modinfo string.
172 std::env::var("RUST_MODFILE").expect("Unable to fetch RUST_MODFILE environmental variable");
173 modinfo.emit_only_builtin("file", &file);
179 /// Used by the printing macros, e.g. [`info!`].
180 const __LOG_PREFIX: &[u8] = b\"{name}\\0\";
182 /// The \"Rust loadable module\" mark, for `scripts/is_rust_module.sh`.
184 // This may be best done another way later on, e.g. as a new modinfo
185 // key or a new section. For the moment, keep it simple.
189 static __IS_RUST_MODULE: () = ();
191 static mut __MOD: Option<{type_}> = None;
193 // SAFETY: `__this_module` is constructed by the kernel at load time and will not be
194 // freed until the module is unloaded.
196 static THIS_MODULE: kernel::ThisModule = unsafe {{
197 kernel::ThisModule::from_ptr(&kernel::bindings::__this_module as *const _ as *mut _)
200 static THIS_MODULE: kernel::ThisModule = unsafe {{
201 kernel::ThisModule::from_ptr(core::ptr::null_mut())
204 // Loadable modules need to export the `{{init,cleanup}}_module` identifiers.
208 pub extern \"C\" fn init_module() -> core::ffi::c_int {{
215 pub extern \"C\" fn cleanup_module() {{
219 // Built-in modules are initialized through an initcall pointer
220 // and the identifiers need to be unique.
222 #[cfg(not(CONFIG_HAVE_ARCH_PREL32_RELOCATIONS))]
224 #[link_section = \"{initcall_section}\"]
226 pub static __{name}_initcall: extern \"C\" fn() -> core::ffi::c_int = __{name}_init;
229 #[cfg(CONFIG_HAVE_ARCH_PREL32_RELOCATIONS)]
230 core::arch::global_asm!(
231 r#\".section \"{initcall_section}\", \"a\"
233 .long __{name}_init - .
241 pub extern \"C\" fn __{name}_init() -> core::ffi::c_int {{
248 pub extern \"C\" fn __{name}_exit() {{
252 fn __init() -> core::ffi::c_int {{
253 match <{type_} as kernel::Module>::init(&THIS_MODULE) {{
261 return e.to_kernel_errno();
268 // Invokes `drop()` on `__MOD`, which should be used for cleanup.
277 modinfo = modinfo.buffer,
278 initcall_section = ".initcall6.init"
281 .expect("Error parsing formatted string into token stream.")