axbuild 0.4.5

An OS build lib toolkit used by arceos
Documentation
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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
use std::{
    fs,
    path::{Path, PathBuf},
};

use anyhow::Context;
use ostool::run::qemu::QemuConfig;

use crate::{
    axvisor::{
        context::AxvisorContext,
        image::{config::ImageConfig, spec::ImageSpecRef, storage::Storage},
    },
    context::AxvisorCliArgs,
    test_qemu::AxvisorBoardTestGroup,
};

pub const LINUX_AARCH64_IMAGE_SPEC: &str = "qemu_aarch64_linux";
pub const LINUX_RISCV64_IMAGE_SPEC: &str = "qemu_riscv64_linux";
pub const LINUX_AARCH64_VMCONFIG_TEMPLATE: &str =
    "os/axvisor/configs/vms/linux-aarch64-qemu-smp1.toml";
pub const LINUX_AARCH64_GENERATED_VMCONFIG: &str =
    "os/axvisor/tmp/vmconfigs/linux-aarch64-qemu-smp1.generated.toml";
pub const LINUX_RISCV64_VMCONFIG_TEMPLATE: &str =
    "os/axvisor/configs/vms/linux-riscv64-qemu-smp1.toml";
pub const LINUX_RISCV64_GENERATED_VMCONFIG: &str =
    "os/axvisor/tmp/vmconfigs/linux-riscv64-qemu-smp1.generated.toml";
pub const NIMBOS_X86_64_IMAGE_SPEC: &str = "qemu_x86_64_nimbos";
pub const NIMBOS_X86_64_VMCONFIG: &str = "os/axvisor/configs/vms/nimbos-x86_64-qemu-smp1.toml";
const RDK_S100_LINUX_GROUP_NAME: &str = "rdk-s100-linux";
const RDK_S100_LINUX_VMCONFIG_TEMPLATE: &str =
    "os/axvisor/configs/vms/linux-aarch64-s100-smp1.toml";
const RDK_S100_LINUX_GENERATED_VMCONFIG: &str =
    "os/axvisor/tmp/vmconfigs/linux-aarch64-s100-ci.generated.toml";
const RDK_S100_LINUX_IMAGE_SPEC: &str = "rdk-s100p_linux";
const RDK_S100_LINUX_KERNEL_IN_IMAGE: &str = "rdk-s100p";

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PreparedLinuxGuestAssets {
    pub image_dir: PathBuf,
    pub generated_vmconfig: PathBuf,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ShellAutoInitConfig {
    pub shell_prefix: String,
    pub shell_init_cmd: String,
    pub success_regex: Vec<String>,
    pub fail_regex: Vec<String>,
}

pub(crate) async fn prepare_linux_aarch64_guest_assets(
    ctx: &AxvisorContext,
) -> anyhow::Result<PreparedLinuxGuestAssets> {
    let image_dir = pull_guest_image(ctx, LINUX_AARCH64_IMAGE_SPEC).await?;
    let kernel_path = image_dir.join("qemu-aarch64");
    ensure_guest_kernel_exists(&kernel_path, "linux guest")?;

    let workspace_root = ctx.workspace_root();
    let generated_vmconfig = workspace_root.join(LINUX_AARCH64_GENERATED_VMCONFIG);
    generate_linux_vmconfig(
        &workspace_root.join(LINUX_AARCH64_VMCONFIG_TEMPLATE),
        &generated_vmconfig,
        &kernel_path,
    )?;

    Ok(PreparedLinuxGuestAssets {
        image_dir,
        generated_vmconfig,
    })
}

pub(crate) async fn prepare_linux_riscv64_guest_assets(
    ctx: &AxvisorContext,
) -> anyhow::Result<PreparedLinuxGuestAssets> {
    let image_dir = pull_guest_image(ctx, LINUX_RISCV64_IMAGE_SPEC).await?;
    let kernel_path = image_dir.join("qemu-riscv64");
    let rootfs_path = guest_rootfs_path(&image_dir);
    ensure_guest_kernel_exists(&kernel_path, "linux guest")?;
    ensure_guest_rootfs_exists(&rootfs_path, "linux guest")?;

    let workspace_root = ctx.workspace_root();
    let generated_vmconfig = workspace_root.join(LINUX_RISCV64_GENERATED_VMCONFIG);
    generate_linux_vmconfig(
        &workspace_root.join(LINUX_RISCV64_VMCONFIG_TEMPLATE),
        &generated_vmconfig,
        &kernel_path,
    )?;

    Ok(PreparedLinuxGuestAssets {
        image_dir,
        generated_vmconfig,
    })
}

pub(crate) async fn prepare_nimbos_x86_64_guest_vmconfig(
    ctx: &AxvisorContext,
) -> anyhow::Result<PathBuf> {
    let image_dir = pull_guest_image(ctx, NIMBOS_X86_64_IMAGE_SPEC).await?;
    let kernel_path = image_dir.join("qemu-x86_64");
    let bios_path = image_dir.join("axvm-bios.bin");
    let rootfs_path = guest_rootfs_path(&image_dir);
    ensure_guest_kernel_exists(&kernel_path, "nimbos guest")?;
    if !bios_path.exists() {
        anyhow::bail!("nimbos guest bios not found at {}", bios_path.display());
    }
    ensure_guest_rootfs_exists(&rootfs_path, "nimbos guest")?;

    Ok(ctx.workspace_root().join(NIMBOS_X86_64_VMCONFIG))
}

pub(crate) async fn prepare_board_test_vmconfigs(
    ctx: &AxvisorContext,
    group: &AxvisorBoardTestGroup,
) -> anyhow::Result<Vec<PathBuf>> {
    if group.name != RDK_S100_LINUX_GROUP_NAME {
        return Ok(group.vmconfigs.iter().map(PathBuf::from).collect());
    }

    let image_dir = pull_guest_image(ctx, RDK_S100_LINUX_IMAGE_SPEC).await?;
    let kernel_path = image_dir.join(RDK_S100_LINUX_KERNEL_IN_IMAGE);
    ensure_guest_kernel_exists(&kernel_path, group.name)?;

    let workspace_root = ctx.workspace_root();
    let generated_vmconfig = workspace_root.join(RDK_S100_LINUX_GENERATED_VMCONFIG);
    generate_vmconfig_with_guest_assets(
        &workspace_root.join(RDK_S100_LINUX_VMCONFIG_TEMPLATE),
        &generated_vmconfig,
        &kernel_path,
        None,
        None,
        None,
    )?;

    Ok(vec![generated_vmconfig])
}

pub(crate) fn apply_shell_autoinit_config(config: &mut QemuConfig, shell: &ShellAutoInitConfig) {
    config.success_regex = shell.success_regex.clone();
    config.fail_regex = shell.fail_regex.clone();
    config.shell_prefix = Some(shell.shell_prefix.clone());
    config.shell_init_cmd = Some(shell.shell_init_cmd.clone());
}

fn generate_linux_vmconfig(
    template_path: &Path,
    output_path: &Path,
    kernel_path: &Path,
) -> anyhow::Result<()> {
    generate_vmconfig_with_guest_assets(template_path, output_path, kernel_path, None, None, None)
}

fn generate_vmconfig_with_guest_assets(
    template_path: &Path,
    output_path: &Path,
    kernel_path: &Path,
    dtb_path: Option<&Path>,
    bios_path: Option<&Path>,
    ramdisk_path: Option<&Path>,
) -> anyhow::Result<()> {
    let mut value = read_toml(template_path)?;
    let kernel = value
        .get_mut("kernel")
        .and_then(toml::Value::as_table_mut)
        .ok_or_else(|| {
            anyhow::anyhow!("missing `[kernel]` section in {}", template_path.display())
        })?;
    kernel.insert(
        "kernel_path".to_string(),
        toml::Value::String(kernel_path.display().to_string()),
    );
    update_optional_guest_path(kernel, "dtb_path", dtb_path);
    update_optional_guest_path(kernel, "bios_path", bios_path);
    update_optional_guest_path(kernel, "ramdisk_path", ramdisk_path);

    write_toml(output_path, &value)
}

fn update_optional_guest_path(
    kernel: &mut toml::map::Map<String, toml::Value>,
    key: &str,
    path: Option<&Path>,
) {
    match path {
        Some(path) => {
            kernel.insert(
                key.to_string(),
                toml::Value::String(path.display().to_string()),
            );
        }
        None => {
            kernel.remove(key);
        }
    }
}

async fn pull_guest_image(ctx: &AxvisorContext, image_spec: &str) -> anyhow::Result<PathBuf> {
    let mut config = ImageConfig::read_config(ctx.workspace_root())?;
    config.local_storage = absolute_path(ctx.workspace_root(), &config.local_storage);

    let storage = Storage::new_from_config(&config).await?;
    storage
        .pull_image(ImageSpecRef::parse(image_spec), None, true)
        .await
}

fn guest_rootfs_path(image_dir: &Path) -> PathBuf {
    image_dir.join("rootfs.img")
}

fn ensure_guest_kernel_exists(kernel_path: &Path, guest_name: &str) -> anyhow::Result<()> {
    if kernel_path.exists() {
        Ok(())
    } else {
        anyhow::bail!("{guest_name} kernel not found at {}", kernel_path.display());
    }
}

fn ensure_guest_rootfs_exists(rootfs_path: &Path, guest_name: &str) -> anyhow::Result<()> {
    if rootfs_path.exists() {
        Ok(())
    } else {
        anyhow::bail!("{guest_name} rootfs not found at {}", rootfs_path.display());
    }
}

fn read_toml(path: &Path) -> anyhow::Result<toml::Value> {
    let content =
        fs::read_to_string(path).with_context(|| format!("failed to read {}", path.display()))?;
    toml::from_str(&content).with_context(|| format!("failed to parse {}", path.display()))
}

fn write_toml(path: &Path, value: &toml::Value) -> anyhow::Result<()> {
    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent)
            .with_context(|| format!("failed to create {}", parent.display()))?;
    }
    fs::write(path, toml::to_string_pretty(value)?)
        .with_context(|| format!("failed to write {}", path.display()))
}

fn absolute_path(workspace_root: &Path, path: &Path) -> PathBuf {
    if path.is_absolute() {
        path.to_path_buf()
    } else {
        workspace_root.join(path)
    }
}

pub(crate) fn qemu_test_build_args(arch: &str, vmconfigs: Vec<PathBuf>) -> AxvisorCliArgs {
    AxvisorCliArgs {
        config: None,
        arch: Some(arch.to_string()),
        target: None,
        plat_dyn: None,
        smp: None,
        debug: false,
        vmconfigs,
    }
}

pub(crate) fn uboot_test_build_args(build_config: &str, vmconfig: &str) -> AxvisorCliArgs {
    AxvisorCliArgs {
        config: Some(PathBuf::from(build_config)),
        arch: None,
        target: None,
        plat_dyn: None,
        smp: None,
        debug: false,
        vmconfigs: vec![PathBuf::from(vmconfig)],
    }
}

pub(crate) fn board_test_build_args(
    group: &AxvisorBoardTestGroup,
    vmconfigs: Vec<PathBuf>,
) -> AxvisorCliArgs {
    AxvisorCliArgs {
        config: Some(PathBuf::from(group.build_config)),
        arch: None,
        target: None,
        plat_dyn: None,
        smp: None,
        debug: false,
        vmconfigs,
    }
}

#[cfg(test)]
mod tests {
    use tempfile::tempdir;

    use super::*;

    #[test]
    fn generate_linux_vmconfig_rewrites_only_kernel_path() {
        let dir = tempdir().unwrap();
        let template = dir.path().join("linux.toml");
        let output = dir.path().join("out/generated.toml");
        fs::write(
            &template,
            r#"
[base]
id = 1

[kernel]
kernel_path = "old"
entry_point = 1
"#,
        )
        .unwrap();

        generate_linux_vmconfig(&template, &output, Path::new("/tmp/kernel.bin")).unwrap();

        let value: toml::Value = toml::from_str(&fs::read_to_string(&output).unwrap()).unwrap();
        assert_eq!(
            value["kernel"]["kernel_path"].as_str(),
            Some("/tmp/kernel.bin")
        );
        assert_eq!(value["kernel"]["entry_point"].as_integer(), Some(1));
        assert_eq!(value["base"]["id"].as_integer(), Some(1));
    }

    #[test]
    fn generate_vmconfig_with_guest_assets_updates_optional_paths() {
        let dir = tempdir().unwrap();
        let template = dir.path().join("linux.toml");
        let output = dir.path().join("out/generated.toml");
        fs::write(
            &template,
            r#"
[base]
id = 2

[kernel]
kernel_path = "old"
dtb_path = "old.dtb"
bios_path = "old.bios"
ramdisk_path = "old.ramdisk"
"#,
        )
        .unwrap();

        generate_vmconfig_with_guest_assets(
            &template,
            &output,
            Path::new("/tmp/kernel.bin"),
            Some(Path::new("/tmp/guest.dtb")),
            None,
            Some(Path::new("/tmp/initrd.img")),
        )
        .unwrap();

        let value: toml::Value = toml::from_str(&fs::read_to_string(&output).unwrap()).unwrap();
        assert_eq!(
            value["kernel"]["kernel_path"].as_str(),
            Some("/tmp/kernel.bin")
        );
        assert_eq!(value["kernel"]["dtb_path"].as_str(), Some("/tmp/guest.dtb"));
        assert!(value["kernel"].get("bios_path").is_none());
        assert_eq!(
            value["kernel"]["ramdisk_path"].as_str(),
            Some("/tmp/initrd.img")
        );
    }

    #[test]
    fn apply_shell_autoinit_config_preserves_existing_args() {
        let mut qemu = QemuConfig {
            args: vec!["-nographic".to_string()],
            ..Default::default()
        };

        apply_shell_autoinit_config(
            &mut qemu,
            &ShellAutoInitConfig {
                shell_prefix: "~ #".to_string(),
                shell_init_cmd: "pwd && echo 'test pass!'".to_string(),
                success_regex: vec!["^test pass!$".to_string()],
                fail_regex: vec!["(?i)panic".to_string()],
            },
        );

        assert_eq!(qemu.args, vec!["-nographic".to_string()]);
        assert_eq!(qemu.shell_prefix.as_deref(), Some("~ #"));
        assert_eq!(
            qemu.shell_init_cmd.as_deref(),
            Some("pwd && echo 'test pass!'")
        );
        assert_eq!(qemu.success_regex, vec!["^test pass!$".to_string()]);
        assert_eq!(qemu.fail_regex, vec!["(?i)panic".to_string()]);
    }

    #[test]
    fn qemu_test_build_args_allows_empty_vmconfigs() {
        let args = qemu_test_build_args("loongarch64", vec![]);

        assert_eq!(args.arch.as_deref(), Some("loongarch64"));
        assert!(args.vmconfigs.is_empty());
    }

    #[test]
    fn absolute_path_keeps_absolute_paths() {
        let root = Path::new("/workspace");
        let path = Path::new("/tmp/image");

        assert_eq!(absolute_path(root, path), PathBuf::from("/tmp/image"));
    }
}