1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
// SPDX-License-Identifier: MPL-2.0

#![allow(unused_variables)]

//! The module to parse kernel command-line arguments.
//!
//! The format of the Asterinas command line string conforms
//! to the Linux kernel command line rules:
//!
//! <https://www.kernel.org/doc/html/v6.4/admin-guide/kernel-parameters.html>
//!

use alloc::{
    collections::BTreeMap,
    ffi::CString,
    string::{String, ToString},
    vec,
    vec::Vec,
};

use log::warn;

#[derive(PartialEq, Debug)]
struct InitprocArgs {
    path: Option<String>,
    argv: Vec<CString>,
    envp: Vec<CString>,
}

/// Kernel module arguments
#[derive(PartialEq, Debug, Clone)]
pub enum ModuleArg {
    /// A string argument
    Arg(CString),
    /// A key-value argument
    KeyVal(CString, CString),
}

/// The struct to store the parsed kernel command-line arguments.
#[derive(Debug)]
pub struct KCmdlineArg {
    initproc: InitprocArgs,
    module_args: BTreeMap<String, Vec<ModuleArg>>,
}

// Define get APIs.
impl KCmdlineArg {
    /// Gets the path of the initprocess.
    pub fn get_initproc_path(&self) -> Option<&str> {
        self.initproc.path.as_deref()
    }
    /// Gets the argument vector(argv) of the initprocess.
    pub fn get_initproc_argv(&self) -> &Vec<CString> {
        &self.initproc.argv
    }
    /// Gets the environment vector(envp) of the initprocess.
    pub fn get_initproc_envp(&self) -> &Vec<CString> {
        &self.initproc.envp
    }
    /// Gets the argument vector of a kernel module.
    pub fn get_module_args(&self, module: &str) -> Option<&Vec<ModuleArg>> {
        self.module_args.get(module)
    }
}

// Splits the command line string by spaces but preserve
// ones that are protected by double quotes(`"`).
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()
    })
}

// Define the way to parse a string to `KCmdlineArg`.
impl From<&str> for KCmdlineArg {
    fn from(cmdline: &str) -> Self {
        // What we construct.
        let mut result: KCmdlineArg = KCmdlineArg {
            initproc: InitprocArgs {
                path: None,
                argv: Vec::new(),
                envp: Vec::new(),
            },
            module_args: BTreeMap::new(),
        };

        // Every thing after the "--" mark is the initproc arguments.
        let mut kcmdline_end = false;

        // The main parse loop. The processing steps are arranged (not very strictly)
        // by the analysis over the Backus–Naur form syntax tree.
        for arg in split_arg(cmdline) {
            // Cmdline => KernelArg "--" InitArg
            // KernelArg => Arg "\s+" KernelArg | %empty
            // InitArg => Arg "\s+" InitArg | %empty
            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;
            }
            // Arg => Entry | Entry "=" Value
            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])),
                _ => {
                    warn!("Unable to parse kernel argument {}, skip for now", arg);
                    continue;
                }
            };
            // Entry => Module "." ModuleOptionName | KernelOptionName
            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]),
                _ => {
                    warn!(
                        "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;
            }
            // KernelOptionName => /*literal string alternatives*/ | /*init environment*/
            if let Some(value) = value {
                // The option has a 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());
                    }
                    _ => {
                        // If the option is not recognized, it is passed to the initproc.
                        // Pattern 'option=value' is treated as the init environment.
                        let envp_entry = CString::new(option.to_string() + "=" + value).unwrap();
                        result.initproc.envp.push(envp_entry);
                    }
                }
            } else {
                // There is no value, the entry is only a option.

                // If the option is not recognized, it is passed to the initproc.
                // Pattern 'option' without value is treated as the init argument.
                let argv_entry = CString::new(option.to_string()).unwrap();
                result.initproc.argv.push(argv_entry);
            }
        }

        result
    }
}