1 // SPDX-License-Identifier: GPL-2.0
4 use proc_macro::{token_stream, Delimiter, Literal, TokenStream, TokenTree};
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();
13 while let Some(val) = try_string(&mut it) {
14 assert!(val.is_ascii(), "Expected ASCII string");
17 Some(TokenTree::Punct(punct)) => assert_eq!(punct.as_char(), ','),
19 _ => panic!("Expected ',' or end of array"),
25 struct ModInfoBuilder<'a> {
31 impl<'a> ModInfoBuilder<'a> {
32 fn new(module: &'a str) -> Self {
36 buffer: String::new(),
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.`.
44 "{module}.{field}={content}\0",
50 // Loadable modules' modinfo strings go as-is.
51 format!("{field}={content}\0", field = field, content = content)
59 #[link_section = \".modinfo\"]
61 pub static __{module}_{counter}: [u8; {length}] = *{string};
68 module = self.module.to_uppercase(),
69 counter = self.counter,
70 length = string.len(),
71 string = Literal::byte_string(string.as_bytes()),
78 fn emit_only_builtin(&mut self, field: &str, content: &str) {
79 self.emit_base(field, content, true)
82 fn emit_only_loadable(&mut self, field: &str, content: &str) {
83 self.emit_base(field, content, false)
86 fn emit(&mut self, field: &str, content: &str) {
87 self.emit_only_builtin(field, content);
88 self.emit_only_loadable(field, content);
92 #[derive(Debug, Default)]
97 author: Option<String>,
98 description: Option<String>,
99 alias: Option<Vec<String>>,
103 fn parse(it: &mut token_stream::IntoIter) -> Self {
104 let mut info = ModuleInfo::default();
106 const EXPECTED_KEYS: &[&str] =
107 &["type", "name", "author", "description", "license", "alias"];
108 const REQUIRED_KEYS: &[&str] = &["type", "name", "license"];
109 let mut seen_keys = Vec::new();
112 let key = match it.next() {
113 Some(TokenTree::Ident(ident)) => ident.to_string(),
114 Some(_) => panic!("Expected Ident or end"),
118 if seen_keys.contains(&key) {
120 "Duplicated key \"{}\". Keys can only be specified once.",
125 assert_eq!(expect_punct(it), ':');
128 "type" => info.type_ = expect_ident(it),
129 "name" => info.name = expect_string_ascii(it),
130 "author" => info.author = Some(expect_string(it)),
131 "description" => info.description = Some(expect_string(it)),
132 "license" => info.license = expect_string_ascii(it),
133 "alias" => info.alias = Some(expect_string_array(it)),
135 "Unknown key \"{}\". Valid keys are: {:?}.",
140 assert_eq!(expect_punct(it), ',');
147 for key in REQUIRED_KEYS {
148 if !seen_keys.iter().any(|e| e == key) {
149 panic!("Missing required key \"{}\".", key);
153 let mut ordered_keys: Vec<&str> = Vec::new();
154 for key in EXPECTED_KEYS {
155 if seen_keys.iter().any(|e| e == key) {
156 ordered_keys.push(key);
160 if seen_keys != ordered_keys {
162 "Keys are not ordered as expected. Order them like: {:?}.",
171 pub(crate) fn module(ts: TokenStream) -> TokenStream {
172 let mut it = ts.into_iter();
174 let info = ModuleInfo::parse(&mut it);
176 let mut modinfo = ModInfoBuilder::new(info.name.as_ref());
177 if let Some(author) = info.author {
178 modinfo.emit("author", &author);
180 if let Some(description) = info.description {
181 modinfo.emit("description", &description);
183 modinfo.emit("license", &info.license);
184 if let Some(aliases) = info.alias {
185 for alias in aliases {
186 modinfo.emit("alias", &alias);
190 // Built-in modules also export the `file` modinfo string.
192 std::env::var("RUST_MODFILE").expect("Unable to fetch RUST_MODFILE environmental variable");
193 modinfo.emit_only_builtin("file", &file);
199 /// Used by the printing macros, e.g. [`info!`].
200 const __LOG_PREFIX: &[u8] = b\"{name}\\0\";
202 /// The \"Rust loadable module\" mark.
204 // This may be best done another way later on, e.g. as a new modinfo
205 // key or a new section. For the moment, keep it simple.
209 static __IS_RUST_MODULE: () = ();
211 static mut __MOD: Option<{type_}> = None;
213 // SAFETY: `__this_module` is constructed by the kernel at load time and will not be
214 // freed until the module is unloaded.
216 static THIS_MODULE: kernel::ThisModule = unsafe {{
217 kernel::ThisModule::from_ptr(&kernel::bindings::__this_module as *const _ as *mut _)
220 static THIS_MODULE: kernel::ThisModule = unsafe {{
221 kernel::ThisModule::from_ptr(core::ptr::null_mut())
224 // Loadable modules need to export the `{{init,cleanup}}_module` identifiers.
228 pub extern \"C\" fn init_module() -> core::ffi::c_int {{
235 pub extern \"C\" fn cleanup_module() {{
239 // Built-in modules are initialized through an initcall pointer
240 // and the identifiers need to be unique.
242 #[cfg(not(CONFIG_HAVE_ARCH_PREL32_RELOCATIONS))]
244 #[link_section = \"{initcall_section}\"]
246 pub static __{name}_initcall: extern \"C\" fn() -> core::ffi::c_int = __{name}_init;
249 #[cfg(CONFIG_HAVE_ARCH_PREL32_RELOCATIONS)]
250 core::arch::global_asm!(
251 r#\".section \"{initcall_section}\", \"a\"
253 .long __{name}_init - .
261 pub extern \"C\" fn __{name}_init() -> core::ffi::c_int {{
268 pub extern \"C\" fn __{name}_exit() {{
272 fn __init() -> core::ffi::c_int {{
273 match <{type_} as kernel::Module>::init(&THIS_MODULE) {{
288 // Invokes `drop()` on `__MOD`, which should be used for cleanup.
297 modinfo = modinfo.buffer,
298 initcall_section = ".initcall6.init"
301 .expect("Error parsing formatted string into token stream.")