danos/system/services/args-echo/args-echo.zig

51 lines
2.1 KiB
Zig

//! args-echo — a test fixture for process arguments (bundled in the
//! initial-ramdisk, spawned only by the `args` test case). Run with no arguments,
//! it respawns itself *with* some via `spawnWithArguments` — exercising the
//! system_spawn argument blob. Run with arguments, it burns more stack than one
//! page could hold (proving the multi-page stack: on a single-page stack the
//! recursion would hit the guard and the process would be killed before echoing),
//! then echoes its whole argv in one `debug_write` the kernel test asserts on —
//! proving the kernel-built System V entry stack (argc, argv pointers,
//! NUL-terminated strings) and the runtime's parsing of it, end to end.
const runtime = @import("runtime");
/// Recurse with a real frame each level: `depth` levels of ~0.5 KiB, touched
/// through a volatile pointer so no optimiser can flatten the frames away.
fn burnStack(depth: usize) u8 {
var frame: [512]u8 = undefined;
const touch: *volatile [512]u8 = &frame;
touch[0] = @truncate(depth);
touch[511] = touch[0];
if (depth == 0) return touch[511];
return touch[0] +% burnStack(depth - 1);
}
pub fn main(init: runtime.process.Init) void {
if (init.arguments.count <= 1) {
// First instance: spawn the second with real arguments, then exit.
_ = runtime.system.spawnWithArguments("args-echo", &.{ "alpha", "beta-42" });
return;
}
// ~16 x 0.5 KiB frames: comfortably past one page, well inside the 32 KiB stack.
_ = burnStack(16);
// Second instance: echo "args: <argv0> <argv1> ..." for the test to match.
var buffer: [128]u8 = undefined;
const prefix = "args:";
@memcpy(buffer[0..prefix.len], prefix);
var len: usize = prefix.len;
var iterator = init.arguments.iterate();
while (iterator.next()) |argument| {
if (len + 1 + argument.len + 1 > buffer.len) break;
buffer[len] = ' ';
len += 1;
@memcpy(buffer[len..][0..argument.len], argument);
len += argument.len;
}
buffer[len] = '\n';
len += 1;
_ = runtime.system.write(buffer[0..len]);
}