1 // SPDX-License-Identifier: GPL-2.0 2 3 use crate::helpers::*; 4 use proc_macro::{token_stream, Delimiter, Literal, TokenStream, TokenTree}; 5 use std::fmt::Write; 6 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(); 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 25 struct ModInfoBuilder<'a> { 26 module: &'a str, 27 counter: usize, 28 buffer: String, 29 } 30 31 impl<'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)] 93 struct 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 104 impl 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!( 130 "Duplicated key \"{}\". Keys can only be specified once.", 131 key 132 ); 133 } 134 135 assert_eq!(expect_punct(it), ':'); 136 137 match key.as_str() { 138 "type" => info.type_ = expect_ident(it), 139 "name" => info.name = expect_string_ascii(it), 140 "author" => info.author = Some(expect_string(it)), 141 "authors" => info.authors = Some(expect_string_array(it)), 142 "description" => info.description = Some(expect_string(it)), 143 "license" => info.license = expect_string_ascii(it), 144 "alias" => info.alias = Some(expect_string_array(it)), 145 "firmware" => info.firmware = Some(expect_string_array(it)), 146 _ => panic!( 147 "Unknown key \"{}\". Valid keys are: {:?}.", 148 key, EXPECTED_KEYS 149 ), 150 } 151 152 assert_eq!(expect_punct(it), ','); 153 154 seen_keys.push(key); 155 } 156 157 expect_end(it); 158 159 for key in REQUIRED_KEYS { 160 if !seen_keys.iter().any(|e| e == key) { 161 panic!("Missing required key \"{}\".", key); 162 } 163 } 164 165 let mut ordered_keys: Vec<&str> = Vec::new(); 166 for key in EXPECTED_KEYS { 167 if seen_keys.iter().any(|e| e == key) { 168 ordered_keys.push(key); 169 } 170 } 171 172 if seen_keys != ordered_keys { 173 panic!( 174 "Keys are not ordered as expected. Order them like: {:?}.", 175 ordered_keys 176 ); 177 } 178 179 info 180 } 181 } 182 183 pub(crate) fn module(ts: TokenStream) -> TokenStream { 184 let mut it = ts.into_iter(); 185 186 let info = ModuleInfo::parse(&mut it); 187 188 let mut modinfo = ModInfoBuilder::new(info.name.as_ref()); 189 if let Some(author) = info.author { 190 modinfo.emit("author", &author); 191 } 192 if let Some(authors) = info.authors { 193 for author in authors { 194 modinfo.emit("author", &author); 195 } 196 } 197 if let Some(description) = info.description { 198 modinfo.emit("description", &description); 199 } 200 modinfo.emit("license", &info.license); 201 if let Some(aliases) = info.alias { 202 for alias in aliases { 203 modinfo.emit("alias", &alias); 204 } 205 } 206 if let Some(firmware) = info.firmware { 207 for fw in firmware { 208 modinfo.emit("firmware", &fw); 209 } 210 } 211 212 // Built-in modules also export the `file` modinfo string. 213 let file = 214 std::env::var("RUST_MODFILE").expect("Unable to fetch RUST_MODFILE environmental variable"); 215 modinfo.emit_only_builtin("file", &file); 216 217 format!( 218 " 219 /// The module name. 220 /// 221 /// Used by the printing macros, e.g. [`info!`]. 222 const __LOG_PREFIX: &[u8] = b\"{name}\\0\"; 223 224 // SAFETY: `__this_module` is constructed by the kernel at load time and will not be 225 // freed until the module is unloaded. 226 #[cfg(MODULE)] 227 static THIS_MODULE: kernel::ThisModule = unsafe {{ 228 extern \"C\" {{ 229 static __this_module: kernel::types::Opaque<kernel::bindings::module>; 230 }} 231 232 kernel::ThisModule::from_ptr(__this_module.get()) 233 }}; 234 #[cfg(not(MODULE))] 235 static THIS_MODULE: kernel::ThisModule = unsafe {{ 236 kernel::ThisModule::from_ptr(core::ptr::null_mut()) 237 }}; 238 239 impl kernel::ModuleMetadata for {type_} {{ 240 const NAME: &'static kernel::str::CStr = kernel::c_str!(\"{name}\"); 241 }} 242 243 // Double nested modules, since then nobody can access the public items inside. 244 mod __module_init {{ 245 mod __module_init {{ 246 use super::super::{type_}; 247 use kernel::init::PinInit; 248 249 /// The \"Rust loadable module\" mark. 250 // 251 // This may be best done another way later on, e.g. as a new modinfo 252 // key or a new section. For the moment, keep it simple. 253 #[cfg(MODULE)] 254 #[doc(hidden)] 255 #[used] 256 static __IS_RUST_MODULE: () = (); 257 258 static mut __MOD: core::mem::MaybeUninit<{type_}> = 259 core::mem::MaybeUninit::uninit(); 260 261 // Loadable modules need to export the `{{init,cleanup}}_module` identifiers. 262 /// # Safety 263 /// 264 /// This function must not be called after module initialization, because it may be 265 /// freed after that completes. 266 #[cfg(MODULE)] 267 #[doc(hidden)] 268 #[no_mangle] 269 #[link_section = \".init.text\"] 270 pub unsafe extern \"C\" fn init_module() -> kernel::ffi::c_int {{ 271 // SAFETY: This function is inaccessible to the outside due to the double 272 // module wrapping it. It is called exactly once by the C side via its 273 // unique name. 274 unsafe {{ __init() }} 275 }} 276 277 #[cfg(MODULE)] 278 #[doc(hidden)] 279 #[used] 280 #[link_section = \".init.data\"] 281 static __UNIQUE_ID___addressable_init_module: unsafe extern \"C\" fn() -> i32 = init_module; 282 283 #[cfg(MODULE)] 284 #[doc(hidden)] 285 #[no_mangle] 286 pub extern \"C\" fn cleanup_module() {{ 287 // SAFETY: 288 // - This function is inaccessible to the outside due to the double 289 // module wrapping it. It is called exactly once by the C side via its 290 // unique name, 291 // - furthermore it is only called after `init_module` has returned `0` 292 // (which delegates to `__init`). 293 unsafe {{ __exit() }} 294 }} 295 296 #[cfg(MODULE)] 297 #[doc(hidden)] 298 #[used] 299 #[link_section = \".exit.data\"] 300 static __UNIQUE_ID___addressable_cleanup_module: extern \"C\" fn() = cleanup_module; 301 302 // Built-in modules are initialized through an initcall pointer 303 // and the identifiers need to be unique. 304 #[cfg(not(MODULE))] 305 #[cfg(not(CONFIG_HAVE_ARCH_PREL32_RELOCATIONS))] 306 #[doc(hidden)] 307 #[link_section = \"{initcall_section}\"] 308 #[used] 309 pub static __{name}_initcall: extern \"C\" fn() -> kernel::ffi::c_int = __{name}_init; 310 311 #[cfg(not(MODULE))] 312 #[cfg(CONFIG_HAVE_ARCH_PREL32_RELOCATIONS)] 313 core::arch::global_asm!( 314 r#\".section \"{initcall_section}\", \"a\" 315 __{name}_initcall: 316 .long __{name}_init - . 317 .previous 318 \"# 319 ); 320 321 #[cfg(not(MODULE))] 322 #[doc(hidden)] 323 #[no_mangle] 324 pub extern \"C\" fn __{name}_init() -> kernel::ffi::c_int {{ 325 // SAFETY: This function is inaccessible to the outside due to the double 326 // module wrapping it. It is called exactly once by the C side via its 327 // placement above in the initcall section. 328 unsafe {{ __init() }} 329 }} 330 331 #[cfg(not(MODULE))] 332 #[doc(hidden)] 333 #[no_mangle] 334 pub extern \"C\" fn __{name}_exit() {{ 335 // SAFETY: 336 // - This function is inaccessible to the outside due to the double 337 // module wrapping it. It is called exactly once by the C side via its 338 // unique name, 339 // - furthermore it is only called after `__{name}_init` has returned `0` 340 // (which delegates to `__init`). 341 unsafe {{ __exit() }} 342 }} 343 344 /// # Safety 345 /// 346 /// This function must only be called once. 347 unsafe fn __init() -> kernel::ffi::c_int {{ 348 let initer = 349 <{type_} as kernel::InPlaceModule>::init(&super::super::THIS_MODULE); 350 // SAFETY: No data race, since `__MOD` can only be accessed by this module 351 // and there only `__init` and `__exit` access it. These functions are only 352 // called once and `__exit` cannot be called before or during `__init`. 353 match unsafe {{ initer.__pinned_init(__MOD.as_mut_ptr()) }} {{ 354 Ok(m) => 0, 355 Err(e) => e.to_errno(), 356 }} 357 }} 358 359 /// # Safety 360 /// 361 /// This function must 362 /// - only be called once, 363 /// - be called after `__init` has been called and returned `0`. 364 unsafe fn __exit() {{ 365 // SAFETY: No data race, since `__MOD` can only be accessed by this module 366 // and there only `__init` and `__exit` access it. These functions are only 367 // called once and `__init` was already called. 368 unsafe {{ 369 // Invokes `drop()` on `__MOD`, which should be used for cleanup. 370 __MOD.assume_init_drop(); 371 }} 372 }} 373 374 {modinfo} 375 }} 376 }} 377 ", 378 type_ = info.type_, 379 name = info.name, 380 modinfo = modinfo.buffer, 381 initcall_section = ".initcall6.init" 382 ) 383 .parse() 384 .expect("Error parsing formatted string into token stream.") 385 } 386