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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
//!  SPDX-License-Identifier: MIT
//!
//! Copyright (c) 2023, eunomia-bpf
//! All rights reserved.
//!

use anyhow::{bail, Result};
use clap::{Arg, ArgAction, Command};
use serde_json::Value;

use super::EunomiaObjectMeta;

const DEFAULT_DESCRIPTION: &str = "A simple eBPF program";
const DEFAULT_VERSION: &str = "0.1.0";
const DEFAULT_EPILOG: &str = "Built with eunomia-bpf framework.\nSee https://github.com/eunomia-bpf/eunomia-bpf for more information.";

impl EunomiaObjectMeta {
    /// Build an argument parser use the `cmdarg` sections in .rodata/.bss variables.
    ///
    /// Each variable in the `.bss` or `.rodata` sections will be mapped into a command line argument.
    ///
    /// If a variable has it's default value, the default value will be used in the command line parser.
    ///
    /// Variables with `bool` will have some special cases:
    /// - If the variable has no default values, a switch named `--<NAME>` will be added, indicating to set the value to true or false
    /// - If the default value if true, a switch named `--disable-<NAME>` will be added, means set the value to false
    /// - If the default value if false, a switch named `--enable-<NAME>` will be added, means to set the value to true.
    ///
    /// The first will be used to set the value of the variable to `true`, second one will be used to set `false`
    ///
    /// Variables with other types will accept values. But values will be checked in `parse_arguments_and_fill_skeleton_variables`, so here the values input in the command line parser will be regarded as strings.
    pub fn build_argument_parser(&self) -> Result<Command> {
        let cmd = Command::new(self.bpf_skel.obj_name.to_string());

        let cmd = if let Some(doc) = &self.bpf_skel.doc {
            cmd.version(
                doc.version
                    .to_owned()
                    .unwrap_or_else(|| DEFAULT_VERSION.to_string()),
            )
            .after_help(
                doc.details
                    .to_owned()
                    .unwrap_or_else(|| DEFAULT_EPILOG.to_owned()),
            )
            .before_help(
                doc.brief
                    .to_owned()
                    .or(doc.description.to_owned())
                    .unwrap_or_else(|| DEFAULT_DESCRIPTION.to_owned()),
            )
        } else {
            cmd.version(DEFAULT_VERSION)
                .after_help(DEFAULT_EPILOG)
                .before_help(DEFAULT_DESCRIPTION)
        };
        // Add a switch to control whether to show debug information
        let mut cmd = cmd.arg(
            Arg::new("verbose")
                .long("verbose")
                .action(ArgAction::SetTrue)
                .help("Whether to show libbpf debug information"),
        );
        // Add arguments for section vars
        for section in self.bpf_skel.data_sections.iter() {
            for variable in section.variables.iter() {
                // Ignore useless variables
                if variable.name.starts_with("__eunomia_dummy") {
                    continue;
                }
                let help = variable
                    .cmdarg
                    .help
                    .to_owned()
                    .or(variable.description.to_owned())
                    .unwrap_or_else(|| {
                        format!("Set value of `{}` variable {}", variable.ty, variable.name)
                    });

                let long = variable
                    .cmdarg
                    .long
                    .to_owned()
                    .unwrap_or_else(|| variable.name.to_string());
                if variable.ty == "bool" {
                    // If there is default values
                    let default = if let Some(val) = variable
                        .cmdarg
                        .default
                        .to_owned()
                        .or(variable.value.to_owned())
                    {
                        Some(match val {
                            Value::Bool(b) => b,
                            _ => bail!("Only expected bool values in bool variables"),
                        })
                    } else {
                        None
                    };
                    let arg = match default {
                        // without default values
                        None => Arg::new(variable.name.clone())
                            .help(help)
                            .long(long)
                            .action(ArgAction::SetTrue),
                        Some(true) => Arg::new(variable.name.clone())
                            .help(help)
                            .long(format!("disable-{long}"))
                            .default_value("true")
                            .action(ArgAction::SetFalse),
                        Some(false) => Arg::new(variable.name.clone())
                            .help(help)
                            .long(format!("enable-{long}"))
                            .action(ArgAction::SetTrue),
                    };
                    cmd = cmd.arg(arg);
                } else {
                    let short = variable.cmdarg.short.to_owned();

                    let default = if let Some(default) = variable
                        .cmdarg
                        .default
                        .to_owned()
                        .or(variable.value.to_owned())
                    {
                        Some(match default {
                            Value::Number(v) => v.to_string(),
                            Value::String(v) => v,
                            _ => bail!(
                            "We only want to see integers or strings in default values for non-bool variables.."
                        ),
                        })
                    } else {
                        None
                    };
                    let arg = Arg::new(variable.name.clone())
                        .action(ArgAction::Set)
                        .help(help)
                        .long(long);
                    let arg = if let Some(s) = short {
                        let chars = s.chars().collect::<Vec<char>>();
                        if chars.len() != 1 {
                            bail!(
                            "Short name for variable `{}` is expected to be just in 1 character",
                            variable.name
                        );
                        }

                        arg.short(chars[0])
                    } else {
                        arg
                    };
                    // For values with defaults, we set the default ones
                    // For other values, if they were not provided when parsing, we'll fill the corresponding memory with zero, or report error, based on what we need
                    let arg = if let Some(default) = default {
                        arg.default_value(default)
                    } else {
                        arg
                    };
                    cmd = cmd.arg(arg);
                }
            }
        }
        Ok(cmd)
    }
}
#[cfg(test)]
mod tests {
    use crate::{meta::EunomiaObjectMeta, tests::get_assets_dir};

    #[test]
    fn test_arg_builder() {
        let skel = serde_json::from_str::<EunomiaObjectMeta>(
            &std::fs::read_to_string(get_assets_dir().join("arg_builder_test").join("skel.json"))
                .unwrap(),
        )
        .unwrap();
        let cmd = skel.build_argument_parser().unwrap();
        for p in cmd.get_arguments() {
            println!("{:?}", p.get_long());
        }
        let cmd = cmd.color(clap::ColorChoice::Never);
        let matches = cmd
            .try_get_matches_from([
                "myprog",
                "--cv1",
                "2333",
                "--const_val_2",
                "12345678",
                "--const_val_3",
                "abcdefg",
                "--bss_val_1",
                "111",
            ])
            .unwrap();
        assert_eq!(
            matches.get_one::<String>("const_val_1"),
            Some(&String::from("2333"))
        );
        assert_eq!(
            matches.get_one::<String>("const_val_2"),
            Some(&String::from("12345678"))
        );
        assert_eq!(
            matches.get_one::<String>("const_val_3"),
            Some(&String::from("abcdefg"))
        );
        assert_eq!(
            matches.get_one::<String>("bss_val_1"),
            Some(&String::from("111"))
        );
        assert_eq!(matches.get_one::<String>("bss_val_2"), None);
        assert_eq!(matches.get_one::<String>("bss_val_3"), None);
    }
    #[test]
    #[should_panic]
    fn test_arg_builder_invalid_argument() {
        let skel = serde_json::from_str::<EunomiaObjectMeta>(
            &std::fs::read_to_string(get_assets_dir().join("arg_builder_test").join("skel.json"))
                .unwrap(),
        )
        .unwrap();
        let cmd = skel.build_argument_parser().unwrap();
        cmd.try_get_matches_from(["prog", "-a", "123"]).unwrap();
    }
    #[test]
    fn test_boolflag() {
        let skel = serde_json::from_str::<EunomiaObjectMeta>(
            &std::fs::read_to_string(get_assets_dir().join("arg_builder_test").join("skel.json"))
                .unwrap(),
        )
        .unwrap();
        let cmd = skel.build_argument_parser().unwrap();
        let matches = cmd
            .clone()
            .try_get_matches_from([
                "prog",
                "--boolflag",
                "--disable-boolflag-with-default-true",
                "--enable-boolflag-with-default-false",
            ])
            .unwrap();
        assert!(matches.get_flag("boolflag"));
        assert!(!matches.get_flag("boolflag-with-default-true"));
        assert!(matches.get_flag("boolflag-with-default-false"));

        let matches = cmd.clone().try_get_matches_from(["prog"]).unwrap();
        assert!(!matches.get_flag("boolflag"));
        assert!(matches.get_flag("boolflag-with-default-true"));
        assert!(!matches.get_flag("boolflag-with-default-false"));
    }
    #[test]
    #[should_panic]
    fn test_boolflag_2() {
        let skel = serde_json::from_str::<EunomiaObjectMeta>(
            &std::fs::read_to_string(get_assets_dir().join("arg_builder_test").join("skel.json"))
                .unwrap(),
        )
        .unwrap();
        let cmd = skel.build_argument_parser().unwrap();
        cmd.clone()
            .try_get_matches_from(["prog", "--enable-boolflag-with-default-true"])
            .unwrap();
    }
    #[test]
    #[should_panic]
    fn test_boolflag_3() {
        let skel = serde_json::from_str::<EunomiaObjectMeta>(
            &std::fs::read_to_string(get_assets_dir().join("arg_builder_test").join("skel.json"))
                .unwrap(),
        )
        .unwrap();
        let cmd = skel.build_argument_parser().unwrap();
        cmd.clone()
            .try_get_matches_from(["prog", "--disable-boolflag-with-default-false"])
            .unwrap();
    }
}