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
#![feature(exit_status_error)]

mod command;
mod runner;

use std::env::{self, VarError};
use std::path::{Path, PathBuf};

use clap::{Args, Parser, Subcommand};
use color_eyre::eyre::{bail, Context};
use color_eyre::Result;

use crate::runner::Runner;

#[derive(Parser, Debug)]
struct RunnerArgs {
    #[command(subcommand)]
    command: RunnerCommand,
    #[command(flatten)]
    target: TargetArgs,
    #[command(flatten)]
    binaries: BinaryArgs,
}

#[derive(Subcommand, Debug)]
enum RunnerCommand {
    /// Build the kernel binary.
    Build,
    /// Run tests for platform-independent packages.
    Test,
    /// Remove build artifacts.
    Clean,
    /// Build the kernel binary, then run the kernel in QEMU.
    Qemu {
        /// Should QEMU open a GDB server?
        ///
        /// Connect GDB with “target remote localhost:1234”, or consider
        /// running QEMU inside GDB with “qemu run”.
        #[arg(long, short)]
        debugger: bool,
    },
    /// Run GDB, configured to attach to QEMU.
    Gdb,
}

#[derive(Debug)]
enum Target {
    Debug,
    Release,
}

impl Target {
    fn cargo_profile_flag(&self) -> &'static str {
        match self {
            // Cargo does not accept --debug, nor --dev
            Self::Debug => "",
            Self::Release => "--release",
        }
    }

    fn cargo_profile_dir(&self) -> &'static str {
        match self {
            Self::Debug => "debug",
            Self::Release => "release",
        }
    }
}

#[derive(Args, Debug)]
#[command(next_help_heading = "Target")]
struct TargetArgs {
    /// Use a debug build (default).
    #[arg(long, global = true)]
    debug: bool,
    /// Use a release build.
    #[arg(long, global = true)]
    release: bool,
}

impl TargetArgs {
    fn as_target(&self) -> Result<Target> {
        let Self { debug, release } = *self;
        if debug && release {
            // TODO: encode this through clap
            bail!("can't specify both debug and release as target");
        } else if release {
            Ok(Target::Release)
        } else {
            // Default for all other cases (debug specified or no flags specified)
            Ok(Target::Debug)
        }
    }
}

#[derive(Args, Debug)]
#[command(next_help_heading = "Binaries")]
struct BinaryArgs {
    /// Path to a GDB which supports aarch64. [default: $GDB, otherwise `gdb`]
    #[arg(long, global = true)]
    gdb: Option<PathBuf>,
}

impl BinaryArgs {
    fn resolve(
        arg: Option<PathBuf>,
        name: &str,
        default_path: impl Into<PathBuf>,
    ) -> Result<PathBuf> {
        if let Some(path) = arg {
            Ok(path)
        } else {
            match env::var(name) {
                Ok(path) => Ok(PathBuf::from(path)),
                Err(VarError::NotPresent) => Ok(default_path.into()),
                Err(err) => Err(err)
                    .wrap_err_with(|| format!("failed to read environment varaible ${name}")),
            }
        }
    }

    fn into_binaries(self) -> Result<Binaries> {
        Ok(Binaries {
            gdb: Self::resolve(self.gdb, "GDB", "gdb")?,
        })
    }
}

#[derive(Debug)]
struct Binaries {
    gdb: PathBuf,
}

fn main() -> Result<()> {
    color_eyre::install()?;
    let RunnerArgs {
        command,
        target,
        binaries,
    } = RunnerArgs::parse();

    let target = target.as_target()?;
    let binaries = binaries.into_binaries()?;
    let kernel = Path::new("target/aarch64-unknown-none")
        .join(target.cargo_profile_dir())
        .join("kernel");

    let runner = Runner::new(binaries);

    let build = || -> Result<()> {
        runner.step("build");
        runner.run(
            command::make("build")
                .directory("kernel/")
                .variable("CARGOFLAGS", target.cargo_profile_flag()),
        )?;

        Ok(())
    };

    let test = || -> Result<()> {
        let mut flags = vec![target.cargo_profile_flag()];
        for package in ["allocator", "buddy-alloc"] {
            flags.push("-p");
            flags.push(package);
        }

        runner.step("test");
        runner.run(
            command::make("test")
                .directory("kernel/")
                .variable("CARGOFLAGS", flags.join(" ")),
        )?;

        Ok(())
    };

    let clean = || -> Result<()> {
        runner.step("clean");
        runner.run(command::make("clean").directory("kernel/"))?;

        Ok(())
    };

    let qemu = |debugger| -> Result<()> {
        let qemuflags = if debugger { "-S -s" } else { "" };
        let kernel = Path::new("..").join(&kernel);

        runner.step("qemu");
        runner.exec(
            command::make("run-kernel")
                .directory("qemu/")
                .variable("QEMUFLAGS", qemuflags)
                .variable("KERNEL", kernel.to_str().unwrap()),
        )?;

        Ok(())
    };

    let gdb = || -> Result<()> {
        runner.step("gdb");
        runner.exec(
            command::gdb(kernel.to_str().unwrap())
                .arg("-x")
                .arg("kernel/kernel.gdb"),
        )?;

        Ok(())
    };

    match command {
        RunnerCommand::Build => build(),
        RunnerCommand::Test => test(),
        RunnerCommand::Clean => clean(),
        RunnerCommand::Qemu { debugger } => build().and_then(|_| qemu(debugger)),
        RunnerCommand::Gdb => gdb(),
    }?;

    runner.done();
    Ok(())
}