xref: /DragonOS/user/apps/test_ebpf/syscall_ebpf/xtask/src/build_ebpf.rs (revision 55e6f0b65f91b32638fd56581f711a816eccdcd1)
1 use std::{path::PathBuf, process::Command};
2 
3 use clap::Parser;
4 
5 #[derive(Debug, Copy, Clone)]
6 pub enum Architecture {
7     BpfEl,
8     BpfEb,
9 }
10 
11 impl std::str::FromStr for Architecture {
12     type Err = String;
13 
14     fn from_str(s: &str) -> Result<Self, Self::Err> {
15         Ok(match s {
16             "bpfel-unknown-none" => Architecture::BpfEl,
17             "bpfeb-unknown-none" => Architecture::BpfEb,
18             _ => return Err("invalid target".to_owned()),
19         })
20     }
21 }
22 
23 impl std::fmt::Display for Architecture {
24     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
25         f.write_str(match self {
26             Architecture::BpfEl => "bpfel-unknown-none",
27             Architecture::BpfEb => "bpfeb-unknown-none",
28         })
29     }
30 }
31 
32 #[derive(Debug, Parser)]
33 pub struct Options {
34     /// Set the endianness of the BPF target
35     #[clap(default_value = "bpfel-unknown-none", long)]
36     pub target: Architecture,
37     /// Build the release target
38     #[clap(long)]
39     pub release: bool,
40 }
41 
42 pub fn build_ebpf(opts: Options) -> Result<(), anyhow::Error> {
43     let dir = PathBuf::from("syscall_ebpf-ebpf");
44     let target = format!("--target={}", opts.target);
45     let mut args = vec![
46         "build",
47         target.as_str(),
48         "-Z",
49         "build-std=core",
50     ];
51     if opts.release {
52         args.push("--release")
53     }
54 
55     // Command::new creates a child process which inherits all env variables. This means env
56     // vars set by the cargo xtask command are also inherited. RUSTUP_TOOLCHAIN is removed
57     // so the rust-toolchain.toml file in the -ebpf folder is honored.
58 
59     let status = Command::new("cargo")
60         .current_dir(dir)
61         .env_remove("RUSTUP_TOOLCHAIN")
62         .args(&args)
63         .status()
64         .expect("failed to build bpf program");
65     assert!(status.success());
66     Ok(())
67 }
68