summaryrefslogtreecommitdiff
path: root/targets/kernel_vminit.zig
blob: a539689e0b404aa41040857a55fc97f88f29d91e (plain) (blame)
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
//! /init of the virtual machine `zig build test-kernel-vm` boots: this
//! machine's kernel, where we are root and BPF may be loaded. Mounts /proc,
//! /sys and /dev, runs each line of /commands, powers off.
const std = @import("std");
const linux = std.os.linux;

fn say(text: []const u8) void {
    _ = linux.write(1, text.ptr, text.len);
}

pub fn main() void {
    _ = linux.mount("proc", "/proc", "proc", 0, 0);
    _ = linux.mount("sysfs", "/sys", "sysfs", 0, 0);
    _ = linux.mount("devtmpfs", "/dev", "devtmpfs", 0, 0);
    var commands: [4096]u8 = undefined;
    const fd = linux.open("/commands", .{}, 0);
    const len = linux.read(@intCast(fd), &commands, commands.len);
    if (linux.errno(len) != .SUCCESS) say("init: no /commands\n");
    var lines = std.mem.tokenizeScalar(u8, commands[0..if (linux.errno(len) == .SUCCESS) len else 0], '\n');
    while (lines.next()) |line| {
        say("$ ");
        say(line);
        say("\n");
        // The words, each ended by a 0, in a copy.
        var text: [512]u8 = @splat(0);
        @memcpy(text[0..line.len], line);
        var argv: [32:null]?[*:0]const u8 = @splat(null);
        var words = std.mem.tokenizeScalar(u8, line, ' ');
        var count: usize = 0;
        while (words.next()) |word| : (count += 1) {
            const at = word.ptr - line.ptr;
            text[at + word.len] = 0;
            argv[count] = @ptrCast(&text[at]);
        }
        const pid = linux.fork();
        if (pid == 0) {
            _ = linux.execve(argv[0].?, &argv, &[_:null]?[*:0]const u8{});
            linux.exit_group(127);
        }
        var status: u32 = 0;
        _ = linux.waitpid(@intCast(pid), @ptrCast(&status), 0);
    }
    _ = linux.reboot(.MAGIC1, .MAGIC2, .POWER_OFF, null);
}