1 // SPDX-License-Identifier: GPL-2.0 1 // SPDX-License-Identifier: GPL-2.0 2 2 3 use crate::helpers::*; 3 use crate::helpers::*; 4 use proc_macro::{token_stream, Delimiter, Lite !! 4 use proc_macro::{token_stream, Literal, TokenStream, TokenTree}; 5 use std::fmt::Write; 5 use std::fmt::Write; 6 6 7 fn expect_string_array(it: &mut token_stream:: << 8 let group = expect_group(it); << 9 assert_eq!(group.delimiter(), Delimiter::B << 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 ASCI << 15 values.push(val); << 16 match it.next() { << 17 Some(TokenTree::Punct(punct)) => a << 18 None => break, << 19 _ => panic!("Expected ',' or end o << 20 } << 21 } << 22 values << 23 } << 24 << 25 struct ModInfoBuilder<'a> { 7 struct ModInfoBuilder<'a> { 26 module: &'a str, 8 module: &'a str, 27 counter: usize, 9 counter: usize, 28 buffer: String, 10 buffer: String, 29 } 11 } 30 12 31 impl<'a> ModInfoBuilder<'a> { 13 impl<'a> ModInfoBuilder<'a> { 32 fn new(module: &'a str) -> Self { 14 fn new(module: &'a str) -> Self { 33 ModInfoBuilder { 15 ModInfoBuilder { 34 module, 16 module, 35 counter: 0, 17 counter: 0, 36 buffer: String::new(), 18 buffer: String::new(), 37 } 19 } 38 } 20 } 39 21 40 fn emit_base(&mut self, field: &str, conte 22 fn emit_base(&mut self, field: &str, content: &str, builtin: bool) { 41 let string = if builtin { 23 let string = if builtin { 42 // Built-in modules prefix their m 24 // Built-in modules prefix their modinfo strings by `module.`. 43 format!( 25 format!( 44 "{module}.{field}={content}\0" 26 "{module}.{field}={content}\0", 45 module = self.module, 27 module = self.module, 46 field = field, 28 field = field, 47 content = content 29 content = content 48 ) 30 ) 49 } else { 31 } else { 50 // Loadable modules' modinfo strin 32 // Loadable modules' modinfo strings go as-is. 51 format!("{field}={content}\0", fie 33 format!("{field}={content}\0", field = field, content = content) 52 }; 34 }; 53 35 54 write!( 36 write!( 55 &mut self.buffer, 37 &mut self.buffer, 56 " 38 " 57 {cfg} 39 {cfg} 58 #[doc(hidden)] 40 #[doc(hidden)] 59 #[link_section = \".modinfo\"] 41 #[link_section = \".modinfo\"] 60 #[used] 42 #[used] 61 pub static __{module}_{counter 43 pub static __{module}_{counter}: [u8; {length}] = *{string}; 62 ", 44 ", 63 cfg = if builtin { 45 cfg = if builtin { 64 "#[cfg(not(MODULE))]" 46 "#[cfg(not(MODULE))]" 65 } else { 47 } else { 66 "#[cfg(MODULE)]" 48 "#[cfg(MODULE)]" 67 }, 49 }, 68 module = self.module.to_uppercase( 50 module = self.module.to_uppercase(), 69 counter = self.counter, 51 counter = self.counter, 70 length = string.len(), 52 length = string.len(), 71 string = Literal::byte_string(stri 53 string = Literal::byte_string(string.as_bytes()), 72 ) 54 ) 73 .unwrap(); 55 .unwrap(); 74 56 75 self.counter += 1; 57 self.counter += 1; 76 } 58 } 77 59 78 fn emit_only_builtin(&mut self, field: &st 60 fn emit_only_builtin(&mut self, field: &str, content: &str) { 79 self.emit_base(field, content, true) 61 self.emit_base(field, content, true) 80 } 62 } 81 63 82 fn emit_only_loadable(&mut self, field: &s 64 fn emit_only_loadable(&mut self, field: &str, content: &str) { 83 self.emit_base(field, content, false) 65 self.emit_base(field, content, false) 84 } 66 } 85 67 86 fn emit(&mut self, field: &str, content: & 68 fn emit(&mut self, field: &str, content: &str) { 87 self.emit_only_builtin(field, content) 69 self.emit_only_builtin(field, content); 88 self.emit_only_loadable(field, content 70 self.emit_only_loadable(field, content); 89 } 71 } 90 } 72 } 91 73 92 #[derive(Debug, Default)] 74 #[derive(Debug, Default)] 93 struct ModuleInfo { 75 struct ModuleInfo { 94 type_: String, 76 type_: String, 95 license: String, 77 license: String, 96 name: String, 78 name: String, 97 author: Option<String>, 79 author: Option<String>, 98 description: Option<String>, 80 description: Option<String>, 99 alias: Option<Vec<String>>, !! 81 alias: Option<String>, 100 firmware: Option<Vec<String>>, << 101 } 82 } 102 83 103 impl ModuleInfo { 84 impl ModuleInfo { 104 fn parse(it: &mut token_stream::IntoIter) 85 fn parse(it: &mut token_stream::IntoIter) -> Self { 105 let mut info = ModuleInfo::default(); 86 let mut info = ModuleInfo::default(); 106 87 107 const EXPECTED_KEYS: &[&str] = &[ !! 88 const EXPECTED_KEYS: &[&str] = 108 "type", !! 89 &["type", "name", "author", "description", "license", "alias"]; 109 "name", << 110 "author", << 111 "description", << 112 "license", << 113 "alias", << 114 "firmware", << 115 ]; << 116 const REQUIRED_KEYS: &[&str] = &["type 90 const REQUIRED_KEYS: &[&str] = &["type", "name", "license"]; 117 let mut seen_keys = Vec::new(); 91 let mut seen_keys = Vec::new(); 118 92 119 loop { 93 loop { 120 let key = match it.next() { 94 let key = match it.next() { 121 Some(TokenTree::Ident(ident)) 95 Some(TokenTree::Ident(ident)) => ident.to_string(), 122 Some(_) => panic!("Expected Id 96 Some(_) => panic!("Expected Ident or end"), 123 None => break, 97 None => break, 124 }; 98 }; 125 99 126 if seen_keys.contains(&key) { 100 if seen_keys.contains(&key) { 127 panic!( 101 panic!( 128 "Duplicated key \"{}\". Ke 102 "Duplicated key \"{}\". Keys can only be specified once.", 129 key 103 key 130 ); 104 ); 131 } 105 } 132 106 133 assert_eq!(expect_punct(it), ':'); 107 assert_eq!(expect_punct(it), ':'); 134 108 135 match key.as_str() { 109 match key.as_str() { 136 "type" => info.type_ = expect_ 110 "type" => info.type_ = expect_ident(it), 137 "name" => info.name = expect_s 111 "name" => info.name = expect_string_ascii(it), 138 "author" => info.author = Some 112 "author" => info.author = Some(expect_string(it)), 139 "description" => info.descript 113 "description" => info.description = Some(expect_string(it)), 140 "license" => info.license = ex 114 "license" => info.license = expect_string_ascii(it), 141 "alias" => info.alias = Some(e !! 115 "alias" => info.alias = Some(expect_string_ascii(it)), 142 "firmware" => info.firmware = << 143 _ => panic!( 116 _ => panic!( 144 "Unknown key \"{}\". Valid 117 "Unknown key \"{}\". Valid keys are: {:?}.", 145 key, EXPECTED_KEYS 118 key, EXPECTED_KEYS 146 ), 119 ), 147 } 120 } 148 121 149 assert_eq!(expect_punct(it), ','); 122 assert_eq!(expect_punct(it), ','); 150 123 151 seen_keys.push(key); 124 seen_keys.push(key); 152 } 125 } 153 126 154 expect_end(it); 127 expect_end(it); 155 128 156 for key in REQUIRED_KEYS { 129 for key in REQUIRED_KEYS { 157 if !seen_keys.iter().any(|e| e == 130 if !seen_keys.iter().any(|e| e == key) { 158 panic!("Missing required key \ 131 panic!("Missing required key \"{}\".", key); 159 } 132 } 160 } 133 } 161 134 162 let mut ordered_keys: Vec<&str> = Vec: 135 let mut ordered_keys: Vec<&str> = Vec::new(); 163 for key in EXPECTED_KEYS { 136 for key in EXPECTED_KEYS { 164 if seen_keys.iter().any(|e| e == k 137 if seen_keys.iter().any(|e| e == key) { 165 ordered_keys.push(key); 138 ordered_keys.push(key); 166 } 139 } 167 } 140 } 168 141 169 if seen_keys != ordered_keys { 142 if seen_keys != ordered_keys { 170 panic!( 143 panic!( 171 "Keys are not ordered as expec 144 "Keys are not ordered as expected. Order them like: {:?}.", 172 ordered_keys 145 ordered_keys 173 ); 146 ); 174 } 147 } 175 148 176 info 149 info 177 } 150 } 178 } 151 } 179 152 180 pub(crate) fn module(ts: TokenStream) -> Token 153 pub(crate) fn module(ts: TokenStream) -> TokenStream { 181 let mut it = ts.into_iter(); 154 let mut it = ts.into_iter(); 182 155 183 let info = ModuleInfo::parse(&mut it); 156 let info = ModuleInfo::parse(&mut it); 184 157 185 let mut modinfo = ModInfoBuilder::new(info 158 let mut modinfo = ModInfoBuilder::new(info.name.as_ref()); 186 if let Some(author) = info.author { 159 if let Some(author) = info.author { 187 modinfo.emit("author", &author); 160 modinfo.emit("author", &author); 188 } 161 } 189 if let Some(description) = info.descriptio 162 if let Some(description) = info.description { 190 modinfo.emit("description", &descripti 163 modinfo.emit("description", &description); 191 } 164 } 192 modinfo.emit("license", &info.license); 165 modinfo.emit("license", &info.license); 193 if let Some(aliases) = info.alias { !! 166 if let Some(alias) = info.alias { 194 for alias in aliases { !! 167 modinfo.emit("alias", &alias); 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 } 168 } 203 169 204 // Built-in modules also export the `file` 170 // Built-in modules also export the `file` modinfo string. 205 let file = 171 let file = 206 std::env::var("RUST_MODFILE").expect(" 172 std::env::var("RUST_MODFILE").expect("Unable to fetch RUST_MODFILE environmental variable"); 207 modinfo.emit_only_builtin("file", &file); 173 modinfo.emit_only_builtin("file", &file); 208 174 209 format!( 175 format!( 210 " 176 " 211 /// The module name. 177 /// The module name. 212 /// 178 /// 213 /// Used by the printing macros, e 179 /// Used by the printing macros, e.g. [`info!`]. 214 const __LOG_PREFIX: &[u8] = b\"{na 180 const __LOG_PREFIX: &[u8] = b\"{name}\\0\"; 215 181 >> 182 /// The \"Rust loadable module\" mark, for `scripts/is_rust_module.sh`. >> 183 // >> 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. >> 186 #[cfg(MODULE)] >> 187 #[doc(hidden)] >> 188 #[used] >> 189 static __IS_RUST_MODULE: () = (); >> 190 >> 191 static mut __MOD: Option<{type_}> = None; >> 192 216 // SAFETY: `__this_module` is cons 193 // SAFETY: `__this_module` is constructed by the kernel at load time and will not be 217 // freed until the module is unloa 194 // freed until the module is unloaded. 218 #[cfg(MODULE)] 195 #[cfg(MODULE)] 219 static THIS_MODULE: kernel::ThisMo 196 static THIS_MODULE: kernel::ThisModule = unsafe {{ 220 extern \"C\" {{ !! 197 kernel::ThisModule::from_ptr(&kernel::bindings::__this_module as *const _ as *mut _) 221 static __this_module: kern << 222 }} << 223 << 224 kernel::ThisModule::from_ptr(_ << 225 }}; 198 }}; 226 #[cfg(not(MODULE))] 199 #[cfg(not(MODULE))] 227 static THIS_MODULE: kernel::ThisMo 200 static THIS_MODULE: kernel::ThisModule = unsafe {{ 228 kernel::ThisModule::from_ptr(c 201 kernel::ThisModule::from_ptr(core::ptr::null_mut()) 229 }}; 202 }}; 230 203 231 // Double nested modules, since th !! 204 // Loadable modules need to export the `{{init,cleanup}}_module` identifiers. 232 mod __module_init {{ !! 205 #[cfg(MODULE)] 233 mod __module_init {{ !! 206 #[doc(hidden)] 234 use super::super::{type_}; !! 207 #[no_mangle] 235 !! 208 pub extern \"C\" fn init_module() -> core::ffi::c_int {{ 236 /// The \"Rust loadable mo !! 209 __init() 237 // !! 210 }} 238 // This may be best done a << 239 // key or a new section. F << 240 #[cfg(MODULE)] << 241 #[doc(hidden)] << 242 #[used] << 243 static __IS_RUST_MODULE: ( << 244 << 245 static mut __MOD: Option<{ << 246 << 247 // Loadable modules need t << 248 /// # Safety << 249 /// << 250 /// This function must not << 251 /// freed after that compl << 252 #[cfg(MODULE)] << 253 #[doc(hidden)] << 254 #[no_mangle] << 255 #[link_section = \".init.t << 256 pub unsafe extern \"C\" fn << 257 // SAFETY: This functi << 258 // module wrapping it. << 259 // unique name. << 260 unsafe {{ __init() }} << 261 }} << 262 211 263 #[cfg(MODULE)] !! 212 #[cfg(MODULE)] 264 #[doc(hidden)] !! 213 #[doc(hidden)] 265 #[used] !! 214 #[no_mangle] 266 #[link_section = \".init.d !! 215 pub extern \"C\" fn cleanup_module() {{ 267 static __UNIQUE_ID___addre !! 216 __exit() 268 !! 217 }} 269 #[cfg(MODULE)] << 270 #[doc(hidden)] << 271 #[no_mangle] << 272 pub extern \"C\" fn cleanu << 273 // SAFETY: << 274 // - This function is << 275 // module wrapping i << 276 // unique name, << 277 // - furthermore it is << 278 // (which delegates << 279 unsafe {{ __exit() }} << 280 }} << 281 218 282 #[cfg(MODULE)] !! 219 // Built-in modules are initialized through an initcall pointer 283 #[doc(hidden)] !! 220 // and the identifiers need to be unique. 284 #[used] !! 221 #[cfg(not(MODULE))] 285 #[link_section = \".exit.d !! 222 #[cfg(not(CONFIG_HAVE_ARCH_PREL32_RELOCATIONS))] 286 static __UNIQUE_ID___addre !! 223 #[doc(hidden)] 287 !! 224 #[link_section = \"{initcall_section}\"] 288 // Built-in modules are in !! 225 #[used] 289 // and the identifiers nee !! 226 pub static __{name}_initcall: extern \"C\" fn() -> core::ffi::c_int = __{name}_init; 290 #[cfg(not(MODULE))] << 291 #[cfg(not(CONFIG_HAVE_ARCH << 292 #[doc(hidden)] << 293 #[link_section = \"{initca << 294 #[used] << 295 pub static __{name}_initca << 296 << 297 #[cfg(not(MODULE))] << 298 #[cfg(CONFIG_HAVE_ARCH_PRE << 299 core::arch::global_asm!( << 300 r#\".section \"{initca << 301 __{name}_initcall: << 302 .long __{name}_i << 303 .previous << 304 \"# << 305 ); << 306 << 307 #[cfg(not(MODULE))] << 308 #[doc(hidden)] << 309 #[no_mangle] << 310 pub extern \"C\" fn __{nam << 311 // SAFETY: This functi << 312 // module wrapping it. << 313 // placement above in << 314 unsafe {{ __init() }} << 315 }} << 316 227 317 #[cfg(not(MODULE))] !! 228 #[cfg(not(MODULE))] 318 #[doc(hidden)] !! 229 #[cfg(CONFIG_HAVE_ARCH_PREL32_RELOCATIONS)] 319 #[no_mangle] !! 230 core::arch::global_asm!( 320 pub extern \"C\" fn __{nam !! 231 r#\".section \"{initcall_section}\", \"a\" 321 // SAFETY: !! 232 __{name}_initcall: 322 // - This function is !! 233 .long __{name}_init - . 323 // module wrapping i !! 234 .previous 324 // unique name, !! 235 \"# 325 // - furthermore it is !! 236 ); 326 // (which delegates << 327 unsafe {{ __exit() }} << 328 }} << 329 237 330 /// # Safety !! 238 #[cfg(not(MODULE))] 331 /// !! 239 #[doc(hidden)] 332 /// This function must onl !! 240 #[no_mangle] 333 unsafe fn __init() -> core !! 241 pub extern \"C\" fn __{name}_init() -> core::ffi::c_int {{ 334 match <{type_} as kern !! 242 __init() 335 Ok(m) => {{ !! 243 }} 336 // SAFETY: No !! 244 337 // module and !! 245 #[cfg(not(MODULE))] 338 // functions a !! 246 #[doc(hidden)] 339 // before or d !! 247 #[no_mangle] 340 unsafe {{ !! 248 pub extern \"C\" fn __{name}_exit() {{ 341 __MOD = So !! 249 __exit() 342 }} !! 250 }} 343 return 0; << 344 }} << 345 Err(e) => {{ << 346 return e.to_er << 347 }} << 348 }} << 349 }} << 350 251 351 /// # Safety !! 252 fn __init() -> core::ffi::c_int {{ 352 /// !! 253 match <{type_} as kernel::Module>::init(&THIS_MODULE) {{ 353 /// This function must !! 254 Ok(m) => {{ 354 /// - only be called once, << 355 /// - be called after `__i << 356 unsafe fn __exit() {{ << 357 // SAFETY: No data rac << 358 // and there only `__i << 359 // called once and `__ << 360 unsafe {{ 255 unsafe {{ 361 // Invokes `drop() !! 256 __MOD = Some(m); 362 __MOD = None; << 363 }} 257 }} >> 258 return 0; 364 }} 259 }} >> 260 Err(e) => {{ >> 261 return e.to_kernel_errno(); >> 262 }} >> 263 }} >> 264 }} 365 265 366 {modinfo} !! 266 fn __exit() {{ >> 267 unsafe {{ >> 268 // Invokes `drop()` on `__MOD`, which should be used for cleanup. >> 269 __MOD = None; 367 }} 270 }} 368 }} 271 }} >> 272 >> 273 {modinfo} 369 ", 274 ", 370 type_ = info.type_, 275 type_ = info.type_, 371 name = info.name, 276 name = info.name, 372 modinfo = modinfo.buffer, 277 modinfo = modinfo.buffer, 373 initcall_section = ".initcall6.init" 278 initcall_section = ".initcall6.init" 374 ) 279 ) 375 .parse() 280 .parse() 376 .expect("Error parsing formatted string in 281 .expect("Error parsing formatted string into token stream.") 377 } 282 }
Linux® is a registered trademark of Linus Torvalds in the United States and other countries.
TOMOYO® is a registered trademark of NTT DATA CORPORATION.