redoxer 0.2.32

Method for quickly running programs inside of Redox from a KVM capable OS.
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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
use redoxfs::{archive_at, DiskSparse, FileSystem, TreePtr, BLOCK_SIZE};
use std::path::{Path, PathBuf};
use std::process::{self, Command};
use std::time::{SystemTime, UNIX_EPOCH};
use std::{fs, io};

use crate::redoxfs::RedoxFs;
use crate::{installed, redoxer_dir, status_error, syscall_error, target, toolchain};

const BOOTLOADER_SIZE: usize = 2 * 1024 * 1024;
const DISK_SIZE: u64 = 1024 * 1024 * 1024;

static BASE_TOML: &'static str = include_str!("../res/base.toml");
static GUI_TOML: &'static str = include_str!("../res/gui.toml");

/// Redoxer is used for testing out apps in redox OS environment.
/// For this reason no live image is required
const INSTALL_LIVE_IMAGE: bool = false;

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, INSTALL_LIVE_IMAGE)
            .map_err(|err| io::Error::new(io::ErrorKind::Other, format!("{}", err)))?;

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

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

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

        let base_dir = redoxer_dir().join(name);
        if base_dir.is_dir() {
            fs::remove_dir_all(&base_dir)?;
        }
        fs::create_dir_all(&base_dir)?;

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

        if fuse {
            let disk = DiskSparse::create(&base_partial, DISK_SIZE).map_err(syscall_error)?;

            let bootloader = {
                let mut bootloader = fs::read(bootloader_bin)?.to_vec();

                // Pad bootloader to 2 MiB
                while bootloader.len() < BOOTLOADER_SIZE {
                    bootloader.push(0);
                }

                bootloader
            };

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

            fs.disk.file.set_len(DISK_SIZE)?;
        }

        {
            let redoxfs_opt = if fuse {
                Some(RedoxFs::new(&base_partial, &base_dir)?)
            } else {
                None
            };

            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)))?;

            let cookbook: Option<&str> = None;
            redox_installer::install(config, &base_dir, cookbook, INSTALL_LIVE_IMAGE)
                .map_err(|err| io::Error::new(io::ErrorKind::Other, format!("{}", err)))?;

            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)?;
        }

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

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

    let bootloader = {
        let mut bootloader = fs::read(bootloader_path)?.to_vec();

        // Pad bootloader to 2 MiB
        while bootloader.len() < BOOTLOADER_SIZE {
            bootloader.push(0);
        }

        bootloader
    };

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

    let end_block = fs
        .tx(|tx| {
            // Archive_at root node
            archive_at(tx, folder_path, TreePtr::root())
                .map_err(|err| syscall::Error::new(err.raw_os_error().unwrap()))?;

            // Squash alloc log
            tx.sync(true)?;

            let mut end_block = tx.header.size() / BLOCK_SIZE;
            /* TODO: Cut off any free blocks at the end of the filesystem
            let mut end_changed = true;
            while end_changed {
                end_changed = false;

                let allocator = fs.allocator();
                let levels = allocator.levels();
                for level in 0..levels.len() {
                    let level_size = 1 << level;
                    for &block in levels[level].iter() {
                        if block < end_block && block + level_size >= end_block {
                            end_block = block;
                            end_changed = true;
                        }
                    }
                }
            }
            */

            // Update header
            tx.header.size = (end_block * BLOCK_SIZE).into();
            tx.header_changed = true;
            tx.sync(false)?;

            Ok(end_block)
        })
        .map_err(syscall_error)?;

    let size = (fs.block + end_block) * BLOCK_SIZE;
    fs.disk.file.set_len(size)?;

    Ok(())
}

fn inner(
    arguments: &[String],
    folder_opt: Option<String>,
    gui: bool,
    output_opt: Option<String>,
) -> io::Result<i32> {
    let kvm = Path::new("/dev/kvm").exists();
    if !installed("qemu-system-x86_64")? {
        eprintln!("redoxer: qemu-system-x86 not found, please install before continuing");
        process::exit(1);
    }

    let fuse = Path::new("/dev/fuse").exists();
    if fuse {
        if !installed("fusermount")? {
            eprintln!("redoxer: fuse not found, please install before continuing");
            process::exit(1);
        }
    } else if !installed("tar")? {
        eprintln!("redoxer: tar not found, please install before continuing");
        process::exit(1);
    }

    let toolchain_dir = toolchain()?;
    let bootloader_bin = bootloader()?;
    let base_bin = base(&bootloader_bin, gui, fuse)?;

    let tempdir = tempfile::tempdir()?;

    let code = {
        let redoxer_bin = tempdir.path().join("redoxer.bin");
        if fuse {
            Command::new("cp")
                .arg(&base_bin)
                .arg(&redoxer_bin)
                .status()
                .and_then(status_error)?;
        }

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

        {
            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
            };

            let toolchain_lib_dir = toolchain_dir.join(target()).join("lib");
            let lib_dir = redoxer_dir.join("lib");
            for obj in &[
                "ld64.so.1",
                "libc.so",
                "libgcc_s.so",
                "libgcc_s.so.1",
                "libstdc++.so",
                "libstdc++.so.6",
                "libstdc++.so.6.0.25",
            ] {
                eprintln!("redoxer: copying '{}' to '/lib'", obj);

                Command::new("rsync")
                    .arg("--archive")
                    .arg(&toolchain_lib_dir.join(obj))
                    .arg(&lib_dir)
                    .status()
                    .and_then(status_error)?;
            }

            let mut redoxerd_config = String::new();
            for arg in arguments.iter() {
                // 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;
                    }
                }

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

            if let Some(ref folder) = folder_opt {
                eprintln!("redoxer: copying '{}' to '/root'", folder);

                let root_dir = redoxer_dir.join("root");
                Command::new("rsync")
                    .arg("--archive")
                    .arg(&folder)
                    .arg(&root_dir)
                    .status()
                    .and_then(status_error)?;
            }

            if let Some(mut redoxfs) = redoxfs_opt {
                redoxfs.unmount()?;
            }
        }

        if !fuse {
            archive_free_space(
                &redoxer_bin,
                &redoxer_dir,
                &bootloader_bin,
                DISK_SIZE,
            )?;
        }

        let redoxer_log = tempdir.path().join("redoxer.log");
        let mut command = Command::new("qemu-system-x86_64");
        command
            .arg("-cpu")
            .arg("max")
            .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")
            .arg("-drive")
            .arg(format!("file={},format=raw", redoxer_bin.display()));
        if kvm {
            command.arg("-accel").arg("kvm");
        }
        if !gui {
            command.arg("-nographic").arg("-vga").arg("none");
        }

        let status = command.status()?;

        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
            }
        };

        if let Some(output) = output_opt {
            fs::copy(&redoxer_log, output)?;
        } else {
            print!("{}", fs::read_to_string(&redoxer_log)?);
        }

        code
    };

    tempdir.close()?;

    Ok(code)
}

fn usage() {
    eprintln!("redoxer exec [-f|--folder folder] [-g|--gui] [-h|--help] [-o|--output file] [--] <command> [arguments]...");
    process::exit(1);
}

pub fn main(args: &[String]) {
    // Matching flags
    let mut matching = true;
    // Folder to copy
    let mut folder_opt = None;
    // Run with GUI
    let mut gui = false;
    // File to put command output into
    let mut output_opt = None;
    // Arguments to pass to command
    let mut arguments = Vec::new();

    let mut args = args.iter().cloned().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();
                }
            },
            "-g" | "--gui" if matching => {
                gui = true;
            }
            // TODO: argument for replacing the folder path with /root when found in arguments
            "-h" | "--help" if matching => {
                usage();
            }
            "-o" | "--output" if matching => match args.next() {
                Some(output) => {
                    output_opt = Some(output);
                }
                None => {
                    usage();
                }
            },
            // TODO: "-p" | "--package"
            "--" if matching => {
                matching = false;
            }
            _ => {
                matching = false;
                arguments.push(arg);
            }
        }
    }

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

    match inner(&arguments, folder_opt, gui, output_opt) {
        Ok(code) => {
            process::exit(code);
        }
        Err(err) => {
            eprintln!("redoxer exec: {}", err);
            process::exit(3);
        }
    }
}