exec.rs 11.9 KB
Newer Older
1
use redoxfs::{archive_at, BLOCK_SIZE, DiskSparse, FileSystem};
2
use std::{env, fs, io};
Jeremy Soller's avatar
Jeremy Soller committed
3
use std::io::{Seek, Write};
4 5
use std::path::{Path, PathBuf};
use std::process::{self, Command};
6
use std::time::{SystemTime, UNIX_EPOCH};
7

8
use crate::{installed, redoxer_dir, status_error, syscall_error};
9 10 11
use crate::redoxfs::RedoxFs;

static BASE_TOML: &'static str = include_str!("../res/base.toml");
12
static GUI_TOML: &'static str = include_str!("../res/gui.toml");
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

fn bootloader() -> io::Result<PathBuf> {
    let bootloader_bin = redoxer_dir().join("bootloader.bin");
    if ! bootloader_bin.is_file() {
        eprintln!("redoxer: building bootloader");

        let bootloader_dir = redoxer_dir().join("bootloader");
        if bootloader_dir.is_dir() {
            fs::remove_dir_all(&bootloader_dir)?;
        }
        fs::create_dir_all(&bootloader_dir)?;

        let mut config = redox_installer::Config::default();
        config.packages.insert("bootloader".to_string(), Default::default());
        let cookbook: Option<&str> = None;
        redox_installer::install(config, &bootloader_dir, cookbook).map_err(|err| {
            io::Error::new(
                io::ErrorKind::Other,
                format!("{}", err)
            )
        })?;

        fs::rename(&bootloader_dir.join("bootloader"), &bootloader_bin)?;
    }
    Ok(bootloader_bin)
}

40
fn base(bootloader_bin: &Path, gui: bool, fuse: bool) -> io::Result<PathBuf> {
41
    let name = if gui { "gui" } else { "base" };
42
    let ext = if fuse { "bin" } else { "tar" };
43

44
    let base_bin = redoxer_dir().join(format!("{}.{}", name, ext));
45
    if ! base_bin.is_file() {
46
        eprintln!("redoxer: building {}", name);
47

48
        let base_dir = redoxer_dir().join(name);
49 50 51 52 53
        if base_dir.is_dir() {
            fs::remove_dir_all(&base_dir)?;
        }
        fs::create_dir_all(&base_dir)?;

54
        let base_partial = redoxer_dir().join(format!("{}.{}.partial", name, ext));
55

56 57 58 59 60 61 62 63 64 65 66 67 68
        if fuse {
            Command::new("truncate")
                .arg("--size=4G")
                .arg(&base_partial)
                .status()
                .and_then(status_error)?;

            Command::new("redoxfs-mkfs")
                .arg(&base_partial)
                .arg(&bootloader_bin)
                .status()
                .and_then(status_error)?;
        }
69 70

        {
71 72 73 74 75
            let redoxfs_opt = if fuse {
                Some(RedoxFs::new(&base_partial, &base_dir)?)
            } else {
                None
            };
76

77 78 79 80 81 82 83 84 85
            let config: redox_installer::Config = toml::from_str(
                if gui { GUI_TOML } else { BASE_TOML }
            ).map_err(|err| {
                io::Error::new(
                    io::ErrorKind::Other,
                    format!("{}", err)
                )
            })?;

86 87 88 89 90 91 92 93
            let cookbook: Option<&str> = None;
            redox_installer::install(config, &base_dir, cookbook).map_err(|err| {
                io::Error::new(
                    io::ErrorKind::Other,
                    format!("{}", err)
                )
            })?;

94 95 96 97 98 99 100 101 102 103 104 105 106 107
            if let Some(mut redoxfs) = redoxfs_opt {
                redoxfs.unmount()?;
            }
        }

        if ! fuse {
            Command::new("tar")
                .arg("-c")
                .arg("-p")
                .arg("-f").arg(&base_partial)
                .arg("-C").arg(&base_dir)
                .arg(".")
                .status()
                .and_then(status_error)?;
108 109 110 111 112 113 114
        }

        fs::rename(&base_partial, &base_bin)?;
    }
    Ok(base_bin)
}

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
fn archive_free_space(disk_path: &Path, folder_path: &Path, bootloader_path: &Path, free_space: u64) -> io::Result<()> {
    let disk = DiskSparse::create(&disk_path).map_err(syscall_error)?;

    let bootloader = fs::read(bootloader_path)?;

    let ctime = SystemTime::now().duration_since(UNIX_EPOCH).unwrap();
    let mut fs = FileSystem::create_reserved(
        disk,
        &bootloader,
        ctime.as_secs(),
        ctime.subsec_nanos()
    ).map_err(syscall_error)?;

    let root_block = fs.header.1.root;
    archive_at(&mut fs, folder_path, root_block)?;

    let free_block = fs.header.1.free;
    let mut free = fs.node(free_block).map_err(syscall_error)?;
    let end_block = free.1.extents[0].block;
    free.1.extents[0].length = free_space;
    let end_size = end_block * BLOCK_SIZE + free.1.extents[0].length;
    fs.write_at(free.0, &free.1).map_err(syscall_error)?;

    fs.header.1.size = end_size;
    let header = fs.header;
    fs.write_at(header.0, &header.1).map_err(syscall_error)?;

    let size = header.0 * BLOCK_SIZE + end_size;
    fs.disk.file.set_len(size)?;
144

145 146 147 148
    Ok(())
}

fn inner(arguments: &[String], folder_opt: Option<String>, gui: bool) -> io::Result<i32> {
149 150 151 152
    let kvm = Path::new("/dev/kvm").exists();

    if ! installed("qemu-system-x86_64")? {
        eprintln!("redoxer: qemu-system-x86 not found, please install before continuing");
153 154 155
        process::exit(1);
    }

156 157 158 159 160 161
    let fuse = Path::new("/dev/fuse").exists();
    if ! fuse && ! installed("tar")? {
        eprintln!("redoxer: tar not found, please install before continuing");
        process::exit(1);
    }
    if fuse && ! installed("redoxfs")? {
162 163 164 165 166 167 168 169 170
        eprintln!("redoxer: redoxfs not found, installing with cargo");
        Command::new("cargo")
            .arg("install")
            .arg("redoxfs")
            .status()
            .and_then(status_error)?;
    }

    let bootloader_bin = bootloader()?;
171
    let base_bin = base(&bootloader_bin, gui, fuse)?;
172 173 174 175 176

    let tempdir = tempfile::tempdir()?;

    let code = {
        let redoxer_bin = tempdir.path().join("redoxer.bin");
177 178 179 180 181 182 183
        if fuse {
            Command::new("cp")
                .arg(&base_bin)
                .arg(&redoxer_bin)
                .status()
                .and_then(status_error)?;
        }
184 185 186 187 188

        let redoxer_dir = tempdir.path().join("redoxer");
        fs::create_dir_all(&redoxer_dir)?;

        {
189 190 191 192 193 194 195 196 197 198 199 200 201 202
            let redoxfs_opt = if fuse {
                Some(RedoxFs::new(&redoxer_bin, &redoxer_dir)?)
            } else {
                Command::new("tar")
                    .arg("-x")
                    .arg("-p")
                    .arg("--same-owner")
                    .arg("-f").arg(&base_bin)
                    .arg("-C").arg(&redoxer_dir)
                    .arg(".")
                    .status()
                    .and_then(status_error)?;
                None
            };
203 204 205

            let mut redoxerd_config = String::new();
            for arg in arguments.iter() {
Jeremy Soller's avatar
Jeremy Soller committed
206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222
                // Replace absolute path to folder with /root in command name
                // TODO: make this activated by a flag
                if let Some(ref folder) = folder_opt {
                    let folder_canonical_path = fs::canonicalize(&folder)?;
                    let folder_canonical = folder_canonical_path.to_str().ok_or(io::Error::new(
                        io::ErrorKind::Other,
                        "folder path is not valid UTF-8"
                    ))?;
                    if arg.starts_with(&folder_canonical) {
                        let arg_replace = arg.replace(folder_canonical, "/root");
                        eprintln!("redoxer: replacing '{}' with '{}' in arguments", arg, arg_replace);
                        redoxerd_config.push_str(&arg_replace);
                        redoxerd_config.push('\n');
                        continue;
                    }
                }

223 224 225 226 227
                redoxerd_config.push_str(&arg);
                redoxerd_config.push('\n');
            }
            fs::write(redoxer_dir.join("etc/redoxerd"), redoxerd_config)?;

Jeremy Soller's avatar
Jeremy Soller committed
228
            if let Some(ref folder) = folder_opt {
229 230 231 232 233 234 235 236 237 238 239 240 241 242
                eprintln!("redoxer: copying '{}' to '/root'", folder);

                let root_dir = redoxer_dir.join("root");
                Command::new("cp")
                    .arg("--dereference")
                    .arg("--no-target-directory")
                    .arg("--preserve=mode,timestamps")
                    .arg("--recursive")
                    .arg(&folder)
                    .arg(&root_dir)
                    .status()
                    .and_then(status_error)?;
            }

243 244 245 246 247 248
            if let Some(mut redoxfs) = redoxfs_opt {
                redoxfs.unmount()?;
            }
        }

        if ! fuse {
249 250 251 252 253 254
            archive_free_space(
                &redoxer_bin,
                &redoxer_dir,
                &bootloader_bin,
                1024 * 1024 * 1024
            )?;
255 256
        }

Jeremy Soller's avatar
Jeremy Soller committed
257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276
        // Set default bootloader configuration
        if gui {
            let mut f = fs::OpenOptions::new()
                .write(true)
                .open(&redoxer_bin)?;

            // Configuration is stored in the third sector
            f.seek(io::SeekFrom::Start(512 * 3))?;

            // Width and height are stored as two u16 values
            let width = 1024;
            let height = 768;
            f.write(&[
                width as u8,
                (width >> 8) as u8,
                height as u8,
                (height >> 8) as u8,
            ])?;
        }

277
        let redoxer_log = tempdir.path().join("redoxer.log");
278
        let mut command = Command::new("qemu-system-x86_64");
279
        command
280
            .arg("-cpu").arg("max")
281 282 283 284 285 286 287 288 289
            .arg("-machine").arg("q35")
            .arg("-m").arg("2048")
            .arg("-smp").arg("4")
            .arg("-serial").arg("mon:stdio")
            .arg("-chardev").arg(format!("file,id=log,path={}", redoxer_log.display()))
            .arg("-device").arg("isa-debugcon,chardev=log")
            .arg("-device").arg("isa-debug-exit")
            .arg("-netdev").arg("user,id=net0")
            .arg("-device").arg("e1000,netdev=net0")
290
            .arg("-drive").arg(format!("file={},format=raw", redoxer_bin.display()));
291 292 293 294
        if kvm {
            command
                .arg("-accel").arg("kvm");
        }
295 296 297 298 299 300 301
        if ! gui {
            command
                .arg("-nographic")
                .arg("-vga").arg("none");
        }

        let status = command.status()?;
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

        eprintln!();

        let code = match status.code() {
            Some(51) => {
                eprintln!("## redoxer (success) ##");
                0
            },
            Some(53) => {
                eprintln!("## redoxer (failure) ##");
                1
            },
            _ => {
                eprintln!("## redoxer (failure, qemu exit status {:?} ##", status);
                2
            }
        };

        print!("{}", fs::read_to_string(&redoxer_log)?);

        code
    };

    tempdir.close()?;

    Ok(code)
}

fn usage() {
331
    eprintln!("redoxer exec [-f|--folder folder] [-g|--gui] [-h|--help] [--] <command> [arguments]...");
332 333 334 335 336 337 338 339
    process::exit(1);
}

pub fn main() {
    // Matching flags
    let mut matching = true;
    // Folder to copy
    let mut folder_opt = None;
340 341
    // Run with GUI
    let mut gui = false;
342 343 344 345 346 347 348 349 350 351 352 353 354 355
    // Arguments to pass to command
    let mut arguments = Vec::new();

    let mut args = env::args().skip(2);
    while let Some(arg) = args.next() {
        match arg.as_str() {
            "-f" | "--folder" if matching => match args.next() {
                Some(folder) => {
                    folder_opt = Some(folder);
                },
                None => {
                    usage();
                },
            },
356 357 358
            "-g" | "--gui" if matching => {
                gui = true;
            },
Jeremy Soller's avatar
Jeremy Soller committed
359
            // TODO: argument for replacing the folder path with /root when found in arguments
360 361 362
            "-h" | "--help" if matching => {
                usage();
            },
Jeremy Soller's avatar
Jeremy Soller committed
363
            // TODO: "-p" | "--package"
364 365 366 367 368 369 370 371 372 373 374 375 376 377
            "--" if matching => {
                matching = false;
            }
            _ => {
                matching = false;
                arguments.push(arg);
            }
        }
    }

    if arguments.is_empty() {
        usage();
    }

378
    match inner(&arguments, folder_opt, gui) {
379 380 381 382
        Ok(code) => {
            process::exit(code);
        },
        Err(err) => {
383
            eprintln!("redoxer exec: {}", err);
384 385 386 387
            process::exit(3);
        }
    }
}