#![allow(unused_variables)]
use alloc::{
collections::BTreeMap,
ffi::CString,
string::{String, ToString},
vec,
vec::Vec,
};
use crate::early_println;
#[derive(PartialEq, Debug)]
struct InitprocArgs {
path: Option<String>,
argv: Vec<CString>,
envp: Vec<CString>,
}
#[derive(PartialEq, Debug, Clone)]
pub enum ModuleArg {
Arg(CString),
KeyVal(CString, CString),
}
#[derive(Debug)]
pub struct KCmdlineArg {
initproc: InitprocArgs,
module_args: BTreeMap<String, Vec<ModuleArg>>,
}
impl KCmdlineArg {
pub fn get_initproc_path(&self) -> Option<&str> {
self.initproc.path.as_deref()
}
pub fn get_initproc_argv(&self) -> &Vec<CString> {
&self.initproc.argv
}
pub fn get_initproc_envp(&self) -> &Vec<CString> {
&self.initproc.envp
}
pub fn get_module_args(&self, module: &str) -> Option<&Vec<ModuleArg>> {
self.module_args.get(module)
}
}
fn split_arg(input: &str) -> impl Iterator<Item = &str> {
let mut inside_quotes = false;
input.split(move |c: char| {
if c == '"' {
inside_quotes = !inside_quotes;
}
!inside_quotes && c.is_whitespace()
})
}
impl From<&str> for KCmdlineArg {
fn from(cmdline: &str) -> Self {
let mut result: KCmdlineArg = KCmdlineArg {
initproc: InitprocArgs {
path: None,
argv: Vec::new(),
envp: Vec::new(),
},
module_args: BTreeMap::new(),
};
let mut kcmdline_end = false;
for arg in split_arg(cmdline) {
if kcmdline_end {
if result.initproc.path.is_none() {
panic!("Initproc arguments provided but no initproc path specified!");
}
result.initproc.argv.push(CString::new(arg).unwrap());
continue;
}
if arg == "--" {
kcmdline_end = true;
continue;
}
let arg_pattern: Vec<_> = arg.split('=').collect();
let (entry, value) = match arg_pattern.len() {
1 => (arg_pattern[0], None),
2 => (arg_pattern[0], Some(arg_pattern[1])),
_ => {
early_println!(
"[KCmdline] Unable to parse kernel argument {}, skip for now",
arg
);
continue;
}
};
let entry_pattern: Vec<_> = entry.split('.').collect();
let (node, option) = match entry_pattern.len() {
1 => (None, entry_pattern[0]),
2 => (Some(entry_pattern[0]), entry_pattern[1]),
_ => {
early_println!(
"[KCmdline] Unable to parse entry {} in argument {}, skip for now",
entry,
arg
);
continue;
}
};
if let Some(modname) = node {
let modarg = if let Some(v) = value {
ModuleArg::KeyVal(
CString::new(option.to_string()).unwrap(),
CString::new(v).unwrap(),
)
} else {
ModuleArg::Arg(CString::new(option).unwrap())
};
result
.module_args
.entry(modname.to_string())
.and_modify(|v| v.push(modarg.clone()))
.or_insert(vec![modarg.clone()]);
continue;
}
if let Some(value) = value {
match option {
"init" => {
if let Some(v) = &result.initproc.path {
panic!("Initproc assigned twice in the command line!");
}
result.initproc.path = Some(value.to_string());
}
_ => {
let envp_entry = CString::new(option.to_string() + "=" + value).unwrap();
result.initproc.envp.push(envp_entry);
}
}
} else {
let argv_entry = CString::new(option.to_string()).unwrap();
result.initproc.argv.push(argv_entry);
}
}
result
}
}