From c24a4c115eb3fd01419a550e5752165d73659c96 Mon Sep 17 00:00:00 2001 From: Rohit Goswami Date: Fri, 27 Nov 2026 00:43:47 +0100 Subject: [PATCH 01/17] feat: __vm-run runs a command under a virtual CPU that presents a target An internal helper. --mode kvm boots the host kernel under QEMU with a named CPU model and enforce, the host root shared read-only over virtiofs; --mode tcg runs the command in qemu user mode for a target of another architecture. The guest checks archdetect, archspec, gcc -march=native, the vendor and /dev/fd before the command starts, and the helper refuses when one does not name the target. --- src/main.zig | 10 + src/vm.zig | 1130 ++++++++++++++++++++++++++++++++++++++++++ src/vm/guest-init.sh | 40 ++ src/vm/tcg-ns.sh | 14 + src/vm/verify.sh | 54 ++ 5 files changed, 1248 insertions(+) create mode 100644 src/vm.zig create mode 100755 src/vm/guest-init.sh create mode 100755 src/vm/tcg-ns.sh create mode 100755 src/vm/verify.sh diff --git a/src/main.zig b/src/main.zig index 700afd3..612ae8c 100644 --- a/src/main.zig +++ b/src/main.zig @@ -37,6 +37,8 @@ pub const cvmfs = @import("cvmfs.zig"); pub const mpi = @import("mpi.zig"); /// `eb-local overlay`: declarative site overlays for upstream easyconfigs. pub const recipe_overlay = @import("recipe_overlay.zig"); +/// `eb-local __vm-run`: a command under a virtual CPU that presents a target. +pub const vm = @import("vm.zig"); /// `--json` for scriptable commands. const jsonout = @import("jsonout.zig"); const Allocator = std.mem.Allocator; @@ -7417,6 +7419,14 @@ fn runMain(init: std.process.Init) u8 { return cmdExtend(c, loadSettings(c, .{}), forwarded); } + // The internal helper `__vm-run` is not a documented command: it has no + // place in the help, and its options are its own. + if (argv_all.len > 1 and std.mem.eql(u8, argv_all[1], "__vm-run")) { + const rest = a.alloc([]const u8, argv_all.len - 2) catch oom(); + for (argv_all[2..], 0..) |arg, n| rest[n] = arg; + return vm.run(a, c.env, cwd, rest); + } + var args: []const [:0]const u8 = argv_all[1..]; var command: Command = .build; if (args.len > 0) { diff --git a/src/vm.zig b/src/vm.zig new file mode 100644 index 0000000..efcf99c --- /dev/null +++ b/src/vm.zig @@ -0,0 +1,1130 @@ +//! `eb-local __vm-run`: run a command under a virtual CPU that presents an +//! EESSI CPU target. An internal helper, absent from `--help`. +//! +//! `--mode kvm` boots the host kernel under QEMU with KVM, a named CPU model +//! per target and `enforce`; the guest's root is the host's, read-only over +//! virtiofs, with /cvmfs and the build directories shared. `--mode tcg` runs +//! the command in qemu user mode with `QEMU_CPU` set, for a target of another +//! architecture. Before the command starts, the guest checks that EESSI +//! archdetect, archspec, `gcc -march=native` (or `-mcpu=native`), the CPU +//! vendor and /dev/fd all name the target, and the helper refuses when one +//! does not. +const std = @import("std"); +const builtin = @import("builtin"); +const linux = std.os.linux; +const common = @import("zig_common"); +const sys = common.sys; +const fsx = common.fsx; +const cli = common.cli; +const proc = common.proc; +const Allocator = std.mem.Allocator; + +const guest_init = @embedFile("vm/guest-init.sh"); +const verify_script = @embedFile("vm/verify.sh"); +const tcg_ns_script = @embedFile("vm/tcg-ns.sh"); + +/// Refused before anything started: usage, an unknown target, a target this +/// mode cannot present, or a missing tool. +pub const status_refused: u8 = 2; +/// The VM or emulator failed, so the command did not report a status. +pub const status_failed: u8 = 125; +/// The guest checked the CPU view and it does not name the target; the +/// command did not run. +pub const status_unverified: u8 = 126; + +pub const Mode = enum { kvm, tcg }; +pub const Arch = enum { x86_64, aarch64 }; + +/// The architecture this binary runs on. +pub const host_arch: Arch = switch (builtin.cpu.arch) { + .aarch64 => .aarch64, + else => .x86_64, +}; + +/// The mitigation bits a host that is not affected sets, so that a guest +/// kernel does not take the Safe-RET path on every kernel entry, and the +/// TSC-deadline timer. +const amd_bits = "srso-user-kernel-no=on,sbpb=on,ibpb-brtype=on,tsa-sq-no=on,tsa-l1-no=on,tsc-deadline=on"; + +/// An EESSI CPU target, what each detector must call it, and the QEMU CPU +/// that presents it. +pub const Target = struct { + /// The EESSI software subdirectory. + name: []const u8, + arch: Arch, + /// `vendor_id` on x86_64, `CPU implementer` on aarch64. + vendor: []const u8, + /// archspec's name for the CPU. + archspec: []const u8, + /// What `gcc -march=native` (x86_64) or `-mcpu=native` (aarch64) names, + /// as space-separated alternatives. + gcc: []const u8, + /// The `-cpu` value, without `enforce`, under KVM. + kvm: ?[]const u8 = null, + kvm_refusal: []const u8 = "", + /// The `-cpu` value in qemu user mode. + tcg: ?[]const u8 = null, + tcg_refusal: []const u8 = "", +}; + +const no_zen5 = "a Zen 5 guest needs a Zen 5 host: archspec reads zen5 only with cppc, tsc_adjust and flush_l1d, none of which survive into a KVM guest"; +const no_avx512 = "TCG has no AVX-512, so the guest would be a zen3 or a haswell to every tool"; +const no_arm_kvm = "KVM on Arm offers the host CPU only; use --mode tcg from an x86_64 host"; +const no_x86_kvm = "an x86_64 target needs an x86_64 host under KVM, or --mode tcg from an aarch64 host"; + +pub const targets = [_]Target{ + .{ .name = "x86_64/amd/zen2", .arch = .x86_64, .vendor = "AuthenticAMD", .archspec = "zen2", .gcc = "znver2", .kvm = "EPYC-Rome," ++ amd_bits, .tcg = "EPYC-Rome" }, + .{ .name = "x86_64/amd/zen3", .arch = .x86_64, .vendor = "AuthenticAMD", .archspec = "zen3", .gcc = "znver3", .kvm = "EPYC-Milan,pcid=off," ++ amd_bits, .tcg = "EPYC-Milan" }, + .{ .name = "x86_64/amd/zen4", .arch = .x86_64, .vendor = "AuthenticAMD", .archspec = "zen4", .gcc = "znver4", .kvm = "EPYC-Genoa,flush-l1d=on,la57=off,pcid=off," ++ amd_bits, .tcg_refusal = no_avx512 }, + .{ .name = "x86_64/amd/zen5", .arch = .x86_64, .vendor = "AuthenticAMD", .archspec = "zen5", .gcc = "znver5", .kvm_refusal = no_zen5, .tcg_refusal = no_avx512 }, + .{ .name = "x86_64/intel/haswell", .arch = .x86_64, .vendor = "GenuineIntel", .archspec = "haswell", .gcc = "haswell", .kvm = "Haswell-noTSX-IBRS,vendor=GenuineIntel,pcid=off", .tcg = "Haswell-noTSX-IBRS,vendor=GenuineIntel" }, + .{ .name = "x86_64/intel/skylake_avx512", .arch = .x86_64, .vendor = "GenuineIntel", .archspec = "skylake_avx512", .gcc = "skylake-avx512", .kvm = "Skylake-Server-v5,vendor=GenuineIntel,pcid=off,clflushopt=on", .tcg_refusal = no_avx512 }, + .{ .name = "x86_64/intel/cascadelake", .arch = .x86_64, .vendor = "GenuineIntel", .archspec = "cascadelake", .gcc = "cascadelake", .kvm = "Cascadelake-Server-v5,vendor=GenuineIntel,pcid=off,ibrs-all=off", .tcg_refusal = no_avx512 }, + .{ .name = "x86_64/intel/icelake", .arch = .x86_64, .vendor = "GenuineIntel", .archspec = "icelake", .gcc = "icelake-server", .kvm = "Icelake-Server-v7,vendor=GenuineIntel,hle=off,rtm=off,ibrs-all=off,la57=off,pcid=off,taa-no=off", .tcg_refusal = no_avx512 }, + .{ .name = "x86_64/intel/sapphirerapids", .arch = .x86_64, .vendor = "GenuineIntel", .archspec = "sapphirerapids", .gcc = "sapphirerapids", .kvm = "SapphireRapids-v4,vendor=GenuineIntel,pcid=off,la57=off", .tcg_refusal = no_avx512 }, + .{ .name = "aarch64/neoverse_n1", .arch = .aarch64, .vendor = "0x41", .archspec = "neoverse_n1", .gcc = "neoverse-n1", .kvm_refusal = no_arm_kvm, .tcg = "neoverse-n1" }, + .{ .name = "aarch64/neoverse_v1", .arch = .aarch64, .vendor = "0x41", .archspec = "neoverse_v1", .gcc = "neoverse-v1", .kvm_refusal = no_arm_kvm, .tcg = "neoverse-v1" }, + .{ .name = "aarch64/a64fx", .arch = .aarch64, .vendor = "0x46", .archspec = "a64fx", .gcc = "a64fx", .kvm_refusal = no_arm_kvm, .tcg = "a64fx" }, +}; + +/// The target named `name`, an EESSI software subdirectory. +pub fn find(name: []const u8) ?*const Target { + for (&targets) |*t| if (std.mem.eql(u8, t.name, name)) return t; + return null; +} + +/// What a mode does for a target on a host: the QEMU CPU, or the reason it +/// cannot. +pub const Plan = union(enum) { + /// The `-cpu` value, `enforce` included. + kvm: []const u8, + /// The `QEMU_CPU` value. + tcg: []const u8, + refused: []const u8, +}; + +pub fn plan(a: Allocator, t: *const Target, mode: Mode, host: Arch) Allocator.Error!Plan { + switch (mode) { + .kvm => { + if (t.arch != host) return .{ .refused = if (t.arch == .aarch64) no_arm_kvm else no_x86_kvm }; + const model = t.kvm orelse return .{ .refused = t.kvm_refusal }; + return .{ .kvm = try std.fmt.allocPrint(a, "{s},enforce", .{model}) }; + }, + .tcg => { + if (t.arch == host) return .{ .refused = "--mode tcg is for a target of another architecture; use --mode kvm" }; + const model = t.tcg orelse return .{ .refused = t.tcg_refusal }; + return .{ .tcg = model }; + }, + } +} + +/// A command line after `__vm-run`. +pub const Request = struct { + mode: Mode, + target: []const u8, + memory_mib: u32 = 8192, + cpus: ?u32 = null, + share: []const []const u8 = &.{}, + share_ro: []const []const u8 = &.{}, + allow_archspec_mismatch: bool = false, + command: []const []const u8, +}; + +pub const Parsed = union(enum) { + ok: Request, + /// The message for stderr. + bad: []const u8, +}; + +fn optValue(args: []const []const u8, i: *usize, name: []const u8) ?[]const u8 { + const x = args[i.*]; + if (std.mem.eql(u8, x, name)) { + if (i.* + 1 >= args.len) return null; + i.* += 1; + return args[i.*]; + } + if (x.len > name.len and std.mem.startsWith(u8, x, name) and x[name.len] == '=') return x[name.len + 1 ..]; + return null; +} + +fn isOpt(x: []const u8, name: []const u8) bool { + return std.mem.eql(u8, x, name) or (x.len > name.len and std.mem.startsWith(u8, x, name) and x[name.len] == '='); +} + +/// Parse `--mode kvm|tcg --cpu-target TARGET [--memory MiB] [--cpus N] +/// [--share DIR] [--share-ro DIR] [--allow-archspec-mismatch] -- COMMAND...`. +pub fn parseArgs(a: Allocator, args: []const []const u8) Allocator.Error!Parsed { + var mode: ?Mode = null; + var target: ?[]const u8 = null; + var req: Request = .{ .mode = .kvm, .target = "", .command = &.{} }; + var share: std.ArrayList([]const u8) = .empty; + var share_ro: std.ArrayList([]const u8) = .empty; + var i: usize = 0; + while (i < args.len) : (i += 1) { + const x = args[i]; + if (std.mem.eql(u8, x, "--")) { + i += 1; + break; + } + if (isOpt(x, "--mode")) { + const v = optValue(args, &i, "--mode") orelse return .{ .bad = "--mode needs kvm or tcg" }; + mode = std.meta.stringToEnum(Mode, v) orelse return .{ .bad = "--mode takes kvm or tcg" }; + } else if (isOpt(x, "--cpu-target")) { + target = optValue(args, &i, "--cpu-target") orelse return .{ .bad = "--cpu-target needs a target" }; + } else if (isOpt(x, "--memory")) { + const v = optValue(args, &i, "--memory") orelse return .{ .bad = "--memory needs a size in MiB" }; + req.memory_mib = std.fmt.parseInt(u32, v, 10) catch return .{ .bad = "--memory takes a number of MiB" }; + if (req.memory_mib < 256) return .{ .bad = "--memory takes at least 256 MiB" }; + } else if (isOpt(x, "--cpus")) { + const v = optValue(args, &i, "--cpus") orelse return .{ .bad = "--cpus needs a number" }; + const n = std.fmt.parseInt(u32, v, 10) catch return .{ .bad = "--cpus takes a number" }; + if (n == 0) return .{ .bad = "--cpus takes at least 1" }; + req.cpus = n; + } else if (isOpt(x, "--share")) { + try share.append(a, optValue(args, &i, "--share") orelse return .{ .bad = "--share needs a directory" }); + } else if (isOpt(x, "--share-ro")) { + try share_ro.append(a, optValue(args, &i, "--share-ro") orelse return .{ .bad = "--share-ro needs a directory" }); + } else if (std.mem.eql(u8, x, "--allow-archspec-mismatch")) { + req.allow_archspec_mismatch = true; + } else { + return .{ .bad = try std.fmt.allocPrint(a, "__vm-run does not know '{s}'", .{x}) }; + } + } + req.mode = mode orelse return .{ .bad = "__vm-run needs --mode kvm|tcg" }; + req.target = target orelse return .{ .bad = "__vm-run needs --cpu-target TARGET" }; + if (i >= args.len) return .{ .bad = "__vm-run needs -- COMMAND [ARG...]" }; + req.command = args[i..]; + req.share = try share.toOwnedSlice(a); + req.share_ro = try share_ro.toOwnedSlice(a); + return .{ .ok = req }; +} + +/// One virtiofs share: a daemon serving `host`, a device tagged `tag`. +pub const Share = struct { + tag: []const u8, + host: []const u8, + /// Where the guest mounts it; empty for the root and the job directory, + /// which the kernel and the init mount. + guest: []const u8 = "", + readonly: bool = true, + cache: []const u8 = "always", +}; + +/// What the guest's kernel command line and QEMU need. +pub const KvmConfig = struct { + qemu: []const u8, + cpu: []const u8, + cpus: u32, + memory_mib: u32, + kernel: []const u8, + rundir: []const u8, + shares: []const Share, +}; + +pub fn socketPath(a: Allocator, rundir: []const u8, tag: []const u8) Allocator.Error![]u8 { + return std.fmt.allocPrint(a, "{s}/{s}.sock", .{ rundir, tag }); +} + +/// The kernel command line: the host root over virtiofs, read-only, and the +/// init in the job directory. +pub fn kernelCmdline(a: Allocator, rundir: []const u8) Allocator.Error![]u8 { + return std.fmt.allocPrint(a, "console=ttyS0 rootfstype=virtiofs root=hostroot ro init={s}/init panic=-1 quiet", .{rundir}); +} + +/// The QEMU command line. The CPU is the named model with `enforce`; no +/// argument names the host CPU. +pub fn qemuArgv(a: Allocator, cfg: KvmConfig) Allocator.Error![]const []const u8 { + var v: std.ArrayList([]const u8) = .empty; + const fixed = [_][]const u8{ "-accel", "kvm", "-machine", "q35", "-display", "none", "-nodefaults", "-no-user-config", "-monitor", "none", "-no-reboot", "-cpu" }; + for (fixed) |x| try v.append(a, x); + try v.append(a, cfg.cpu); + try v.append(a, "-smp"); + try v.append(a, try std.fmt.allocPrint(a, "{d}", .{cfg.cpus})); + try v.append(a, "-m"); + try v.append(a, try std.fmt.allocPrint(a, "{d}M", .{cfg.memory_mib})); + try v.append(a, "-object"); + try v.append(a, try std.fmt.allocPrint(a, "memory-backend-memfd,id=mem,size={d}M,share=on", .{cfg.memory_mib})); + try v.append(a, "-numa"); + try v.append(a, "node,memdev=mem"); + for (cfg.shares, 0..) |s, n| { + try v.append(a, "-chardev"); + try v.append(a, try std.fmt.allocPrint(a, "socket,id=fs{d},path={s}", .{ n, try socketPath(a, cfg.rundir, s.tag) })); + try v.append(a, "-device"); + try v.append(a, try std.fmt.allocPrint(a, "vhost-user-fs-pci,chardev=fs{d},tag={s}", .{ n, s.tag })); + } + // ttyS0 is the console log; ttyS1 and ttyS2 carry the command's stdout and stderr. + try v.append(a, "-serial"); + try v.append(a, try std.fmt.allocPrint(a, "file:{s}/console.log", .{cfg.rundir})); + try v.append(a, "-chardev"); + try v.append(a, "file,id=so,path=/proc/self/fd/1,append=on"); + try v.append(a, "-serial"); + try v.append(a, "chardev:so"); + try v.append(a, "-chardev"); + try v.append(a, "file,id=se,path=/proc/self/fd/2,append=on"); + try v.append(a, "-serial"); + try v.append(a, "chardev:se"); + try v.append(a, "-kernel"); + try v.append(a, cfg.kernel); + try v.append(a, "-append"); + try v.append(a, try kernelCmdline(a, cfg.rundir)); + return v.toOwnedSlice(a); +} + +pub fn virtiofsdArgv(a: Allocator, virtiofsd: []const u8, rundir: []const u8, s: Share) Allocator.Error![]const []const u8 { + var v: std.ArrayList([]const u8) = .empty; + try v.append(a, virtiofsd); + try v.append(a, try std.fmt.allocPrint(a, "--socket-path={s}", .{try socketPath(a, rundir, s.tag)})); + try v.append(a, try std.fmt.allocPrint(a, "--shared-dir={s}", .{s.host})); + try v.append(a, "--sandbox=none"); + if (s.readonly) try v.append(a, "--readonly"); + try v.append(a, try std.fmt.allocPrint(a, "--cache={s}", .{s.cache})); + try v.append(a, "--log-level=error"); + return v.toOwnedSlice(a); +} + +/// The guest init's `mounts` file: one line per mount, parent paths first. +pub fn mountsFile(a: Allocator, shares: []const Share, cvmfs_root: bool) Allocator.Error![]u8 { + var out: std.ArrayList(u8) = .empty; + if (cvmfs_root) try out.appendSlice(a, "tmpfs cvmfs /cvmfs\n"); + for (shares) |s| { + if (s.guest.len == 0) continue; + try out.print(a, "virtiofs {s} {s} {s}\n", .{ s.tag, s.guest, if (s.readonly) "ro" else "rw" }); + } + return out.toOwnedSlice(a); +} + +/// Drop each path that lies inside another one in the list, and repeats; +/// sorted shortest first so that a parent is mounted before its children +/// would be. +pub fn dedupePaths(a: Allocator, paths: []const []const u8) Allocator.Error![]const []const u8 { + const sorted = try a.dupe([]const u8, paths); + std.mem.sort([]const u8, sorted, {}, struct { + fn lt(_: void, x: []const u8, y: []const u8) bool { + if (x.len != y.len) return x.len < y.len; + return std.mem.lessThan(u8, x, y); + } + }.lt); + var keep: std.ArrayList([]const u8) = .empty; + outer: for (sorted) |p| { + for (keep.items) |k| { + if (std.mem.eql(u8, k, p)) continue :outer; + if (std.mem.startsWith(u8, p, k) and p.len > k.len and (p[k.len] == '/' or std.mem.eql(u8, k, "/"))) continue :outer; + } + try keep.append(a, p); + } + return keep.toOwnedSlice(a); +} + +/// Environment variables the command receives in the guest. +pub fn envForwarded(name: []const u8) bool { + const exact = [_][]const u8{ + "PATH", "HOME", "USER", "LOGNAME", "LANG", "TERM", "TZ", "TMPDIR", + "MODULEPATH", "LOADEDMODULES", "_LMFILES_", "XDG_CACHE_HOME", "XDG_CONFIG_HOME", "XDG_DATA_HOME", "SOURCE_DATE_EPOCH", "WORKING_DIR", + }; + for (exact) |e| if (std.mem.eql(u8, name, e)) return true; + const prefixes = [_][]const u8{ "LC_", "LMOD", "EASYBUILD_", "EESSI_", "EB_", "SLURM_" }; + if (std.mem.startsWith(u8, name, "EB_LOCAL_VM_")) return false; + for (prefixes) |p| if (std.mem.startsWith(u8, name, p)) return true; + return false; +} + +/// The variables whose values name directories the command writes. +pub const writable_vars = [_][]const u8{ + "HOME", "TMPDIR", "XDG_CACHE_HOME", "WORKING_DIR", "EASYBUILD_PREFIX", + "EASYBUILD_BUILDPATH", "EASYBUILD_INSTALLPATH", "EASYBUILD_SOURCEPATH", "EASYBUILD_REPOSITORYPATH", "EESSI_USER_INSTALL", + "EESSI_PROJECT_INSTALL", "EESSI_SITE_INSTALL", +}; + +/// `s` in single quotes for a POSIX shell. +pub fn shellQuote(a: Allocator, s: []const u8) Allocator.Error![]u8 { + var out: std.ArrayList(u8) = .empty; + try out.append(a, '\''); + for (s) |c| { + if (c == '\'') { + try out.appendSlice(a, "'\\''"); + } else try out.append(a, c); + } + try out.append(a, '\''); + return out.toOwnedSlice(a); +} + +/// The values the job script exports for the verification and the command. +pub const Job = struct { + /// The job directory as the command sees it. + dir: []const u8, + cwd: []const u8, + t: *const Target, + eessi_version: []const u8, + allow_archspec_mismatch: bool, + gcc_bin: []const u8 = "", + /// Name and value of every variable the command receives. + env: []const [2][]const u8, + command: []const []const u8, +}; + +pub fn jobScript(a: Allocator, j: Job) Allocator.Error![]u8 { + var out: std.ArrayList(u8) = .empty; + try out.appendSlice(a, "#!/bin/bash\n"); + for (j.env) |kv| try out.print(a, "export {s}={s}\n", .{ kv[0], try shellQuote(a, kv[1]) }); + const arch = @tagName(j.t.arch); + const pairs = [_][2][]const u8{ + .{ "EBVM_DIR", j.dir }, + .{ "EBVM_ARCH", arch }, + .{ "EBVM_TARGET", j.t.name }, + .{ "EBVM_VENDOR", j.t.vendor }, + .{ "EBVM_ARCHSPEC", j.t.archspec }, + .{ "EBVM_GCC", j.t.gcc }, + .{ "EBVM_EESSI_VERSION", j.eessi_version }, + .{ "EBVM_ALLOW_ARCHSPEC", if (j.allow_archspec_mismatch) "1" else "0" }, + .{ "EBVM_GCC_BIN", j.gcc_bin }, + }; + for (pairs) |kv| try out.print(a, "export {s}={s}\n", .{ kv[0], try shellQuote(a, kv[1]) }); + try out.print(a, "cd {s} || {{ echo 'eb-local: vm-run: cannot enter the working directory' >&2; exit 127; }}\n", .{try shellQuote(a, j.cwd)}); + try out.appendSlice(a, "bash \"$EBVM_DIR/verify.sh\" || exit 126\n"); + try out.appendSlice(a, "exec"); + for (j.command) |x| try out.print(a, " {s}", .{try shellQuote(a, x)}); + try out.append(a, '\n'); + return out.toOwnedSlice(a); +} + +/// What the guest left in the job directory. +pub const Outcome = struct { + /// The `refused` file, when the verification refused. + refused: ?[]const u8 = null, + /// The `status` file, when the guest init wrote one. + status: ?[]const u8 = null, +}; + +/// The helper's exit status for what the guest reported. A refusal is 126 +/// whatever else exists; a command's own status passes through; no report is +/// a VM failure. +pub fn exitStatus(o: Outcome) u8 { + if (o.refused != null) return status_unverified; + const text = std.mem.trim(u8, o.status orelse return status_failed, " \t\r\n"); + const n = std.fmt.parseInt(u16, text, 10) catch return status_failed; + if (n > 255) return status_failed; + return @intCast(n); +} + +/// The status of a process the helper waited for: its exit code, or 128 plus +/// the signal. +pub fn termStatus(raw: u32) u8 { + if (linux.W.IFEXITED(raw)) return linux.W.EXITSTATUS(raw); + if (linux.W.IFSIGNALED(raw)) return @intCast(128 + @as(u32, @backingInt(linux.W.TERMSIG(raw)))); + return status_failed; +} + +fn err(comptime fmt: []const u8, args: anytype) void { + cli.err("eb-local: vm-run: " ++ fmt ++ "\n", args); +} + +fn readSmall(a: Allocator, path: []const u8) ?[]u8 { + const fd = sys.openat(fsx.cwd, path, .{}, 0) catch return null; + defer sys.close(fd); + return fsx.readAll(a, fd, 1 << 20) catch null; +} + +fn writeFile(path: []const u8, bytes: []const u8, mode: linux.mode_t) !void { + const fd = try sys.openat(fsx.cwd, path, .{ .ACCMODE = .WRONLY, .CREAT = true, .TRUNC = true }, mode); + defer sys.close(fd); + try sys.writeAll(fd, bytes); + try sys.fchmod(fd, mode); +} + +fn isDir(path: []const u8) bool { + const st = fsx.statAt(fsx.cwd, path, true) catch return false; + return st.isDir(); +} + +fn executable(a: Allocator, path: []const u8) bool { + const z = a.dupeZ(u8, path) catch return false; + return linux.errno(linux.access(z.ptr, 1)) == .SUCCESS; +} + +/// An executable `name`: in `EB_LOCAL_QEMU_DIR` when that is set and holds +/// it, then in PATH, then in the usual places a distribution puts it. +fn locate(a: Allocator, env: *const std.process.Environ.Map, name: []const u8, extra: []const []const u8) ?[]const u8 { + if (env.get("EB_LOCAL_QEMU_DIR")) |d| if (d.len > 0) { + const p = std.fs.path.join(a, &.{ d, name }) catch return null; + if (executable(a, p)) return p; + }; + if (env.get("PATH")) |path| { + if (proc.which(a, name, path) catch null) |p| return p; + } + for (extra) |d| { + const p = std.fs.path.join(a, &.{ d, name }) catch return null; + if (executable(a, p)) return p; + } + return null; +} + +fn cpuCount() u32 { + var set: linux.cpu_set_t = undefined; + if (linux.errno(linux.sched_getaffinity(0, @sizeOf(linux.cpu_set_t), &set)) != .SUCCESS) return 1; + return @max(linux.CPU_COUNT(set), 1); +} + +fn kernelPath(a: Allocator, env: *const std.process.Environ.Map) ?[]const u8 { + if (env.get("EB_LOCAL_VM_KERNEL")) |k| if (k.len > 0) return k; + var uts: linux.utsname = undefined; + if (linux.errno(linux.uname(&uts)) != .SUCCESS) return null; + const rel = std.mem.sliceTo(&uts.release, 0); + const cands = [_][]const u8{ + std.fmt.allocPrint(a, "/lib/modules/{s}/vmlinuz", .{rel}) catch return null, + std.fmt.allocPrint(a, "/boot/vmlinuz-{s}", .{rel}) catch return null, + "/boot/vmlinuz", + }; + for (cands) |p| { + const fd = sys.openat(fsx.cwd, p, .{}, 0) catch continue; + sys.close(fd); + return p; + } + return null; +} + +const Spawned = struct { pid: linux.pid_t }; + +fn spawn(a: Allocator, argv: []const []const u8, envp: proc.Envp) !Spawned { + const zargv = try a.allocSentinel(?[*:0]const u8, argv.len, null); + for (argv, 0..) |x, i| zargv[i] = (try a.dupeZ(u8, x)).ptr; + const rc = linux.fork(); + switch (linux.errno(rc)) { + .SUCCESS => {}, + else => return error.SpawnFailed, + } + if (rc == 0) { + // A child does not outlive the helper. + _ = linux.prctl(@backingInt(linux.PR.SET_PDEATHSIG), @intCast(@backingInt(linux.SIG.KILL)), 0, 0, 0); + _ = linux.execve(zargv[0].?, zargv.ptr, envp); + cli.err("eb-local: vm-run: cannot run {s}\n", .{argv[0]}); + linux.exit_group(127); + } + return .{ .pid = @intCast(rc) }; +} + +fn waitFor(pid: linux.pid_t) u32 { + var raw: i32 = 0; + while (true) { + const rc = linux.wait4(pid, &raw, 0, null); + switch (linux.errno(rc)) { + .SUCCESS => return @bitCast(raw), + .INTR => continue, + else => return 0xff00, + } + } +} + +fn waitForSocket(path: []const u8) bool { + var tries: u32 = 0; + while (tries < 100) : (tries += 1) { + if (fsx.statAt(fsx.cwd, path, true)) |_| return true else |_| {} + var ts: linux.timespec = .{ .sec = 0, .nsec = 100 * std.time.ns_per_ms }; + _ = linux.nanosleep(&ts, null); + } + return false; +} + +/// The directories to mount writable and read-only: the working directory, +/// the caller's `--share`s and the directories its environment names, each +/// only when it exists and no wider share holds it. +fn writableShares(a: Allocator, env: *const std.process.Environ.Map, cwd: []const u8, extra: []const []const u8) ![]const []const u8 { + var list: std.ArrayList([]const u8) = .empty; + try list.append(a, cwd); + for (extra) |p| try list.append(a, p); + for (writable_vars) |name| { + const v = env.get(name) orelse continue; + var it = std.mem.splitScalar(u8, v, ':'); + while (it.next()) |p| try list.append(a, p); + } + var ok: std.ArrayList([]const u8) = .empty; + for (list.items) |p| { + if (p.len == 0 or p[0] != '/' or std.mem.eql(u8, p, "/")) continue; + if (std.mem.indexOfAny(u8, p, " \t\n\\\"'") != null) continue; + if (isDir(p)) try ok.append(a, try fsx.absPath(a, p)); + } + return dedupePaths(a, ok.items); +} + +/// Run `request` and return the helper's exit status. +pub fn run(a: Allocator, env: *const std.process.Environ.Map, cwd: []const u8, args: []const []const u8) u8 { + const parsed = parseArgs(a, args) catch { + err("out of memory", .{}); + return status_failed; + }; + const req = switch (parsed) { + .ok => |r| r, + .bad => |m| { + err("{s}", .{m}); + return status_refused; + }, + }; + const t = find(req.target) orelse { + var names: std.ArrayList(u8) = .empty; + for (&targets) |*x| names.print(a, " {s}", .{x.name}) catch {}; + err("unknown target '{s}'; known:{s}", .{ req.target, names.items }); + return status_refused; + }; + const chosen = plan(a, t, req.mode, host_arch) catch return status_failed; + switch (chosen) { + .refused => |why| { + err("{s} under --mode {s}: {s}", .{ t.name, @tagName(req.mode), why }); + return status_refused; + }, + .kvm => |cpu| return runKvm(a, env, cwd, req, t, cpu), + .tcg => |cpu| return runTcg(a, env, cwd, req, t, cpu), + } +} + +fn eessiVersion(env: *const std.process.Environ.Map) []const u8 { + if (env.get("EB_LOCAL_VM_EESSI_VERSION")) |v| if (v.len > 0) return v; + return "2025.06"; +} + +/// A directory for the job: `EB_LOCAL_VM_DIR`, TMPDIR, /var/tmp or /tmp. +/// Under KVM it must be on the root file system, which the guest boots from. +fn makeRundir(a: Allocator, env: *const std.process.Environ.Map, need_root_fs: bool) ?[]const u8 { + const root_dev = (fsx.statAt(fsx.cwd, "/", true) catch return null).dev; + var cands: std.ArrayList([]const u8) = .empty; + if (env.get("EB_LOCAL_VM_DIR")) |d| if (d.len > 0) cands.append(a, d) catch return null; + if (env.get("TMPDIR")) |d| if (d.len > 0) cands.append(a, d) catch return null; + cands.append(a, "/var/tmp") catch return null; + cands.append(a, "/tmp") catch return null; + for (cands.items) |d| { + const st = fsx.statAt(fsx.cwd, d, true) catch continue; + if (!st.isDir()) continue; + if (need_root_fs and st.dev != root_dev) continue; + if (std.mem.indexOfAny(u8, d, " \t\n") != null) continue; + return fsx.mkdtemp(a, d, "eb-local-vm.") catch continue; + } + return null; +} + +fn forwardedEnv(a: Allocator, env: *const std.process.Environ.Map, path_override: ?[]const u8) ![]const [2][]const u8 { + var out: std.ArrayList([2][]const u8) = .empty; + var it = env.iterator(); + while (it.next()) |kv| { + const name = kv.key_ptr.*; + if (!envForwarded(name) or !common.env.validName(name)) continue; + var value = kv.value_ptr.*; + if (path_override) |p| if (std.mem.eql(u8, name, "PATH")) { + value = p; + }; + try out.append(a, .{ name, value }); + } + return out.toOwnedSlice(a); +} + +fn envBlock(a: Allocator, env: *const std.process.Environ.Map, extra: []const [2][]const u8) !proc.Envp { + var b: common.env.Builder = .init(a); + var it = env.iterator(); + while (it.next()) |kv| try b.set(kv.key_ptr.*, kv.value_ptr.*); + for (extra) |kv| try b.set(kv[0], kv[1]); + return b.envp(); +} + +fn runKvm(a: Allocator, env: *const std.process.Environ.Map, cwd: []const u8, req: Request, t: *const Target, cpu: []const u8) u8 { + const qemu_name = if (host_arch == .x86_64) "qemu-system-x86_64" else "qemu-system-aarch64"; + const qemu = locate(a, env, qemu_name, &.{ "/usr/bin", "/usr/local/bin" }) orelse { + err("{s} not found: put it on PATH or set EB_LOCAL_QEMU_DIR to its directory", .{qemu_name}); + return status_refused; + }; + const virtiofsd = if (env.get("EB_LOCAL_VIRTIOFSD")) |v| (if (v.len > 0) v else null) else null; + const vfsd = virtiofsd orelse locate(a, env, "virtiofsd", &.{ "/usr/lib/virtiofsd", "/usr/libexec", "/usr/bin" }) orelse { + err("virtiofsd not found: put it on PATH, in EB_LOCAL_QEMU_DIR, or set EB_LOCAL_VIRTIOFSD to its path", .{}); + return status_refused; + }; + const kernel = kernelPath(a, env) orelse { + err("no readable host kernel image: set EB_LOCAL_VM_KERNEL (it needs virtiofs and virtio-pci built in)", .{}); + return status_refused; + }; + const kvm_z = a.dupeZ(u8, "/dev/kvm") catch return status_failed; + if (linux.errno(linux.access(kvm_z.ptr, 6)) != .SUCCESS) { + err("/dev/kvm is not readable and writable here; --mode kvm needs KVM", .{}); + return status_refused; + } + const rundir = makeRundir(a, env, true) orelse { + err("no directory for the job on the root file system: set EB_LOCAL_VM_DIR", .{}); + return status_refused; + }; + + // The shares: the host root, the job directory, EESSI, and what the build writes. + var shares: std.ArrayList(Share) = .empty; + const build = fail: { + shares.append(a, .{ .tag = "hostroot", .host = "/" }) catch break :fail false; + shares.append(a, .{ .tag = "job", .host = rundir, .readonly = false, .cache = "never" }) catch break :fail false; + const repos = if (env.get("EB_LOCAL_VM_CVMFS_REPOS")) |v| (if (v.len > 0) v else "software.eessi.io") else "software.eessi.io"; + var rit = std.mem.tokenizeAny(u8, repos, ": ,"); + var n: usize = 0; + while (rit.next()) |repo| : (n += 1) { + shares.append(a, .{ + .tag = std.fmt.allocPrint(a, "cvmfs{d}", .{n}) catch break :fail false, + .host = std.fmt.allocPrint(a, "/cvmfs/{s}", .{repo}) catch break :fail false, + .guest = std.fmt.allocPrint(a, "/cvmfs/{s}", .{repo}) catch break :fail false, + }) catch break :fail false; + } + const extra_rw = writableShares(a, env, cwd, req.share) catch break :fail false; + for (extra_rw, 0..) |p, i| shares.append(a, .{ + .tag = std.fmt.allocPrint(a, "rw{d}", .{i}) catch break :fail false, + .host = p, + .guest = p, + .readonly = false, + .cache = "auto", + }) catch break :fail false; + for (req.share_ro, 0..) |p, i| shares.append(a, .{ + .tag = std.fmt.allocPrint(a, "ro{d}", .{i}) catch break :fail false, + .host = fsx.absPath(a, p) catch break :fail false, + .guest = fsx.absPath(a, p) catch break :fail false, + }) catch break :fail false; + break :fail true; + }; + if (!build) return status_failed; + + const mount_text = mountsFile(a, shares.items, true) catch return status_failed; + const uid = linux.getuid(); + const gid = linux.getgid(); + var groups_buf: [256]linux.gid_t = undefined; + const ng = linux.getgroups(groups_buf.len, &groups_buf); + var ids: std.ArrayList(u8) = .empty; + ids.print(a, "EBVM_UID={d}\nEBVM_GID={d}\nEBVM_GROUPS=", .{ uid, gid }) catch return status_failed; + if (linux.errno(ng) == .SUCCESS) { + for (groups_buf[0..ng], 0..) |g, i| ids.print(a, "{s}{d}", .{ if (i > 0) "," else "", g }) catch return status_failed; + } + ids.append(a, '\n') catch return status_failed; + + const fwd = forwardedEnv(a, env, null) catch return status_failed; + const gcc_bin = if (env.get("EB_LOCAL_VM_GCC")) |v| v else ""; + const job = jobScript(a, .{ + .dir = "/run/ebvm", + .cwd = cwd, + .t = t, + .eessi_version = eessiVersion(env), + .allow_archspec_mismatch = req.allow_archspec_mismatch, + .gcc_bin = gcc_bin, + .env = fwd, + .command = req.command, + }) catch return status_failed; + + const files = [_]struct { name: []const u8, bytes: []const u8, mode: linux.mode_t }{ + .{ .name = "init", .bytes = guest_init, .mode = 0o755 }, + .{ .name = "verify.sh", .bytes = verify_script, .mode = 0o755 }, + .{ .name = "job.sh", .bytes = job, .mode = 0o700 }, + .{ .name = "mounts", .bytes = mount_text, .mode = 0o600 }, + .{ .name = "ids", .bytes = ids.items, .mode = 0o600 }, + }; + for (files) |f| { + const p = std.fs.path.join(a, &.{ rundir, f.name }) catch return status_failed; + writeFile(p, f.bytes, f.mode) catch |e| { + err("cannot write {s}: {s}", .{ p, sys.describe(sys.asError(e) orelse error.Unexpected) }); + return status_failed; + }; + } + + const base_env = envBlock(a, env, &.{}) catch return status_failed; + var daemons: std.ArrayList(linux.pid_t) = .empty; + defer { + for (daemons.items) |pid| { + _ = linux.kill(pid, .TERM); + _ = waitFor(pid); + } + } + for (shares.items) |s| { + const argv = virtiofsdArgv(a, vfsd, rundir, s) catch return status_failed; + const sp = spawn(a, argv, base_env) catch { + err("cannot start virtiofsd", .{}); + return status_failed; + }; + daemons.append(a, sp.pid) catch return status_failed; + } + for (shares.items) |s| { + const sock = socketPath(a, rundir, s.tag) catch return status_failed; + if (!waitForSocket(sock)) { + err("virtiofsd did not create {s}; sharing {s} failed", .{ sock, s.host }); + return status_failed; + } + } + + const qargs = qemuArgv(a, .{ + .qemu = qemu, + .cpu = cpu, + .cpus = req.cpus orelse cpuCount(), + .memory_mib = req.memory_mib, + .kernel = kernel, + .rundir = rundir, + .shares = shares.items, + }) catch return status_failed; + var argv: std.ArrayList([]const u8) = .empty; + argv.append(a, qemu) catch return status_failed; + argv.appendSlice(a, qargs) catch return status_failed; + const q = spawn(a, argv.items, base_env) catch { + err("cannot start QEMU", .{}); + return status_failed; + }; + const raw = waitFor(q.pid); + + const outcome: Outcome = .{ + .refused = readSmall(a, std.fs.path.join(a, &.{ rundir, "refused" }) catch return status_failed), + .status = readSmall(a, std.fs.path.join(a, &.{ rundir, "status" }) catch return status_failed), + }; + const code = exitStatus(outcome); + if (code == status_failed) { + err("the guest reported no status (QEMU {s}); console log: {s}/console.log", .{ if (termStatus(raw) == 0) "exited 0" else "failed", rundir }); + if (readSmall(a, std.fs.path.join(a, &.{ rundir, "console.log" }) catch return status_failed)) |c| { + const tail = if (c.len > 2000) c[c.len - 2000 ..] else c; + cli.err("{s}\n", .{tail}); + } + if (qemuRefusedModel(raw)) err("QEMU refused the CPU model {s}: this host lacks a feature it needs (enforce is on, and the helper never falls back to the host CPU)", .{cpu}); + return status_failed; + } + if (outcome.refused) |m| err("not run: {s}", .{std.mem.trim(u8, m, "\n")}); + if (std.mem.eql(u8, env.get("EB_LOCAL_VM_KEEP") orelse "", "1")) { + err("job directory kept: {s}", .{rundir}); + } else fsx.deleteTree(a, fsx.cwd, rundir) catch {}; + return code; +} + +fn qemuRefusedModel(raw: u32) bool { + return linux.W.IFEXITED(raw) and linux.W.EXITSTATUS(raw) != 0; +} + +fn runTcg(a: Allocator, env: *const std.process.Environ.Map, cwd: []const u8, req: Request, t: *const Target, cpu: []const u8) u8 { + const arch = @tagName(t.arch); + const qemu_name = std.fmt.allocPrint(a, "qemu-{s}", .{arch}) catch return status_failed; + const qemu = locate(a, env, qemu_name, &.{ "/usr/bin", "/usr/local/bin" }) orelse { + err("{s} not found: put it on PATH or set EB_LOCAL_QEMU_DIR to its directory", .{qemu_name}); + return status_refused; + }; + const version = eessiVersion(env); + const compat = std.fmt.allocPrint(a, "/cvmfs/software.eessi.io/versions/{s}/compat/linux/{s}", .{ version, arch }) catch return status_failed; + if (!isDir(compat)) { + err("the EESSI {s} compat layer is not readable at {s}", .{ version, compat }); + return status_refused; + } + const rundir = makeRundir(a, env, false) orelse { + err("no directory for the job: set EB_LOCAL_VM_DIR", .{}); + return status_refused; + }; + const prefix_path = std.fmt.allocPrint(a, "{s}/bin:{s}/usr/bin:{s}/sbin:{s}/usr/sbin", .{ compat, compat, compat, compat }) catch return status_failed; + const path = std.fmt.allocPrint(a, "{s}:{s}", .{ prefix_path, env.get("PATH") orelse "/usr/bin:/bin" }) catch return status_failed; + var fwd: std.ArrayList([2][]const u8) = .empty; + fwd.appendSlice(a, forwardedEnv(a, env, path) catch return status_failed) catch return status_failed; + var has_path = false; + for (fwd.items) |kv| if (std.mem.eql(u8, kv[0], "PATH")) { + has_path = true; + }; + if (!has_path) fwd.append(a, .{ "PATH", path }) catch return status_failed; + fwd.append(a, .{ "QEMU_CPU", cpu }) catch return status_failed; + const job = jobScript(a, .{ + .dir = rundir, + .cwd = cwd, + .t = t, + .eessi_version = version, + .allow_archspec_mismatch = req.allow_archspec_mismatch, + .gcc_bin = env.get("EB_LOCAL_VM_GCC") orelse "", + .env = fwd.items, + .command = req.command, + }) catch return status_failed; + const files = [_]struct { name: []const u8, bytes: []const u8, mode: linux.mode_t }{ + .{ .name = "verify.sh", .bytes = verify_script, .mode = 0o755 }, + .{ .name = "tcg-ns.sh", .bytes = tcg_ns_script, .mode = 0o755 }, + .{ .name = "job.sh", .bytes = job, .mode = 0o700 }, + }; + for (files) |f| { + const p = std.fs.path.join(a, &.{ rundir, f.name }) catch return status_failed; + writeFile(p, f.bytes, f.mode) catch |e| { + err("cannot write {s}: {s}", .{ p, sys.describe(sys.asError(e) orelse error.Unexpected) }); + return status_failed; + }; + } + const job_path = std.fs.path.join(a, &.{ rundir, "job.sh" }) catch return status_failed; + const ns_path = std.fs.path.join(a, &.{ rundir, "tcg-ns.sh" }) catch return status_failed; + const bash = locate(a, env, "bash", &.{ "/usr/bin", "/bin" }) orelse { + err("bash not found", .{}); + return status_refused; + }; + + const registered = std.fmt.allocPrint(a, "/proc/sys/fs/binfmt_misc/qemu-{s}", .{arch}) catch return status_failed; + const have_binfmt = if (fsx.statAt(fsx.cwd, registered, true)) |_| true else |_| false; + var argv: std.ArrayList([]const u8) = .empty; + var extra: std.ArrayList([2][]const u8) = .empty; + extra.append(a, .{ "QEMU_CPU", cpu }) catch return status_failed; + if (have_binfmt) { + argv.appendSlice(a, &.{ bash, job_path }) catch return status_failed; + extra.append(a, .{ "PATH", path }) catch return status_failed; + } else { + const unshare = locate(a, env, "unshare", &.{ "/usr/bin", "/bin" }) orelse { + err("no binfmt_misc entry for qemu-{s} and no unshare to register one in a user namespace", .{arch}); + return status_refused; + }; + argv.appendSlice(a, &.{ unshare, "--user", "--map-root-user", "--mount", bash, ns_path }) catch return status_failed; + const idv = [_][2][]const u8{ + .{ "EBVM_ARCH", arch }, + .{ "EBVM_QEMU_USER", qemu }, + .{ "EBVM_QEMU_CPU", cpu }, + .{ "EBVM_UID", std.fmt.allocPrint(a, "{d}", .{linux.getuid()}) catch return status_failed }, + .{ "EBVM_GID", std.fmt.allocPrint(a, "{d}", .{linux.getgid()}) catch return status_failed }, + .{ "EBVM_JOB", job_path }, + .{ "EBVM_PATH", path }, + }; + extra.appendSlice(a, &idv) catch return status_failed; + } + const envp = envBlock(a, env, extra.items) catch return status_failed; + const child = spawn(a, argv.items, envp) catch { + err("cannot start the emulation", .{}); + return status_failed; + }; + const raw = waitFor(child.pid); + const refused = readSmall(a, std.fs.path.join(a, &.{ rundir, "refused" }) catch return status_failed); + var code = termStatus(raw); + if (refused != null) { + code = status_unverified; + err("not run: {s}", .{std.mem.trim(u8, refused.?, "\n")}); + } + fsx.deleteTree(a, fsx.cwd, rundir) catch {}; + return code; +} + +const testing = std.testing; + +fn testTarget(name: []const u8) *const Target { + return find(name).?; +} + +test "an AMD target keeps its model, the corrections and enforce" { + var arena: std.heap.ArenaAllocator = .init(testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const zen4 = try plan(a, testTarget("x86_64/amd/zen4"), .kvm, .x86_64); + try testing.expectEqualStrings("EPYC-Genoa,flush-l1d=on,la57=off,pcid=off,srso-user-kernel-no=on,sbpb=on,ibpb-brtype=on,tsa-sq-no=on,tsa-l1-no=on,tsc-deadline=on,enforce", zen4.kvm); + const zen3 = try plan(a, testTarget("x86_64/amd/zen3"), .kvm, .x86_64); + try testing.expectEqualStrings("EPYC-Milan,pcid=off,srso-user-kernel-no=on,sbpb=on,ibpb-brtype=on,tsa-sq-no=on,tsa-l1-no=on,tsc-deadline=on,enforce", zen3.kvm); + const zen2 = try plan(a, testTarget("x86_64/amd/zen2"), .kvm, .x86_64); + try testing.expect(std.mem.startsWith(u8, zen2.kvm, "EPYC-Rome,srso-user-kernel-no=on")); + try testing.expect(std.mem.endsWith(u8, zen2.kvm, ",enforce")); +} + +test "an Intel target names the vendor and strips only non-ISA bits" { + var arena: std.heap.ArenaAllocator = .init(testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + for ([_][]const u8{ "x86_64/intel/haswell", "x86_64/intel/skylake_avx512", "x86_64/intel/cascadelake", "x86_64/intel/icelake", "x86_64/intel/sapphirerapids" }) |name| { + const p = try plan(a, testTarget(name), .kvm, .x86_64); + try testing.expect(std.mem.indexOf(u8, p.kvm, "vendor=GenuineIntel") != null); + try testing.expect(std.mem.endsWith(u8, p.kvm, ",enforce")); + } + const icelake = try plan(a, testTarget("x86_64/intel/icelake"), .kvm, .x86_64); + try testing.expectEqualStrings("Icelake-Server-v7,vendor=GenuineIntel,hle=off,rtm=off,ibrs-all=off,la57=off,pcid=off,taa-no=off,enforce", icelake.kvm); + const skylake = try plan(a, testTarget("x86_64/intel/skylake_avx512"), .kvm, .x86_64); + try testing.expect(std.mem.indexOf(u8, skylake.kvm, "clflushopt=on") != null); + const spr = try plan(a, testTarget("x86_64/intel/sapphirerapids"), .kvm, .x86_64); + try testing.expect(std.mem.startsWith(u8, spr.kvm, "SapphireRapids")); +} + +test "no target maps to the host CPU" { + var arena: std.heap.ArenaAllocator = .init(testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + for (&targets) |*t| { + const p = try plan(a, t, .kvm, t.arch); + switch (p) { + .kvm => |cpu| { + try testing.expect(!std.mem.startsWith(u8, cpu, "host")); + try testing.expect(std.mem.endsWith(u8, cpu, ",enforce")); + }, + else => {}, + } + try testing.expect(t.kvm == null or !std.mem.startsWith(u8, t.kvm.?, "host")); + } +} + +test "aarch64 targets run under emulation with a named model" { + var arena: std.heap.ArenaAllocator = .init(testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + try testing.expectEqualStrings("neoverse-n1", (try plan(a, testTarget("aarch64/neoverse_n1"), .tcg, .x86_64)).tcg); + try testing.expectEqualStrings("neoverse-v1", (try plan(a, testTarget("aarch64/neoverse_v1"), .tcg, .x86_64)).tcg); + try testing.expectEqualStrings("a64fx", (try plan(a, testTarget("aarch64/a64fx"), .tcg, .x86_64)).tcg); +} + +test "a mode refuses what it cannot present" { + var arena: std.heap.ArenaAllocator = .init(testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + // KVM on Arm offers the host CPU only; the other architecture is emulation. + try testing.expect((try plan(a, testTarget("aarch64/neoverse_n1"), .kvm, .x86_64)) == .refused); + try testing.expect((try plan(a, testTarget("aarch64/neoverse_n1"), .kvm, .aarch64)) == .refused); + try testing.expect((try plan(a, testTarget("x86_64/amd/zen4"), .kvm, .aarch64)) == .refused); + // TCG has no AVX-512 and the same architecture belongs to KVM. + try testing.expect((try plan(a, testTarget("x86_64/amd/zen4"), .tcg, .aarch64)) == .refused); + try testing.expect((try plan(a, testTarget("x86_64/amd/zen3"), .tcg, .x86_64)) == .refused); + try testing.expectEqualStrings("EPYC-Milan", (try plan(a, testTarget("x86_64/amd/zen3"), .tcg, .aarch64)).tcg); + // A Zen 5 guest needs a Zen 5 host. + try testing.expect((try plan(a, testTarget("x86_64/amd/zen5"), .kvm, .x86_64)) == .refused); +} + +test "the QEMU command line names the model with enforce, shares and the three serial ports" { + var arena: std.heap.ArenaAllocator = .init(testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const shares = [_]Share{ + .{ .tag = "hostroot", .host = "/" }, + .{ .tag = "job", .host = "/var/tmp/j", .readonly = false }, + }; + const argv = try qemuArgv(a, .{ + .qemu = "qemu-system-x86_64", + .cpu = "EPYC-Genoa,enforce", + .cpus = 4, + .memory_mib = 2048, + .kernel = "/boot/vmlinuz", + .rundir = "/var/tmp/j", + .shares = &shares, + }); + var cpu_at: ?usize = null; + for (argv, 0..) |x, i| { + try testing.expect(!std.mem.eql(u8, x, "host")); + if (std.mem.eql(u8, x, "-cpu")) cpu_at = i; + } + try testing.expectEqualStrings("EPYC-Genoa,enforce", argv[cpu_at.? + 1]); + var serial: usize = 0; + var vfs: usize = 0; + for (argv) |x| { + if (std.mem.eql(u8, x, "-serial")) serial += 1; + if (std.mem.startsWith(u8, x, "vhost-user-fs-pci,")) vfs += 1; + } + try testing.expectEqual(@as(usize, 3), serial); + try testing.expectEqual(@as(usize, 2), vfs); + try testing.expect(std.mem.indexOf(u8, argv[argv.len - 1], "root=hostroot ro init=/var/tmp/j/init") != null); + try testing.expectEqualStrings("kvm", argv[1]); + try testing.expectEqualStrings("-m", argv[cpu_at.? + 3]); + try testing.expectEqualStrings("2048M", argv[cpu_at.? + 4]); +} + +test "virtiofsd shares the host read-only without a sandbox" { + var arena: std.heap.ArenaAllocator = .init(testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const ro = try virtiofsdArgv(a, "/bin/virtiofsd", "/var/tmp/j", .{ .tag = "hostroot", .host = "/" }); + try testing.expectEqualStrings("--socket-path=/var/tmp/j/hostroot.sock", ro[1]); + try testing.expectEqualStrings("--shared-dir=/", ro[2]); + try testing.expectEqualStrings("--sandbox=none", ro[3]); + try testing.expectEqualStrings("--readonly", ro[4]); + const rw = try virtiofsdArgv(a, "/bin/virtiofsd", "/var/tmp/j", .{ .tag = "rw0", .host = "/home/u", .guest = "/home/u", .readonly = false, .cache = "auto" }); + for (rw) |x| try testing.expect(!std.mem.eql(u8, x, "--readonly")); + try testing.expectEqualStrings("--cache=auto", rw[4]); +} + +test "mounts list the tmpfs under /cvmfs first, then each guest path" { + var arena: std.heap.ArenaAllocator = .init(testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const shares = [_]Share{ + .{ .tag = "hostroot", .host = "/" }, + .{ .tag = "cvmfs0", .host = "/cvmfs/software.eessi.io", .guest = "/cvmfs/software.eessi.io" }, + .{ .tag = "rw0", .host = "/home/u", .guest = "/home/u", .readonly = false }, + }; + const text = try mountsFile(a, &shares, true); + try testing.expectEqualStrings("tmpfs cvmfs /cvmfs\nvirtiofs cvmfs0 /cvmfs/software.eessi.io ro\nvirtiofs rw0 /home/u rw\n", text); +} + +test "paths inside another share are dropped" { + var arena: std.heap.ArenaAllocator = .init(testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const kept = try dedupePaths(a, &.{ "/home/u/work", "/home/u", "/var/lib/builds/x", "/home/u", "/home/uu" }); + try testing.expectEqual(@as(usize, 3), kept.len); + try testing.expectEqualStrings("/home/u", kept[0]); + try testing.expectEqualStrings("/home/uu", kept[1]); + try testing.expectEqualStrings("/var/lib/builds/x", kept[2]); +} + +test "arguments: the stable command line and the optional extras" { + var arena: std.heap.ArenaAllocator = .init(testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const ok = try parseArgs(a, &.{ "--mode", "kvm", "--cpu-target", "x86_64/amd/zen4", "--memory", "4096", "--cpus=2", "--", "eb-local", "--flag", "x" }); + try testing.expectEqual(Mode.kvm, ok.ok.mode); + try testing.expectEqualStrings("x86_64/amd/zen4", ok.ok.target); + try testing.expectEqual(@as(u32, 4096), ok.ok.memory_mib); + try testing.expectEqual(@as(?u32, 2), ok.ok.cpus); + try testing.expectEqual(@as(usize, 3), ok.ok.command.len); + try testing.expectEqualStrings("--flag", ok.ok.command[1]); + const share = try parseArgs(a, &.{ "--mode=tcg", "--cpu-target=aarch64/neoverse_n1", "--share", "/a", "--share-ro=/b", "--allow-archspec-mismatch", "--", "true" }); + try testing.expectEqual(Mode.tcg, share.ok.mode); + try testing.expectEqualStrings("/a", share.ok.share[0]); + try testing.expectEqualStrings("/b", share.ok.share_ro[0]); + try testing.expect(share.ok.allow_archspec_mismatch); +} + +test "arguments: each missing or wrong piece is named" { + var arena: std.heap.ArenaAllocator = .init(testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const cases = [_]struct { args: []const []const u8, text: []const u8 }{ + .{ .args = &.{ "--cpu-target", "x", "--", "true" }, .text = "--mode" }, + .{ .args = &.{ "--mode", "kvm", "--", "true" }, .text = "--cpu-target" }, + .{ .args = &.{ "--mode", "kvm", "--cpu-target", "x" }, .text = "COMMAND" }, + .{ .args = &.{ "--mode", "kvm", "--cpu-target", "x", "--" }, .text = "COMMAND" }, + .{ .args = &.{ "--mode", "vm", "--cpu-target", "x", "--", "true" }, .text = "kvm or tcg" }, + .{ .args = &.{ "--mode", "kvm", "--cpu-target", "x", "--memory", "lots", "--", "true" }, .text = "MiB" }, + .{ .args = &.{ "--mode", "kvm", "--cpu-target", "x", "--cpus", "0", "--", "true" }, .text = "--cpus" }, + .{ .args = &.{ "--mode", "kvm", "--cpu-target", "x", "--bogus", "--", "true" }, .text = "--bogus" }, + }; + for (cases) |c| { + const p = try parseArgs(a, c.args); + try testing.expect(p == .bad); + try testing.expect(std.mem.indexOf(u8, p.bad, c.text) != null); + } +} + +test "exit status: the command's own, 126 for a refusal, 125 for no report" { + try testing.expectEqual(@as(u8, 0), exitStatus(.{ .status = "0\n" })); + try testing.expectEqual(@as(u8, 7), exitStatus(.{ .status = "7\n" })); + try testing.expectEqual(@as(u8, 137), exitStatus(.{ .status = "137" })); + try testing.expectEqual(status_unverified, exitStatus(.{ .refused = "archspec reads x86_64_v4", .status = "0" })); + try testing.expectEqual(status_failed, exitStatus(.{})); + try testing.expectEqual(status_failed, exitStatus(.{ .status = "banana" })); + try testing.expectEqual(status_failed, exitStatus(.{ .status = "300" })); + try testing.expectEqual(@as(u8, 3), termStatus(3 << 8)); + try testing.expectEqual(@as(u8, 137), termStatus(9)); +} + +test "the job script quotes every word and checks the CPU before the command" { + var arena: std.heap.ArenaAllocator = .init(testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const script = try jobScript(a, .{ + .dir = "/run/ebvm", + .cwd = "/home/u/it's", + .t = testTarget("x86_64/amd/zen4"), + .eessi_version = "2025.06", + .allow_archspec_mismatch = false, + .env = &.{.{ "FOO", "a b$c" }}, + .command = &.{ "eb", "--robot", "a;b" }, + }); + try testing.expect(std.mem.indexOf(u8, script, "export FOO='a b$c'\n") != null); + try testing.expect(std.mem.indexOf(u8, script, "export EBVM_VENDOR='AuthenticAMD'\n") != null); + try testing.expect(std.mem.indexOf(u8, script, "export EBVM_GCC='znver4'\n") != null); + try testing.expect(std.mem.indexOf(u8, script, "cd '/home/u/it'\\''s'") != null); + const verify = std.mem.indexOf(u8, script, "verify.sh").?; + const exec = std.mem.indexOf(u8, script, "exec 'eb' '--robot' 'a;b'\n").?; + try testing.expect(verify < exec); +} + +test "only the named variables reach the guest" { + try testing.expect(envForwarded("PATH")); + try testing.expect(envForwarded("EASYBUILD_PREFIX")); + try testing.expect(envForwarded("EESSI_USER_INSTALL")); + try testing.expect(envForwarded("LC_ALL")); + try testing.expect(!envForwarded("SSH_AUTH_SOCK")); + try testing.expect(!envForwarded("DISPLAY")); + try testing.expect(!envForwarded("EB_LOCAL_VM_KERNEL")); +} + +test "the guest scripts check every detector and refuse" { + try testing.expect(std.mem.indexOf(u8, verify_script, "/dev/fd/0") != null); + try testing.expect(std.mem.indexOf(u8, verify_script, "eessi_archdetect.sh") != null); + try testing.expect(std.mem.indexOf(u8, verify_script, "archspec.cpu") != null); + try testing.expect(std.mem.indexOf(u8, verify_script, "-march=native") != null); + try testing.expect(std.mem.indexOf(u8, verify_script, "-mcpu=native") != null); + try testing.expect(std.mem.indexOf(u8, verify_script, "vendor_id") != null); + try testing.expect(std.mem.indexOf(u8, guest_init, "/dev/fd") != null); +} diff --git a/src/vm/guest-init.sh b/src/vm/guest-init.sh new file mode 100755 index 0000000..c6e884e --- /dev/null +++ b/src/vm/guest-init.sh @@ -0,0 +1,40 @@ +#!/bin/bash +# PID 1 of an `eb-local __vm-run --mode kvm` guest. The root file system is the +# host's own, read-only over virtiofs; /tmp and /run are tmpfs, and every other +# writable path is a virtiofs share named in the job directory's `mounts` file. +export PATH=/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin +mount -t proc proc /proc +mount -t sysfs sys /sys +mount -t devtmpfs dev /dev +# udev would create these; without /dev/fd EESSI's archdetect falls back to generic. +ln -sfn /proc/self/fd /dev/fd +ln -sfn /proc/self/fd/0 /dev/stdin +ln -sfn /proc/self/fd/1 /dev/stdout +ln -sfn /proc/self/fd/2 /dev/stderr +mkdir -p /dev/pts /dev/shm +mount -t devpts devpts /dev/pts +mount -t tmpfs shm /dev/shm +mount -t tmpfs tmp /tmp +mount -t tmpfs run /run +mkdir -p /run/ebvm +mount -t virtiofs job /run/ebvm || { echo o > /proc/sysrq-trigger; sleep 30; } +ip link set lo up 2>/dev/null +# ttyS1 and ttyS2 carry the command's stdout and stderr; raw keeps newlines unchanged. +stty -F /dev/ttyS1 raw -echo 2>/dev/null +stty -F /dev/ttyS2 raw -echo 2>/dev/null +while read -r kind a b c; do + case $kind in + tmpfs) mount -t tmpfs "$a" "$b" ;; + virtiofs) + mkdir -p "$b" 2>/dev/null + mount -t virtiofs -o "$c" "$a" "$b" || echo "mount of share $a on $b failed" >> /run/ebvm/init.log ;; + esac +done < /run/ebvm/mounts +. /run/ebvm/ids +if [ -n "$EBVM_GROUPS" ]; then groups="--groups=$EBVM_GROUPS"; else groups=--clear-groups; fi +setpriv --reuid="$EBVM_UID" --regid="$EBVM_GID" "$groups" \ + bash /run/ebvm/job.sh < /dev/null > /dev/ttyS1 2> /dev/ttyS2 +echo $? > /run/ebvm/status +sync +echo o > /proc/sysrq-trigger +sleep 30 diff --git a/src/vm/tcg-ns.sh b/src/vm/tcg-ns.sh new file mode 100755 index 0000000..727afaa --- /dev/null +++ b/src/vm/tcg-ns.sh @@ -0,0 +1,14 @@ +#!/bin/bash +# First stage of `eb-local __vm-run --mode tcg` when the host has no +# binfmt_misc entry for the emulator: runs in a user and mount namespace of +# its own, registers the emulator there, then runs the job under the caller's +# own uid in a nested user namespace. Needs EBVM_ARCH, EBVM_QEMU_USER, +# EBVM_QEMU_CPU, EBVM_UID, EBVM_GID, EBVM_JOB and EBVM_PATH. +set -u +mount -t binfmt_misc none /proc/sys/fs/binfmt_misc || { echo "eb-local: vm-run: cannot mount binfmt_misc in a user namespace" >&2; exit 125; } +case $EBVM_ARCH in + aarch64) entry=':qemu-aarch64:M::\x7fELF\x02\x01\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00\xb7\x00:\xff\xff\xff\xff\xff\xff\xff\x00\xff\xff\xff\xff\xff\xff\xff\xff\xfe\xff\xff\xff:' ;; + x86_64) entry=':qemu-x86_64:M::\x7fELF\x02\x01\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00\x3e\x00:\xff\xff\xff\xff\xff\xfe\xfe\x00\xff\xff\xff\xff\xff\xff\xff\xff\xfe\xff\xff\xff:' ;; +esac +printf '%s\n' "${entry}${EBVM_QEMU_USER}:OCF" > /proc/sys/fs/binfmt_misc/register || { echo "eb-local: vm-run: cannot register $EBVM_QEMU_USER" >&2; exit 125; } +exec unshare -U --map-user="$EBVM_UID" --map-group="$EBVM_GID" env QEMU_CPU="$EBVM_QEMU_CPU" PATH="$EBVM_PATH" bash "$EBVM_JOB" diff --git a/src/vm/verify.sh b/src/vm/verify.sh new file mode 100755 index 0000000..491fdc9 --- /dev/null +++ b/src/vm/verify.sh @@ -0,0 +1,54 @@ +#!/bin/bash +# Runs inside the guest before COMMAND. Exits 1, with the reason in +# $EBVM_DIR/refused, unless every detector names the target: +# EBVM_ARCH EBVM_TARGET EBVM_VENDOR EBVM_ARCHSPEC EBVM_GCC (alternatives) +# EBVM_EESSI_VERSION EBVM_ALLOW_ARCHSPEC EBVM_GCC_BIN +set +u +refuse() { + printf '%s\n' "$*" > "$EBVM_DIR/refused" + echo "eb-local: vm-run: refused: $*" >&2 + exit 1 +} +[ -e /dev/fd/0 ] || refuse "/dev/fd is missing, so EESSI archdetect would fall back to generic" +case $EBVM_ARCH in + x86_64) vendor=$(sed -n 's/^vendor_id[[:space:]]*:[[:space:]]*//p' /proc/cpuinfo | head -n 1) ;; + aarch64) vendor=$(sed -n 's/^CPU implementer[[:space:]]*:[[:space:]]*//p' /proc/cpuinfo | head -n 1) ;; +esac +[ "$vendor" = "$EBVM_VENDOR" ] || refuse "the CPU vendor reads '$vendor', $EBVM_TARGET needs '$EBVM_VENDOR'" +unset EESSI_SOFTWARE_SUBDIR_OVERRIDE EESSI_SOFTWARE_SUBDIR EESSI_PREFIX EESSI_VERSION_OVERRIDE +init=/cvmfs/software.eessi.io/versions/$EBVM_EESSI_VERSION/init/bash +[ -r "$init" ] || refuse "EESSI $EBVM_EESSI_VERSION is not readable at $init" +source "$init" > /dev/null 2>&1 +[ -n "$EESSI_SOFTWARE_SUBDIR" ] || refuse "EESSI $EBVM_EESSI_VERSION did not load" +archdetect=$("$EESSI_PREFIX/init/eessi_archdetect.sh" cpupath 2> /dev/null | head -n 1 | cut -d: -f1) +[ "$archdetect" = "$EBVM_TARGET" ] || refuse "EESSI archdetect names '$archdetect', not $EBVM_TARGET" +[ "$EESSI_SOFTWARE_SUBDIR" = "$EBVM_TARGET" ] || refuse "EESSI selected '$EESSI_SOFTWARE_SUBDIR', not $EBVM_TARGET" +if [ -z "$EBVM_GCC_BIN" ]; then + module load GCCcore > /dev/null 2>&1 + EBVM_GCC_BIN=gcc +fi +tmp=$(mktemp -d) || refuse "no temporary directory for the compiler probe" +case $EBVM_ARCH in + x86_64) + march=$("$EBVM_GCC_BIN" -march=native -Q --help=target 2> /dev/null | sed -n 's/^[[:space:]]*-march=[[:space:]]*//p' | head -n 1) ;; + aarch64) + echo 'int main(void){return 0;}' > "$tmp/x.c" + march=$("$EBVM_GCC_BIN" -mcpu=native -### -c "$tmp/x.c" -o "$tmp/x.o" 2>&1 | grep -o -E -- "-mcpu=[^ \"']+" | head -n 1 | sed -e 's/^-mcpu=//' -e 's/+.*//') ;; +esac +rm -rf "$tmp" +gcc_ok= +for want in $EBVM_GCC; do [ "$march" = "$want" ] && gcc_ok=1; done +[ -n "$gcc_ok" ] || refuse "gcc native reads '$march' ($(command -v "$EBVM_GCC_BIN")), $EBVM_TARGET needs one of: $EBVM_GCC" +module load EasyBuild > /dev/null 2>&1 +spec=$(python3 -c 'import archspec.cpu as c; print(c.host().name)' 2> /dev/null) +[ -n "$spec" ] || refuse "archspec is not importable after loading EasyBuild" +if [ "$spec" != "$EBVM_ARCHSPEC" ]; then + if [ "$EBVM_ALLOW_ARCHSPEC" = 1 ]; then + echo "eb-local: vm-run: warning: archspec reads '$spec', $EBVM_TARGET needs '$EBVM_ARCHSPEC'; accepted by --allow-archspec-mismatch" >&2 + else + refuse "archspec reads '$spec', $EBVM_TARGET needs '$EBVM_ARCHSPEC'" + fi +fi +msg="vendor=$vendor archdetect=$archdetect archspec=$spec gcc=$march" +echo "$msg" > "$EBVM_DIR/verified" +echo "eb-local: vm-run: $EBVM_TARGET presented: $msg" >&2 From 81b735320aea1e7c8852b8ffa9aea227df677d0a Mon Sep 17 00:00:00 2001 From: Rohit Goswami Date: Fri, 27 Nov 2026 00:44:17 +0100 Subject: [PATCH 02/17] fix: __vm-run checks the EESSI version eb-local itself defaults to --- src/vm.zig | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/vm.zig b/src/vm.zig index efcf99c..8ffe14d 100644 --- a/src/vm.zig +++ b/src/vm.zig @@ -576,8 +576,8 @@ pub fn run(a: Allocator, env: *const std.process.Environ.Map, cwd: []const u8, a } fn eessiVersion(env: *const std.process.Environ.Map) []const u8 { - if (env.get("EB_LOCAL_VM_EESSI_VERSION")) |v| if (v.len > 0) return v; - return "2025.06"; + if (env.get("EESSI_VERSION")) |v| if (v.len > 0) return v; + return "2026.06"; } /// A directory for the job: `EB_LOCAL_VM_DIR`, TMPDIR, /var/tmp or /tmp. From 9d8b3ecd81b247b4f97952a7dd8ac955e48a8ef4 Mon Sep 17 00:00:00 2001 From: Rohit Goswami Date: Fri, 27 Nov 2026 00:45:01 +0100 Subject: [PATCH 03/17] test: __vm-run refusals everywhere, VM runs behind EB_LOCAL_VM_TESTS=1 --- src/vm.zig | 6 ++- tests/test_vm_run.py | 117 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 122 insertions(+), 1 deletion(-) create mode 100644 tests/test_vm_run.py diff --git a/src/vm.zig b/src/vm.zig index 8ffe14d..4d36176 100644 --- a/src/vm.zig +++ b/src/vm.zig @@ -465,7 +465,11 @@ fn cpuCount() u32 { } fn kernelPath(a: Allocator, env: *const std.process.Environ.Map) ?[]const u8 { - if (env.get("EB_LOCAL_VM_KERNEL")) |k| if (k.len > 0) return k; + if (env.get("EB_LOCAL_VM_KERNEL")) |k| if (k.len > 0) { + const fd = sys.openat(fsx.cwd, k, .{}, 0) catch return null; + sys.close(fd); + return k; + }; var uts: linux.utsname = undefined; if (linux.errno(linux.uname(&uts)) != .SUCCESS) return null; const rel = std.mem.sliceTo(&uts.release, 0); diff --git a/tests/test_vm_run.py b/tests/test_vm_run.py new file mode 100644 index 0000000..0ac3d26 --- /dev/null +++ b/tests/test_vm_run.py @@ -0,0 +1,117 @@ +#!/usr/bin/env python3 +"""The internal helper `eb-local __vm-run`. + +The refusals need no VM and run everywhere. The runs boot a KVM guest or an +emulated user space, which GitHub-hosted runners do not offer in general, so +they run only with EB_LOCAL_VM_TESTS=1, on a host with /dev/kvm, QEMU, +virtiofsd and EESSI (EB_LOCAL_QEMU_DIR and EB_LOCAL_VIRTIOFSD name the +tools when they are not on PATH). +""" +import os +import platform +import subprocess +import time +import unittest + +import binary + +HOST = "aarch64" if platform.machine() in ("aarch64", "arm64") else "x86_64" +RUN_VMS = os.environ.get("EB_LOCAL_VM_TESTS") == "1" + + +def vm_run(*args, env=None): + full = dict(os.environ, **(env or {})) + return subprocess.run([binary.ZIG, "__vm-run", *args], capture_output=True, text=True, env=full) + + +@unittest.skipUnless(binary.ZIG, "the helper is a feature of the Zig build") +class Refusals(unittest.TestCase): + def test_a_missing_option_is_named_and_exits_2(self): + for args, word in [ + ([], "--mode"), + (["--mode", "kvm", "--", "true"], "--cpu-target"), + (["--mode", "kvm", "--cpu-target", "x86_64/amd/zen4"], "COMMAND"), + (["--mode", "vm", "--cpu-target", "x86_64/amd/zen4", "--", "true"], "kvm or tcg"), + (["--mode", "kvm", "--cpu-target", "x86_64/amd/zen4", "--bogus", "--", "true"], "--bogus"), + ]: + run = vm_run(*args) + self.assertEqual(run.returncode, 2, (args, run.stderr)) + self.assertIn(word, run.stderr) + self.assertTrue(run.stderr.startswith("eb-local: vm-run: "), run.stderr) + + def test_an_unknown_target_lists_the_known_ones(self): + run = vm_run("--mode", "kvm", "--cpu-target", "x86_64/amd/zen9", "--", "true") + self.assertEqual(run.returncode, 2) + self.assertIn("x86_64/amd/zen4", run.stderr) + + def test_a_target_the_mode_cannot_present_is_refused_with_the_reason(self): + other = "aarch64/neoverse_n1" if HOST == "x86_64" else "x86_64/amd/zen3" + same = "x86_64/amd/zen4" if HOST == "x86_64" else "aarch64/neoverse_n1" + run = vm_run("--mode", "kvm", "--cpu-target", other, "--", "true") + self.assertEqual(run.returncode, 2, run.stderr) + run = vm_run("--mode", "tcg", "--cpu-target", same, "--", "true") + self.assertEqual(run.returncode, 2, run.stderr) + self.assertIn("another architecture", run.stderr) + run = vm_run("--mode", "kvm", "--cpu-target", "x86_64/amd/zen5", "--", "true") + self.assertEqual(run.returncode, 2, run.stderr) + + def test_a_host_without_the_tools_refuses_and_does_not_start_a_vm(self): + target = "x86_64/amd/zen4" if HOST == "x86_64" else "aarch64/neoverse_n1" + mode = "kvm" if HOST == "x86_64" else "tcg" + run = vm_run("--mode", mode, "--cpu-target", target, "--", + "true", env={"PATH": "/nonexistent", "EB_LOCAL_QEMU_DIR": "/nonexistent", + "EB_LOCAL_VIRTIOFSD": "/nonexistent/virtiofsd", + "EB_LOCAL_VM_KERNEL": "/nonexistent/vmlinuz"}) + if mode == "kvm": + self.assertEqual(run.returncode, 2, run.stderr) + self.assertNotEqual(run.returncode, 0) + + +@unittest.skipUnless(binary.ZIG and RUN_VMS, "set EB_LOCAL_VM_TESTS=1 on a host with KVM, QEMU, virtiofsd and EESSI") +class Runs(unittest.TestCase): + def timed(self, *args, **kw): + start = time.monotonic() + run = vm_run(*args, **kw) + print(f"\n{' '.join(args[:4])}: {time.monotonic() - start:.1f} s, status {run.returncode}") + return run + + @unittest.skipUnless(HOST == "x86_64", "KVM targets are of the host architecture") + def test_kvm_zen4_reports_znver4_and_passes_the_status_through(self): + run = self.timed("--mode", "kvm", "--cpu-target", "x86_64/amd/zen4", "--", + "bash", "-c", "gcc -march=native -Q --help=target | grep -- '-march='; exit 7") + self.assertEqual(run.returncode, 7, run.stderr) + self.assertIn("znver4", run.stdout) + self.assertIn("archdetect=x86_64/amd/zen4", run.stderr) + self.assertIn("archspec=zen4", run.stderr) + + @unittest.skipUnless(HOST == "x86_64", "KVM targets are of the host architecture") + def test_kvm_icelake_reports_an_intel_part(self): + run = self.timed("--mode", "kvm", "--cpu-target", "x86_64/intel/icelake", "--", + "bash", "-c", "gcc -march=native -Q --help=target | grep -- '-march='; grep -m1 vendor_id /proc/cpuinfo") + self.assertEqual(run.returncode, 0, run.stderr) + self.assertIn("icelake-server", run.stdout) + self.assertIn("GenuineIntel", run.stdout) + self.assertIn("archspec=icelake", run.stderr) + + @unittest.skipUnless(HOST == "x86_64", "KVM targets are of the host architecture") + def test_a_cpu_view_that_does_not_name_the_target_is_refused_before_the_command(self): + marker = f"/tmp/eb-local-vm-test-{os.getpid()}" + run = self.timed("--mode", "kvm", "--cpu-target", "x86_64/amd/zen4", "--", + "bash", "-c", f"touch {marker}", env={"EB_LOCAL_VM_GCC": "/nonexistent/gcc"}) + self.assertEqual(run.returncode, 126, run.stderr) + self.assertIn("refused", run.stderr) + self.assertFalse(os.path.exists(marker)) + + @unittest.skipUnless(HOST == "x86_64", "the aarch64 emulation runs on an x86_64 host here") + def test_tcg_neoverse_n1_runs_the_eessi_aarch64_stack(self): + run = self.timed("--mode", "tcg", "--cpu-target", "aarch64/neoverse_n1", + "--allow-archspec-mismatch", "--", + "bash", "-c", "uname -m; echo 'int main(void){return 0;}' > /tmp/x.c; gcc -mcpu=native -### -c /tmp/x.c 2>&1 | grep -o -- '-mcpu=[^ ]*'") + self.assertEqual(run.returncode, 0, run.stderr) + self.assertIn("aarch64", run.stdout) + self.assertIn("neoverse-n1", run.stdout) + self.assertIn("archdetect=aarch64/neoverse_n1", run.stderr) + + +if __name__ == "__main__": + unittest.main() From 9ae9110f9662365dbf60617f57f4b5c0d76bfc94 Mon Sep 17 00:00:00 2001 From: Rohit Goswami Date: Fri, 27 Nov 2026 00:46:51 +0100 Subject: [PATCH 04/17] fix: copy NUL-terminated strings with dupeSentinel in __vm-run --- src/vm.zig | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/vm.zig b/src/vm.zig index 4d36176..f25a1e6 100644 --- a/src/vm.zig +++ b/src/vm.zig @@ -437,7 +437,7 @@ fn isDir(path: []const u8) bool { } fn executable(a: Allocator, path: []const u8) bool { - const z = a.dupeZ(u8, path) catch return false; + const z = a.dupeSentinel(u8, path, 0) catch return false; return linux.errno(linux.access(z.ptr, 1)) == .SUCCESS; } @@ -490,7 +490,7 @@ const Spawned = struct { pid: linux.pid_t }; fn spawn(a: Allocator, argv: []const []const u8, envp: proc.Envp) !Spawned { const zargv = try a.allocSentinel(?[*:0]const u8, argv.len, null); - for (argv, 0..) |x, i| zargv[i] = (try a.dupeZ(u8, x)).ptr; + for (argv, 0..) |x, i| zargv[i] = (try a.dupeSentinel(u8, x, 0)).ptr; const rc = linux.fork(); switch (linux.errno(rc)) { .SUCCESS => {}, @@ -641,7 +641,7 @@ fn runKvm(a: Allocator, env: *const std.process.Environ.Map, cwd: []const u8, re err("no readable host kernel image: set EB_LOCAL_VM_KERNEL (it needs virtiofs and virtio-pci built in)", .{}); return status_refused; }; - const kvm_z = a.dupeZ(u8, "/dev/kvm") catch return status_failed; + const kvm_z = a.dupeSentinel(u8, "/dev/kvm", 0) catch return status_failed; if (linux.errno(linux.access(kvm_z.ptr, 6)) != .SUCCESS) { err("/dev/kvm is not readable and writable here; --mode kvm needs KVM", .{}); return status_refused; From e2ccef5267d7c22e14bf17a9fee0dfe873552273 Mon Sep 17 00:00:00 2001 From: Rohit Goswami Date: Fri, 27 Nov 2026 00:50:54 +0100 Subject: [PATCH 05/17] fix: __vm-run states a refusal once and names the compiler it asked --- src/vm.zig | 6 +----- src/vm/verify.sh | 2 +- 2 files changed, 2 insertions(+), 6 deletions(-) diff --git a/src/vm.zig b/src/vm.zig index f25a1e6..50462ef 100644 --- a/src/vm.zig +++ b/src/vm.zig @@ -779,7 +779,6 @@ fn runKvm(a: Allocator, env: *const std.process.Environ.Map, cwd: []const u8, re if (qemuRefusedModel(raw)) err("QEMU refused the CPU model {s}: this host lacks a feature it needs (enforce is on, and the helper never falls back to the host CPU)", .{cpu}); return status_failed; } - if (outcome.refused) |m| err("not run: {s}", .{std.mem.trim(u8, m, "\n")}); if (std.mem.eql(u8, env.get("EB_LOCAL_VM_KEEP") orelse "", "1")) { err("job directory kept: {s}", .{rundir}); } else fsx.deleteTree(a, fsx.cwd, rundir) catch {}; @@ -879,10 +878,7 @@ fn runTcg(a: Allocator, env: *const std.process.Environ.Map, cwd: []const u8, re const raw = waitFor(child.pid); const refused = readSmall(a, std.fs.path.join(a, &.{ rundir, "refused" }) catch return status_failed); var code = termStatus(raw); - if (refused != null) { - code = status_unverified; - err("not run: {s}", .{std.mem.trim(u8, refused.?, "\n")}); - } + if (refused != null) code = status_unverified; fsx.deleteTree(a, fsx.cwd, rundir) catch {}; return code; } diff --git a/src/vm/verify.sh b/src/vm/verify.sh index 491fdc9..9698edf 100755 --- a/src/vm/verify.sh +++ b/src/vm/verify.sh @@ -38,7 +38,7 @@ esac rm -rf "$tmp" gcc_ok= for want in $EBVM_GCC; do [ "$march" = "$want" ] && gcc_ok=1; done -[ -n "$gcc_ok" ] || refuse "gcc native reads '$march' ($(command -v "$EBVM_GCC_BIN")), $EBVM_TARGET needs one of: $EBVM_GCC" +[ -n "$gcc_ok" ] || refuse "gcc native reads '$march' (compiler: $(command -v "$EBVM_GCC_BIN" || echo none)), $EBVM_TARGET needs one of: $EBVM_GCC" module load EasyBuild > /dev/null 2>&1 spec=$(python3 -c 'import archspec.cpu as c; print(c.host().name)' 2> /dev/null) [ -n "$spec" ] || refuse "archspec is not importable after loading EasyBuild" From 2318bd8f65236889e22b423226bb269e1f37cf84 Mon Sep 17 00:00:00 2001 From: Rohit Goswami Date: Fri, 27 Nov 2026 00:50:54 +0100 Subject: [PATCH 06/17] docs: __vm-run reference, environment variables and the QEMU how-to --- changelog.d/+cpu-target-vm.feature.md | 1 + docs/howto/build-under-qemu.md | 105 ++++++++++++++++++++++++ docs/howto/index.md | 1 + docs/orgmode/howto/build-under-qemu.org | 103 +++++++++++++++++++++++ docs/orgmode/howto/index.org | 1 + docs/orgmode/reference/cli.org | 38 +++++++++ docs/orgmode/reference/environment.org | 3 + docs/reference/cli.md | 38 +++++++++ docs/reference/environment.md | 3 + 9 files changed, 293 insertions(+) create mode 100644 changelog.d/+cpu-target-vm.feature.md create mode 100644 docs/howto/build-under-qemu.md create mode 100644 docs/orgmode/howto/build-under-qemu.org diff --git a/changelog.d/+cpu-target-vm.feature.md b/changelog.d/+cpu-target-vm.feature.md new file mode 100644 index 0000000..6efd019 --- /dev/null +++ b/changelog.d/+cpu-target-vm.feature.md @@ -0,0 +1 @@ +The internal helper `eb-local __vm-run --mode kvm|tcg --cpu-target TARGET -- COMMAND` runs COMMAND inside a QEMU virtual CPU that presents an EESSI target, as the caller, in the caller's working directory, and refuses, before COMMAND starts, when EESSI archdetect, archspec, `gcc -march=native`, the CPU vendor or `/dev/fd` do not name the target. diff --git a/docs/howto/build-under-qemu.md b/docs/howto/build-under-qemu.md new file mode 100644 index 0000000..9fdf8ab --- /dev/null +++ b/docs/howto/build-under-qemu.md @@ -0,0 +1,105 @@ + + +# Build under a virtual CPU with QEMU + +A build that detects the CPU it runs on gets the host's view, so a Zen 5 node builds for Zen 5 whatever target you want. +`eb-local __vm-run` runs a command inside QEMU with a CPU that presents the target instead, and checks that every detector agrees before the command starts. +It is an internal helper: [the command reference](../reference/cli.md) lists its options and exit statuses, and the builds that mask the CPU view call it. +These steps run it by hand, to see what a target looks like or to debug a masked build. + +## Before you start + +For `--mode kvm`, a target of the host's architecture: + +- `/dev/kvm`, readable and writable by you. +- `qemu-system-x86_64` and `virtiofsd` on `PATH`, or in a directory that `EB_LOCAL_QEMU_DIR` names, with `EB_LOCAL_VIRTIOFSD` for a `virtiofsd` elsewhere. On a Nix host the directory is the `bin` of the QEMU store path. +- A host kernel that has virtiofs, virtio-pci and devtmpfs built in. The helper boots `/lib/modules/$(uname -r)/vmlinuz`, then `/boot/vmlinuz-$(uname -r)`; `EB_LOCAL_VM_KERNEL` names another image. +- `bash`, `setpriv` and `stty` from util-linux and coreutils on the host: the guest runs the host's own root file system, read-only. +- A temporary directory on the root file system: `EB_LOCAL_VM_DIR`, `TMPDIR`, `/var/tmp` or `/tmp`, the first that is. +- EESSI mounted at `/cvmfs/software.eessi.io`. + +For `--mode tcg`, a target of the other architecture: + +- `qemu-aarch64` (or `qemu-x86_64` on an aarch64 host), found as above. +- A kernel that lets you create user and mount namespaces, 6.7 or later, unless the host already has a `qemu-aarch64` entry in `binfmt_misc`. Without the entry, the helper registers the emulator in a namespace of its own, which needs no root. +- The EESSI compatibility layer of the target's architecture under `/cvmfs/software.eessi.io`. + +`EESSI_VERSION` names the EESSI version both modes check; it defaults to `2026.06`. + +## Run a command as a Zen 4 + +```bash +eb-local __vm-run --mode kvm --cpu-target x86_64/amd/zen4 -- \ + bash -c 'gcc -march=native -Q --help=target | grep -- -march=' +``` + +The guest boots in a few seconds, checks the CPU, and prints one line before the command output: + +```text +eb-local: vm-run: x86_64/amd/zen4 presented: vendor=AuthenticAMD archdetect=x86_64/amd/zen4 archspec=zen4 gcc=znver4 +``` + +The compiler then names `znver4` on a Zen 5 host. +The command runs in your working directory, as your user and group, and its exit status is the helper's. +Files it creates there belong to you. + +The guest mounts these writable: your working directory and the directories `HOME`, `TMPDIR`, `EASYBUILD_PREFIX`, `EASYBUILD_BUILDPATH`, `EASYBUILD_INSTALLPATH`, `EASYBUILD_SOURCEPATH`, `EASYBUILD_REPOSITORYPATH` and the `EESSI_*_INSTALL` variables name. +Everything else on the host root is read-only, and `/tmp` is memory. +`--share DIR` mounts another writable directory; `--share-ro DIR` mounts a read-only one that lies on a file system other than `/`, such as `/nix`. +`--memory` and `--cpus` size the guest. + +## Run a command as an Intel Ice Lake + +```bash +eb-local __vm-run --mode kvm --cpu-target x86_64/intel/icelake -- grep -m1 vendor_id /proc/cpuinfo +``` + +The vendor reads `GenuineIntel`; QEMU keeps the host's vendor unless the model sets it, and every detector goes wrong on an Intel model with an AMD vendor. + +## Run a command as a Neoverse N1 + +```bash +eb-local __vm-run --mode tcg --cpu-target aarch64/neoverse_n1 --allow-archspec-mismatch -- \ + bash -c 'uname -m; gcc -mcpu=native -### -c x.c 2>&1 | grep -o -- -mcpu=[^\ ]*' +``` + +The command runs on the EESSI aarch64 compatibility layer, whose directories come first in `PATH`, in qemu user mode with `QEMU_CPU=neoverse-n1`. +`uname -m` reads `aarch64`, and the compiler names `neoverse-n1`. +No guest kernel boots, and no memory or CPU count applies. + +QEMU's user mode writes its own `/proc/cpuinfo` for the program, with the CPU part of the model, which EESSI archdetect and GCC read correctly. +Its feature line lacks `evtstrm`, the one feature archspec 0.2.5 requires for `neoverse_n1` that the line leaves out, so archspec reads `aarch64` and the helper refuses without `--allow-archspec-mismatch`. +An easyblock that keys on archspec then sees a generic Arm CPU while the EESSI subdirectory and the compiler see `neoverse_n1`; pass the option only for a command that does not use archspec's answer. + +## What the helper refuses + +The guest checks, before the command, that: + +1. `/dev/fd` exists; without it EESSI archdetect fails on its process substitution and EESSI selects the generic target. +2. The CPU vendor (`vendor_id` or the Arm implementer) names the target's. +3. EESSI archdetect and the EESSI software subdirectory both name the target. +4. `gcc -march=native` (`-mcpu=native` on aarch64) names the target's compiler architecture. +5. archspec, from the EasyBuild module's Python, names the target. + +Any other reading exits 126, names the check on stderr, and does not start the command. +The helper also never uses the host CPU: `enforce` makes QEMU refuse a model the host cannot present, and the helper then exits 125 and says so, where a hand-run QEMU would fall back to `-cpu host` and report the host's target. + +| Situation | Status | Why | +|---|---|---| +| `x86_64/amd/zen5`, an Arm target under `kvm` | 2 | KVM offers no Zen 5 guest on another CPU, and on Arm only the host CPU. | +| An AVX-512 target under `tcg` | 2 | TCG has no AVX-512, so the guest would be a Zen 3 to every tool. | +| A target of the host's architecture under `tcg` | 2 | `kvm` presents it at native speed. | +| `x86_64/intel/sapphirerapids` on a host without AMX | 125 | `enforce` refuses the model: its instructions are real, and no guest can supply them. | + +## What it costs + +Wall times on a Ryzen 9 9950X (Zen 5) host under load, from the helper's start to its exit, EESSI 2026.06, 8 vCPUs, 8 GiB: + +| Target | Mode | Wall time | What ran | +|---|---|---|---| +| `x86_64/amd/zen4` | kvm | 9 to 15 s | boot, the five checks, `gcc -march=native` | +| `x86_64/intel/icelake` | kvm | 10 to 13 s | the same | +| `aarch64/neoverse_n1` | tcg | 16 to 21 s | the checks, `uname -m`, a one-line C compile and run under emulation | + +Most of the time goes to the checks, which load EESSI, GCC and EasyBuild modules. +A build is another matter: a guest on 4 KiB host pages and a virtiofs root costs a compile about 1.45 to 2.3 times its native time, and emulation costs 16 to 28 times. diff --git a/docs/howto/index.md b/docs/howto/index.md index 70787ce..b5ef30a 100644 --- a/docs/howto/index.md +++ b/docs/howto/index.md @@ -20,6 +20,7 @@ eb-without-a-site-file build-for-every-node-type build-against-a-site-gpu-module build-for-profiling +build-under-qemu install-what-eessi-lacks find-what-is-wrong refresh-the-module-cache diff --git a/docs/orgmode/howto/build-under-qemu.org b/docs/orgmode/howto/build-under-qemu.org new file mode 100644 index 0000000..f3724eb --- /dev/null +++ b/docs/orgmode/howto/build-under-qemu.org @@ -0,0 +1,103 @@ +#+title: Build under a virtual CPU with QEMU + +A build that detects the CPU it runs on gets the host's view, so a Zen 5 node builds for Zen 5 whatever target you want. +=eb-local __vm-run= runs a command inside QEMU with a CPU that presents the target instead, and checks that every detector agrees before the command starts. +It is an internal helper: [[file:../reference/cli.org][the command reference]] lists its options and exit statuses, and the builds that mask the CPU view call it. +These steps run it by hand, to see what a target looks like or to debug a masked build. + +* Before you start + +For =--mode kvm=, a target of the host's architecture: + +- =/dev/kvm=, readable and writable by you. +- =qemu-system-x86_64= and =virtiofsd= on =PATH=, or in a directory that =EB_LOCAL_QEMU_DIR= names, with =EB_LOCAL_VIRTIOFSD= for a =virtiofsd= elsewhere. On a Nix host the directory is the =bin= of the QEMU store path. +- A host kernel that has virtiofs, virtio-pci and devtmpfs built in. The helper boots =/lib/modules/$(uname -r)/vmlinuz=, then =/boot/vmlinuz-$(uname -r)=; =EB_LOCAL_VM_KERNEL= names another image. +- =bash=, =setpriv= and =stty= from util-linux and coreutils on the host: the guest runs the host's own root file system, read-only. +- A temporary directory on the root file system: =EB_LOCAL_VM_DIR=, =TMPDIR=, =/var/tmp= or =/tmp=, the first that is. +- EESSI mounted at =/cvmfs/software.eessi.io=. + +For =--mode tcg=, a target of the other architecture: + +- =qemu-aarch64= (or =qemu-x86_64= on an aarch64 host), found as above. +- A kernel that lets you create user and mount namespaces, 6.7 or later, unless the host already has a =qemu-aarch64= entry in =binfmt_misc=. Without the entry, the helper registers the emulator in a namespace of its own, which needs no root. +- The EESSI compatibility layer of the target's architecture under =/cvmfs/software.eessi.io=. + +=EESSI_VERSION= names the EESSI version both modes check; it defaults to =2026.06=. + +* Run a command as a Zen 4 + +#+begin_src bash +eb-local __vm-run --mode kvm --cpu-target x86_64/amd/zen4 -- \ + bash -c 'gcc -march=native -Q --help=target | grep -- -march=' +#+end_src + +The guest boots in a few seconds, checks the CPU, and prints one line before the command output: + +#+begin_example +eb-local: vm-run: x86_64/amd/zen4 presented: vendor=AuthenticAMD archdetect=x86_64/amd/zen4 archspec=zen4 gcc=znver4 +#+end_example + +The compiler then names =znver4= on a Zen 5 host. +The command runs in your working directory, as your user and group, and its exit status is the helper's. +Files it creates there belong to you. + +The guest mounts these writable: your working directory and the directories =HOME=, =TMPDIR=, =EASYBUILD_PREFIX=, =EASYBUILD_BUILDPATH=, =EASYBUILD_INSTALLPATH=, =EASYBUILD_SOURCEPATH=, =EASYBUILD_REPOSITORYPATH= and the =EESSI_*_INSTALL= variables name. +Everything else on the host root is read-only, and =/tmp= is memory. +=--share DIR= mounts another writable directory; =--share-ro DIR= mounts a read-only one that lies on a file system other than =/=, such as =/nix=. +=--memory= and =--cpus= size the guest. + +* Run a command as an Intel Ice Lake + +#+begin_src bash +eb-local __vm-run --mode kvm --cpu-target x86_64/intel/icelake -- grep -m1 vendor_id /proc/cpuinfo +#+end_src + +The vendor reads =GenuineIntel=; QEMU keeps the host's vendor unless the model sets it, and every detector goes wrong on an Intel model with an AMD vendor. + +* Run a command as a Neoverse N1 + +#+begin_src bash +eb-local __vm-run --mode tcg --cpu-target aarch64/neoverse_n1 --allow-archspec-mismatch -- \ + bash -c 'uname -m; gcc -mcpu=native -### -c x.c 2>&1 | grep -o -- -mcpu=[^\ ]*' +#+end_src + +The command runs on the EESSI aarch64 compatibility layer, whose directories come first in =PATH=, in qemu user mode with =QEMU_CPU=neoverse-n1=. +=uname -m= reads =aarch64=, and the compiler names =neoverse-n1=. +No guest kernel boots, and no memory or CPU count applies. + +QEMU's user mode writes its own =/proc/cpuinfo= for the program, with the CPU part of the model, which EESSI archdetect and GCC read correctly. +Its feature line lacks =evtstrm=, the one feature archspec 0.2.5 requires for =neoverse_n1= that the line leaves out, so archspec reads =aarch64= and the helper refuses without =--allow-archspec-mismatch=. +An easyblock that keys on archspec then sees a generic Arm CPU while the EESSI subdirectory and the compiler see =neoverse_n1=; pass the option only for a command that does not use archspec's answer. + +* What the helper refuses + +The guest checks, before the command, that: + +1. =/dev/fd= exists; without it EESSI archdetect fails on its process substitution and EESSI selects the generic target. +2. The CPU vendor (=vendor_id= or the Arm implementer) names the target's. +3. EESSI archdetect and the EESSI software subdirectory both name the target. +4. =gcc -march=native= (=-mcpu=native= on aarch64) names the target's compiler architecture. +5. archspec, from the EasyBuild module's Python, names the target. + +Any other reading exits 126, names the check on stderr, and does not start the command. +The helper also never uses the host CPU: =enforce= makes QEMU refuse a model the host cannot present, and the helper then exits 125 and says so, where a hand-run QEMU would fall back to =-cpu host= and report the host's target. + +| Situation | Status | Why | +|--------------------------------------------+--------+--------------------------------------------------------------------------------| +| =x86_64/amd/zen5=, an Arm target under =kvm= | 2 | KVM offers no Zen 5 guest on another CPU, and on Arm only the host CPU. | +| An AVX-512 target under =tcg= | 2 | TCG has no AVX-512, so the guest would be a Zen 3 to every tool. | +| A target of the host's architecture under =tcg= | 2 | =kvm= presents it at native speed. | +| =x86_64/intel/sapphirerapids= on a host without AMX | 125 | =enforce= refuses the model: its instructions are real, and no guest can supply them. | + +* What it costs + +Wall times on a Ryzen 9 9950X (Zen 5) host under load, from the helper's start to its exit, EESSI 2026.06, 8 vCPUs, 8 GiB: + +| Target | Mode | Wall time | What ran | +|--------------------------------------+------+--------------+-----------------------------------------------------------------------| +| =x86_64/amd/zen4= | kvm | 9 to 15 s | boot, the five checks, =gcc -march=native= | +| =x86_64/intel/icelake= | kvm | 10 to 13 s | the same | +| =aarch64/neoverse_n1= | tcg | 16 to 21 s | the checks, =uname -m=, a one-line C compile and run under emulation | + +Most of the time goes to the checks, which load EESSI, GCC and EasyBuild modules. +A build is another matter: a guest on 4 KiB host pages and a virtiofs root costs a compile about 1.45 to 2.3 times its native time, and emulation costs 16 to 28 times. diff --git a/docs/orgmode/howto/index.org b/docs/orgmode/howto/index.org index 757a9ff..ecaada3 100644 --- a/docs/orgmode/howto/index.org +++ b/docs/orgmode/howto/index.org @@ -19,6 +19,7 @@ eb-without-a-site-file build-for-every-node-type build-against-a-site-gpu-module build-for-profiling +build-under-qemu install-what-eessi-lacks find-what-is-wrong refresh-the-module-cache diff --git a/docs/orgmode/reference/cli.org b/docs/orgmode/reference/cli.org index aa5e222..3bd861b 100644 --- a/docs/orgmode/reference/cli.org +++ b/docs/orgmode/reference/cli.org @@ -418,6 +418,44 @@ Without =--unwrapped=, finding nothing to wrap is exit 1. A wrapper adds a run path, when its command links, for each directory named with =-L= or =--library-path=, for the directory of each existing =lib*.so= or =lib*.so.N= file named by its absolute path, and for each =LIBRARY_PATH= entry when it wraps a compiler driver. The arguments in a response file, =@FILE=, count as its own; one it cannot read is passed on unchanged. +** __vm-run + +Internal: eb-local runs it for the builds that mask the CPU view, and it is not in =--help=; its options can change in any release. + +#+begin_example +eb-local __vm-run --mode kvm|tcg --cpu-target TARGET [--memory MiB] [--cpus N] + [--share DIR] [--share-ro DIR] [--allow-archspec-mismatch] -- COMMAND [ARG...] +#+end_example + +Run COMMAND, in the working directory, as the caller's user and group, with the environment variables EasyBuild and EESSI read, inside a virtual CPU that presents TARGET, an EESSI software subdirectory such as =x86_64/amd/zen4=, =x86_64/intel/icelake= or =aarch64/neoverse_n1=. +Before COMMAND starts, the guest checks that the CPU vendor, EESSI archdetect, archspec and =gcc -march=native= (=gcc -mcpu=native= on aarch64) all name TARGET, and that =/dev/fd= exists, and COMMAND does not run when one does not. +=--mode kvm= is for a target of the host's architecture and boots the host kernel under QEMU with KVM, a named CPU model and =enforce=; it never uses the host CPU. +=--mode tcg= is for a target of the other architecture and runs COMMAND in qemu user mode with =QEMU_CPU= set, on the EESSI compatibility layer of that architecture. +[[file:../howto/build-under-qemu.org][Build under a virtual CPU with QEMU]] describes both and what each needs. + +| Option | Meaning | +|-----------------------------+---------------------------------------------------------------------------------------------------------------------------------| +| =--mode kvm=, =--mode tcg= | The kind of virtual CPU. | +| =--cpu-target TARGET= | The target to present; =x86_64/amd/zen2=, =zen3=, =zen4=, =x86_64/intel/haswell=, =skylake_avx512=, =cascadelake=, =icelake=, =sapphirerapids=, =aarch64/neoverse_n1=, =neoverse_v1= or =a64fx=. | +| =--memory MiB= | Guest memory under =kvm=, at least 256; default 8192. =tcg= has none to set. | +| =--cpus N= | Guest CPUs under =kvm=; default the CPUs this process may run on. | +| =--share DIR= | Also mount DIR writable in the guest, under =kvm=. The working directory and the directories named by =HOME=, =TMPDIR=, =XDG_CACHE_HOME=, =WORKING_DIR=, =EASYBUILD_PREFIX=, =EASYBUILD_BUILDPATH=, =EASYBUILD_INSTALLPATH=, =EASYBUILD_SOURCEPATH=, =EASYBUILD_REPOSITORYPATH= and the =EESSI_*_INSTALL= variables are mounted writable already. | +| =--share-ro DIR= | Also mount DIR read-only in the guest, under =kvm=, for a directory on a file system other than =/= that COMMAND needs. | +| =--allow-archspec-mismatch= | Run COMMAND although archspec names another CPU than TARGET, and say so on stderr. The other checks still refuse. | + +The guest receives =PATH=, =HOME=, =USER=, =LOGNAME=, =LANG=, =LC_*=, =TERM=, =TZ=, =TMPDIR=, =MODULEPATH=, =LOADEDMODULES=, =_LMFILES_=, =LMOD*=, =XDG_*=, =EASYBUILD_*=, =EESSI_*=, =EB_*=, =SLURM_*=, =WORKING_DIR= and =SOURCE_DATE_EPOCH=, and no other variable; under =tcg= the compatibility layer's directories come first in =PATH=. + +Exit status: + +| Status | Meaning | +|--------+----------------------------------------------------------------------------------------------------------------------------------------------------| +| 0 to 255 | COMMAND's own status, or 128 and the signal number when a signal ended it. | +| 2 | Refused before anything started: wrong options, an unknown target, a target the mode cannot present, or a missing tool, with the reason on stderr. | +| 125 | The VM or the emulation failed and COMMAND reported no status; the console log of a failed =kvm= run is kept and its path printed. | +| 126 | The guest refused: its CPU view does not name TARGET. COMMAND did not run, and stderr says which check failed. | + +A COMMAND that itself exits 2, 125 or 126 cannot be told from the helper's own statuses by the number alone; the helper's statuses come with a line on stderr that starts with =eb-local: vm-run:=. + ** check For each =FILE=, print its machine, its program interpreter (the loader), its =RPATH= or =RUNPATH=, and where each library it needs resolves, ignoring =LD_LIBRARY_PATH=, then one line for all of them: diff --git a/docs/orgmode/reference/environment.org b/docs/orgmode/reference/environment.org index f9288a5..d7be296 100644 --- a/docs/orgmode/reference/environment.org +++ b/docs/orgmode/reference/environment.org @@ -44,6 +44,9 @@ The site settings, =storage.*=, =build.site_toolchains= and =build.node_types=, | =EB_LOCAL_PIN_BUILDENV_PYTHON= | =1= prepends the stable private compatibility-layer =python3= directory after =dev= loads a build environment. | | =EB_LOCAL_KEEP_WORK= | =1= keeps the workspace of a build that succeeds. | | =EB_LOCAL_VARIANT=, =EB_LOCAL_VARIANT_BLOCK= | Set by a build with =--variant= for its script, which unsets them; a value in your shell is dropped. | +| =EB_LOCAL_QEMU_DIR=, =EB_LOCAL_VIRTIOFSD= | Where the internal =__vm-run= finds =qemu-system-ARCH=, =qemu-ARCH= and =virtiofsd=: a directory searched before =PATH=, and the path of =virtiofsd=. | +| =EB_LOCAL_VM_KERNEL=, =EB_LOCAL_VM_DIR=, =EB_LOCAL_VM_KEEP= | =__vm-run= under =kvm=: the kernel image to boot, with virtiofs and virtio-pci built in, where the running kernel's image is not readable; the directory for the job, on the root file system; =1= keeps the job directory. | +| =EB_LOCAL_VM_CVMFS_REPOS=, =EB_LOCAL_VM_GCC= | =__vm-run=: the CernVM-FS repositories to mount in the guest, default =software.eessi.io=; the compiler the CPU check asks, in place of the =GCCcore= module's. | | =EB_LOCAL_LOCK_TIMEOUT_MS= | Positive integer milliseconds to wait for a busy =flock= lock before exiting non-zero; default =300000=. | | =EB_LOCAL_EESSI_EXTEND= | Set, not empty and not =0=, it sends every argument to =eb=, as after =eb-local eb --=. An eb-stack EESSI target runs eb-local this way. | | =EB_LOCAL_ENV_STRICT= | Set, not empty and not =0= or =false=, =env= and =dev= prepend the same CVMFS check as =--strict= before their load lines. | diff --git a/docs/reference/cli.md b/docs/reference/cli.md index c3cc1a5..05e76a3 100644 --- a/docs/reference/cli.md +++ b/docs/reference/cli.md @@ -422,6 +422,44 @@ Without `--unwrapped`, finding nothing to wrap is exit 1. A wrapper adds a run path, when its command links, for each directory named with `-L` or `--library-path`, for the directory of each existing `lib*.so` or `lib*.so.N` file named by its absolute path, and for each `LIBRARY_PATH` entry when it wraps a compiler driver. The arguments in a response file, `@FILE`, count as its own; one it cannot read is passed on unchanged. +### \_\_vm-run + +Internal: eb-local runs it for the builds that mask the CPU view, and it is not in `--help`; its options can change in any release. + +```text +eb-local __vm-run --mode kvm|tcg --cpu-target TARGET [--memory MiB] [--cpus N] + [--share DIR] [--share-ro DIR] [--allow-archspec-mismatch] -- COMMAND [ARG...] +``` + +Run COMMAND, in the working directory, as the caller's user and group, with the environment variables EasyBuild and EESSI read, inside a virtual CPU that presents TARGET, an EESSI software subdirectory such as `x86_64/amd/zen4`, `x86_64/intel/icelake` or `aarch64/neoverse_n1`. +Before COMMAND starts, the guest checks that the CPU vendor, EESSI archdetect, archspec and `gcc -march=native` (`gcc -mcpu=native` on aarch64) all name TARGET, and that `/dev/fd` exists, and COMMAND does not run when one does not. +`--mode kvm` is for a target of the host's architecture and boots the host kernel under QEMU with KVM, a named CPU model and `enforce`; it never uses the host CPU. +`--mode tcg` is for a target of the other architecture and runs COMMAND in qemu user mode with `QEMU_CPU` set, on the EESSI compatibility layer of that architecture. +[Build under a virtual CPU with QEMU](../howto/build-under-qemu.md) describes both and what each needs. + +| Option | Meaning | +|---|---| +| `--mode kvm`, `--mode tcg` | The kind of virtual CPU. | +| `--cpu-target TARGET` | The target to present; `x86_64/amd/zen2`, `zen3`, `zen4`, `x86_64/intel/haswell`, `skylake_avx512`, `cascadelake`, `icelake`, `sapphirerapids`, `aarch64/neoverse_n1`, `neoverse_v1` or `a64fx`. | +| `--memory MiB` | Guest memory under `kvm`, at least 256; default 8192. `tcg` has none to set. | +| `--cpus N` | Guest CPUs under `kvm`; default the CPUs this process may run on. | +| `--share DIR` | Also mount DIR writable in the guest, under `kvm`. The working directory and the directories named by `HOME`, `TMPDIR`, `XDG_CACHE_HOME`, `WORKING_DIR`, `EASYBUILD_PREFIX`, `EASYBUILD_BUILDPATH`, `EASYBUILD_INSTALLPATH`, `EASYBUILD_SOURCEPATH`, `EASYBUILD_REPOSITORYPATH` and the `EESSI_*_INSTALL` variables are mounted writable already. | +| `--share-ro DIR` | Also mount DIR read-only in the guest, under `kvm`, for a directory on a file system other than `/` that COMMAND needs. | +| `--allow-archspec-mismatch` | Run COMMAND although archspec names another CPU than TARGET, and say so on stderr. The other checks still refuse. | + +The guest receives `PATH`, `HOME`, `USER`, `LOGNAME`, `LANG`, `LC_*`, `TERM`, `TZ`, `TMPDIR`, `MODULEPATH`, `LOADEDMODULES`, `_LMFILES_`, `LMOD*`, `XDG_*`, `EASYBUILD_*`, `EESSI_*`, `EB_*`, `SLURM_*`, `WORKING_DIR` and `SOURCE_DATE_EPOCH`, and no other variable; under `tcg` the compatibility layer's directories come first in `PATH`. + +Exit status: + +| Status | Meaning | +|---|---| +| 0 to 255 | COMMAND's own status, or 128 and the signal number when a signal ended it. | +| 2 | Refused before anything started: wrong options, an unknown target, a target the mode cannot present, or a missing tool, with the reason on stderr. | +| 125 | The VM or the emulation failed and COMMAND reported no status; the console log of a failed `kvm` run is kept and its path printed. | +| 126 | The guest refused: its CPU view does not name TARGET. COMMAND did not run, and stderr says which check failed. | + +A COMMAND that itself exits 2, 125 or 126 cannot be told from the helper's own statuses by the number alone; the helper's statuses come with a line on stderr that starts with `eb-local: vm-run:`. + ### check For each `FILE`, print its machine, its program interpreter (the loader), its `RPATH` or `RUNPATH`, and where each library it needs resolves, ignoring `LD_LIBRARY_PATH`, then one line for all of them: diff --git a/docs/reference/environment.md b/docs/reference/environment.md index 7aed079..f393ba8 100644 --- a/docs/reference/environment.md +++ b/docs/reference/environment.md @@ -46,6 +46,9 @@ The site settings, `storage.*`, `build.site_toolchains` and `build.node_types`, | `EB_LOCAL_PIN_BUILDENV_PYTHON` | `1` prepends the stable private compatibility-layer `python3` directory after `dev` loads a build environment. | | `EB_LOCAL_KEEP_WORK` | `1` keeps the workspace of a build that succeeds. | | `EB_LOCAL_VARIANT`, `EB_LOCAL_VARIANT_BLOCK` | Set by a build with `--variant` for its script, which unsets them; a value in your shell is dropped. | +| `EB_LOCAL_QEMU_DIR`, `EB_LOCAL_VIRTIOFSD` | Where the internal `__vm-run` finds `qemu-system-ARCH`, `qemu-ARCH` and `virtiofsd`: a directory searched before `PATH`, and the path of `virtiofsd`. | +| `EB_LOCAL_VM_KERNEL`, `EB_LOCAL_VM_DIR`, `EB_LOCAL_VM_KEEP` | `__vm-run` under `kvm`: the kernel image to boot, with virtiofs and virtio-pci built in, where the running kernel's image is not readable; the directory for the job, on the root file system; `1` keeps the job directory. | +| `EB_LOCAL_VM_CVMFS_REPOS`, `EB_LOCAL_VM_GCC` | `__vm-run`: the CernVM-FS repositories to mount in the guest, default `software.eessi.io`; the compiler the CPU check asks, in place of the `GCCcore` module's. | | `EB_LOCAL_LOCK_TIMEOUT_MS` | Positive integer milliseconds to wait for a busy `flock` lock before exiting non-zero; default `300000`. | | `EB_LOCAL_EESSI_EXTEND` | Set, not empty and not `0`, it sends every argument to `eb`, as after `eb-local eb --`. An eb-stack EESSI target runs eb-local this way. | | `EB_LOCAL_ENV_STRICT` | Set, not empty and not `0` or `false`, `env` and `dev` prepend the same CVMFS check as `--strict` before their load lines. | From a1cf3da09fe7693b6bb9d78954c662bcf7029399 Mon Sep 17 00:00:00 2001 From: Rohit Goswami Date: Fri, 27 Nov 2026 00:54:02 +0100 Subject: [PATCH 07/17] docs: document every public declaration of the __vm-run helper --- docs/orgmode/howto/build-under-qemu.org | 4 ++-- src/vm.zig | 8 ++++++++ 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/docs/orgmode/howto/build-under-qemu.org b/docs/orgmode/howto/build-under-qemu.org index f3724eb..cce3ad8 100644 --- a/docs/orgmode/howto/build-under-qemu.org +++ b/docs/orgmode/howto/build-under-qemu.org @@ -33,9 +33,9 @@ eb-local __vm-run --mode kvm --cpu-target x86_64/amd/zen4 -- \ The guest boots in a few seconds, checks the CPU, and prints one line before the command output: -#+begin_example +#+begin_src text eb-local: vm-run: x86_64/amd/zen4 presented: vendor=AuthenticAMD archdetect=x86_64/amd/zen4 archspec=zen4 gcc=znver4 -#+end_example +#+end_src The compiler then names =znver4= on a Zen 5 host. The command runs in your working directory, as your user and group, and its exit status is the helper's. diff --git a/src/vm.zig b/src/vm.zig index 50462ef..c8e6938 100644 --- a/src/vm.zig +++ b/src/vm.zig @@ -32,7 +32,9 @@ pub const status_failed: u8 = 125; /// command did not run. pub const status_unverified: u8 = 126; +/// The kind of virtual CPU: KVM for the host's architecture, qemu user mode for the other. pub const Mode = enum { kvm, tcg }; +/// The CPU architectures a target can have. pub const Arch = enum { x86_64, aarch64 }; /// The architecture this binary runs on. @@ -72,6 +74,7 @@ const no_avx512 = "TCG has no AVX-512, so the guest would be a zen3 or a haswell const no_arm_kvm = "KVM on Arm offers the host CPU only; use --mode tcg from an x86_64 host"; const no_x86_kvm = "an x86_64 target needs an x86_64 host under KVM, or --mode tcg from an aarch64 host"; +/// Every target `__vm-run` knows. pub const targets = [_]Target{ .{ .name = "x86_64/amd/zen2", .arch = .x86_64, .vendor = "AuthenticAMD", .archspec = "zen2", .gcc = "znver2", .kvm = "EPYC-Rome," ++ amd_bits, .tcg = "EPYC-Rome" }, .{ .name = "x86_64/amd/zen3", .arch = .x86_64, .vendor = "AuthenticAMD", .archspec = "zen3", .gcc = "znver3", .kvm = "EPYC-Milan,pcid=off," ++ amd_bits, .tcg = "EPYC-Milan" }, @@ -103,6 +106,7 @@ pub const Plan = union(enum) { refused: []const u8, }; +/// What `mode` does for target `t` on a `host`: the QEMU CPU, or why it cannot. pub fn plan(a: Allocator, t: *const Target, mode: Mode, host: Arch) Allocator.Error!Plan { switch (mode) { .kvm => { @@ -130,6 +134,7 @@ pub const Request = struct { command: []const []const u8, }; +/// The result of `parseArgs`. pub const Parsed = union(enum) { ok: Request, /// The message for stderr. @@ -221,6 +226,7 @@ pub const KvmConfig = struct { shares: []const Share, }; +/// The vhost-user socket of share `tag` in the job directory. pub fn socketPath(a: Allocator, rundir: []const u8, tag: []const u8) Allocator.Error![]u8 { return std.fmt.allocPrint(a, "{s}/{s}.sock", .{ rundir, tag }); } @@ -270,6 +276,7 @@ pub fn qemuArgv(a: Allocator, cfg: KvmConfig) Allocator.Error![]const []const u8 return v.toOwnedSlice(a); } +/// The virtiofsd command line for share `s`: no sandbox, read-only when the share is. pub fn virtiofsdArgv(a: Allocator, virtiofsd: []const u8, rundir: []const u8, s: Share) Allocator.Error![]const []const u8 { var v: std.ArrayList([]const u8) = .empty; try v.append(a, virtiofsd); @@ -362,6 +369,7 @@ pub const Job = struct { command: []const []const u8, }; +/// The script the guest runs as the caller: the environment, the working directory, the CPU check, then the command. pub fn jobScript(a: Allocator, j: Job) Allocator.Error![]u8 { var out: std.ArrayList(u8) = .empty; try out.appendSlice(a, "#!/bin/bash\n"); From 529973398d3b81e3ef1afaacea70664d693a7c3d Mon Sep 17 00:00:00 2001 From: Rohit Goswami Date: Fri, 27 Nov 2026 00:58:08 +0100 Subject: [PATCH 08/17] test: define the __vm-run VM runs only under EB_LOCAL_VM_TESTS=1, so no test is skipped --- src/vm.zig | 4 ++ tests/test_vm_run.py | 100 +++++++++++++++++++++---------------------- 2 files changed, 54 insertions(+), 50 deletions(-) diff --git a/src/vm.zig b/src/vm.zig index c8e6938..9ada9c4 100644 --- a/src/vm.zig +++ b/src/vm.zig @@ -645,6 +645,10 @@ fn runKvm(a: Allocator, env: *const std.process.Environ.Map, cwd: []const u8, re err("virtiofsd not found: put it on PATH, in EB_LOCAL_QEMU_DIR, or set EB_LOCAL_VIRTIOFSD to its path", .{}); return status_refused; }; + if (!executable(a, vfsd)) { + err("virtiofsd is not executable at {s}", .{vfsd}); + return status_refused; + } const kernel = kernelPath(a, env) orelse { err("no readable host kernel image: set EB_LOCAL_VM_KERNEL (it needs virtiofs and virtio-pci built in)", .{}); return status_refused; diff --git a/tests/test_vm_run.py b/tests/test_vm_run.py index 0ac3d26..8a973e9 100644 --- a/tests/test_vm_run.py +++ b/tests/test_vm_run.py @@ -56,61 +56,61 @@ def test_a_target_the_mode_cannot_present_is_refused_with_the_reason(self): self.assertEqual(run.returncode, 2, run.stderr) def test_a_host_without_the_tools_refuses_and_does_not_start_a_vm(self): - target = "x86_64/amd/zen4" if HOST == "x86_64" else "aarch64/neoverse_n1" + target = "x86_64/amd/zen4" if HOST == "x86_64" else "x86_64/amd/zen3" mode = "kvm" if HOST == "x86_64" else "tcg" run = vm_run("--mode", mode, "--cpu-target", target, "--", "true", env={"PATH": "/nonexistent", "EB_LOCAL_QEMU_DIR": "/nonexistent", "EB_LOCAL_VIRTIOFSD": "/nonexistent/virtiofsd", "EB_LOCAL_VM_KERNEL": "/nonexistent/vmlinuz"}) - if mode == "kvm": - self.assertEqual(run.returncode, 2, run.stderr) - self.assertNotEqual(run.returncode, 0) - - -@unittest.skipUnless(binary.ZIG and RUN_VMS, "set EB_LOCAL_VM_TESTS=1 on a host with KVM, QEMU, virtiofsd and EESSI") -class Runs(unittest.TestCase): - def timed(self, *args, **kw): - start = time.monotonic() - run = vm_run(*args, **kw) - print(f"\n{' '.join(args[:4])}: {time.monotonic() - start:.1f} s, status {run.returncode}") - return run - - @unittest.skipUnless(HOST == "x86_64", "KVM targets are of the host architecture") - def test_kvm_zen4_reports_znver4_and_passes_the_status_through(self): - run = self.timed("--mode", "kvm", "--cpu-target", "x86_64/amd/zen4", "--", - "bash", "-c", "gcc -march=native -Q --help=target | grep -- '-march='; exit 7") - self.assertEqual(run.returncode, 7, run.stderr) - self.assertIn("znver4", run.stdout) - self.assertIn("archdetect=x86_64/amd/zen4", run.stderr) - self.assertIn("archspec=zen4", run.stderr) - - @unittest.skipUnless(HOST == "x86_64", "KVM targets are of the host architecture") - def test_kvm_icelake_reports_an_intel_part(self): - run = self.timed("--mode", "kvm", "--cpu-target", "x86_64/intel/icelake", "--", - "bash", "-c", "gcc -march=native -Q --help=target | grep -- '-march='; grep -m1 vendor_id /proc/cpuinfo") - self.assertEqual(run.returncode, 0, run.stderr) - self.assertIn("icelake-server", run.stdout) - self.assertIn("GenuineIntel", run.stdout) - self.assertIn("archspec=icelake", run.stderr) - - @unittest.skipUnless(HOST == "x86_64", "KVM targets are of the host architecture") - def test_a_cpu_view_that_does_not_name_the_target_is_refused_before_the_command(self): - marker = f"/tmp/eb-local-vm-test-{os.getpid()}" - run = self.timed("--mode", "kvm", "--cpu-target", "x86_64/amd/zen4", "--", - "bash", "-c", f"touch {marker}", env={"EB_LOCAL_VM_GCC": "/nonexistent/gcc"}) - self.assertEqual(run.returncode, 126, run.stderr) - self.assertIn("refused", run.stderr) - self.assertFalse(os.path.exists(marker)) - - @unittest.skipUnless(HOST == "x86_64", "the aarch64 emulation runs on an x86_64 host here") - def test_tcg_neoverse_n1_runs_the_eessi_aarch64_stack(self): - run = self.timed("--mode", "tcg", "--cpu-target", "aarch64/neoverse_n1", - "--allow-archspec-mismatch", "--", - "bash", "-c", "uname -m; echo 'int main(void){return 0;}' > /tmp/x.c; gcc -mcpu=native -### -c /tmp/x.c 2>&1 | grep -o -- '-mcpu=[^ ]*'") - self.assertEqual(run.returncode, 0, run.stderr) - self.assertIn("aarch64", run.stdout) - self.assertIn("neoverse-n1", run.stdout) - self.assertIn("archdetect=aarch64/neoverse_n1", run.stderr) + self.assertEqual(run.returncode, 2, run.stderr) + self.assertTrue(run.stderr.startswith("eb-local: vm-run: "), run.stderr) + + +# Defined only when asked for, so that a host without KVM lists no skipped tests. +if binary.ZIG and RUN_VMS: + class Runs(unittest.TestCase): + def timed(self, *args, **kw): + start = time.monotonic() + run = vm_run(*args, **kw) + print(f"\n{' '.join(args[:4])}: {time.monotonic() - start:.1f} s, status {run.returncode}") + return run + + @unittest.skipUnless(HOST == "x86_64", "KVM targets are of the host architecture") + def test_kvm_zen4_reports_znver4_and_passes_the_status_through(self): + run = self.timed("--mode", "kvm", "--cpu-target", "x86_64/amd/zen4", "--", + "bash", "-c", "gcc -march=native -Q --help=target | grep -- '-march='; exit 7") + self.assertEqual(run.returncode, 7, run.stderr) + self.assertIn("znver4", run.stdout) + self.assertIn("archdetect=x86_64/amd/zen4", run.stderr) + self.assertIn("archspec=zen4", run.stderr) + + @unittest.skipUnless(HOST == "x86_64", "KVM targets are of the host architecture") + def test_kvm_icelake_reports_an_intel_part(self): + run = self.timed("--mode", "kvm", "--cpu-target", "x86_64/intel/icelake", "--", + "bash", "-c", "gcc -march=native -Q --help=target | grep -- '-march='; grep -m1 vendor_id /proc/cpuinfo") + self.assertEqual(run.returncode, 0, run.stderr) + self.assertIn("icelake-server", run.stdout) + self.assertIn("GenuineIntel", run.stdout) + self.assertIn("archspec=icelake", run.stderr) + + @unittest.skipUnless(HOST == "x86_64", "KVM targets are of the host architecture") + def test_a_cpu_view_that_does_not_name_the_target_is_refused_before_the_command(self): + marker = f"/tmp/eb-local-vm-test-{os.getpid()}" + run = self.timed("--mode", "kvm", "--cpu-target", "x86_64/amd/zen4", "--", + "bash", "-c", f"touch {marker}", env={"EB_LOCAL_VM_GCC": "/nonexistent/gcc"}) + self.assertEqual(run.returncode, 126, run.stderr) + self.assertIn("refused", run.stderr) + self.assertFalse(os.path.exists(marker)) + + @unittest.skipUnless(HOST == "x86_64", "the aarch64 emulation runs on an x86_64 host here") + def test_tcg_neoverse_n1_runs_the_eessi_aarch64_stack(self): + run = self.timed("--mode", "tcg", "--cpu-target", "aarch64/neoverse_n1", + "--allow-archspec-mismatch", "--", + "bash", "-c", "uname -m; echo 'int main(void){return 0;}' > /tmp/x.c; gcc -mcpu=native -### -c /tmp/x.c 2>&1 | grep -o -- '-mcpu=[^ ]*'") + self.assertEqual(run.returncode, 0, run.stderr) + self.assertIn("aarch64", run.stdout) + self.assertIn("neoverse-n1", run.stdout) + self.assertIn("archdetect=aarch64/neoverse_n1", run.stderr) if __name__ == "__main__": From f7969503421b0c08af21111aa35df3a01d8b404a Mon Sep 17 00:00:00 2001 From: Rohit Goswami Date: Fri, 27 Nov 2026 00:59:45 +0100 Subject: [PATCH 09/17] test: run the __vm-run unit tests --- src/main.zig | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main.zig b/src/main.zig index 612ae8c..da87d2c 100644 --- a/src/main.zig +++ b/src/main.zig @@ -7960,6 +7960,7 @@ test { _ = cvmfs; _ = mpi; _ = recipe_overlay; + _ = vm; } test "a build script selects no MPI transport" { From cdc5efea166f85fd3a0fef1067ccbf176d2e17bf Mon Sep 17 00:00:00 2001 From: Rohit Goswami Date: Fri, 27 Nov 2026 00:59:56 +0100 Subject: [PATCH 10/17] test: index the -smp and -m arguments where qemuArgv puts them --- src/vm.zig | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/vm.zig b/src/vm.zig index 9ada9c4..8a12b52 100644 --- a/src/vm.zig +++ b/src/vm.zig @@ -1006,8 +1006,10 @@ test "the QEMU command line names the model with enforce, shares and the three s try testing.expectEqual(@as(usize, 2), vfs); try testing.expect(std.mem.indexOf(u8, argv[argv.len - 1], "root=hostroot ro init=/var/tmp/j/init") != null); try testing.expectEqualStrings("kvm", argv[1]); - try testing.expectEqualStrings("-m", argv[cpu_at.? + 3]); - try testing.expectEqualStrings("2048M", argv[cpu_at.? + 4]); + try testing.expectEqualStrings("-smp", argv[cpu_at.? + 2]); + try testing.expectEqualStrings("4", argv[cpu_at.? + 3]); + try testing.expectEqualStrings("-m", argv[cpu_at.? + 4]); + try testing.expectEqualStrings("2048M", argv[cpu_at.? + 5]); } test "virtiofsd shares the host read-only without a sandbox" { From cfeb705a2ec7f3e80d04cad917e7f8218748273a Mon Sep 17 00:00:00 2001 From: Rohit Goswami Date: Fri, 27 Nov 2026 01:13:19 +0100 Subject: [PATCH 11/17] feat(cpu-target): map __vm-run statuses, add --mask-allow-archspec-mismatch, test the helper call --- changelog.d/+mask-vm-routes.feature.md | 1 + docs/howto/build-for-another-cpu.md | 4 + docs/orgmode/howto/build-for-another-cpu.org | 4 + docs/orgmode/reference/cli.org | 7 +- docs/reference/cli.md | 7 +- src/cpumask.zig | 32 ++++++- src/main.zig | 87 ++++++++++++++++++-- 7 files changed, 125 insertions(+), 17 deletions(-) create mode 100644 changelog.d/+mask-vm-routes.feature.md diff --git a/changelog.d/+mask-vm-routes.feature.md b/changelog.d/+mask-vm-routes.feature.md new file mode 100644 index 0000000..fd9a399 --- /dev/null +++ b/changelog.d/+mask-vm-routes.feature.md @@ -0,0 +1 @@ +`--mask kvm` and `--mask tcg` run the build through `eb-local __vm-run`, and report its statuses 2, 125 and 126 as a refused request, a virtual machine that did not run and a guest CPU that did not read as the target. `--mask-allow-archspec-mismatch` passes `--allow-archspec-mismatch` to the helper and lets the build's preflight accept an archspec name other than the target's, which an aarch64 `--mask tcg` build needs because archspec reads `aarch64` under qemu-user. diff --git a/docs/howto/build-for-another-cpu.md b/docs/howto/build-for-another-cpu.md index 1023797..44503dc 100644 --- a/docs/howto/build-for-another-cpu.md +++ b/docs/howto/build-for-another-cpu.md @@ -72,6 +72,10 @@ The audit, `eb-local audit-isa DIR --target TARGET`, looks for instructions the | `this CPU lacks avx512_fp16` | A mask removes features and cannot add them. `sapphirerapids` needs a host that has AVX512-FP16 and AMX. | | `no mask profile exists for ...` | Only the virtual machine routes can present that target. | | `preflight FAILED: archspec names ...` | An easyblock that asks archspec would build for another CPU than the tree is labelled for. | +| `the kvm route could not run the build ...` | `__vm-run` exited 125: the virtual machine failed to start or reported no status. The console log path is in the lines above. | +| `the tcg guest did not read as ...` | `__vm-run` exited 126: the guest CPU did not read as the target, and the build command did not run. | +| `the kvm route refused the request ...` | `__vm-run` exited 2: it refused the request; the line above says why. | +| `--mask-allow-archspec-mismatch` | Under `--mask tcg` archspec reads `aarch64` for `aarch64/neoverse_n1`, because qemu-user's feature line lacks `evtstrm`. The option passes `--allow-archspec-mismatch` to `__vm-run` and lets the preflight accept that name. An easyblock that keys on archspec then sees a generic Arm CPU, so give it only for a recipe that does not. | | `/dev/fd is missing` | EESSI's `eessi_archdetect.sh` fails without it and EESSI falls back to the generic target. | | `__vm-run` | This eb-local has no virtual machine helper; the `kvm` and `tcg` routes refuse. | diff --git a/docs/orgmode/howto/build-for-another-cpu.org b/docs/orgmode/howto/build-for-another-cpu.org index da24c8b..cafd6c1 100644 --- a/docs/orgmode/howto/build-for-another-cpu.org +++ b/docs/orgmode/howto/build-for-another-cpu.org @@ -70,6 +70,10 @@ The audit, =eb-local audit-isa DIR --target TARGET=, looks for instructions the | =this CPU lacks avx512_fp16= | A mask removes features and cannot add them. =sapphirerapids= needs a host that has AVX512-FP16 and AMX. | | =no mask profile exists for ...= | Only the virtual machine routes can present that target. | | =preflight FAILED: archspec names ...= | An easyblock that asks archspec would build for another CPU than the tree is labelled for. | +| =the kvm route could not run the build ...= | =__vm-run= exited 125: the virtual machine failed to start or reported no status. The console log path is in the lines above. | +| =the tcg guest did not read as ...= | =__vm-run= exited 126: the guest CPU did not read as the target, and the build command did not run. | +| =the kvm route refused the request ...= | =__vm-run= exited 2: it refused the request; the line above says why. | +| =--mask-allow-archspec-mismatch= | Under =--mask tcg= archspec reads =aarch64= for =aarch64/neoverse_n1=, because qemu-user's feature line lacks =evtstrm=. The option passes =--allow-archspec-mismatch= to =__vm-run= and lets the preflight accept that name. An easyblock that keys on archspec then sees a generic Arm CPU, so give it only for a recipe that does not. | | =/dev/fd is missing= | EESSI's =eessi_archdetect.sh= fails without it and EESSI falls back to the generic target. | | =__vm-run= | This eb-local has no virtual machine helper; the =kvm= and =tcg= routes refuse. | diff --git a/docs/orgmode/reference/cli.org b/docs/orgmode/reference/cli.org index 1b02031..69bdd44 100644 --- a/docs/orgmode/reference/cli.org +++ b/docs/orgmode/reference/cli.org @@ -10,7 +10,7 @@ The repository's shell shim delegates every command to this Zig program. eb-local [OPTION]... [eb options] eb-local [OPTION]... --explain [eb options] eb-local [OPTION]... --variant perf|debug [eb options] -eb-local [OPTION]... --cpu-target TARGET [--mask auto|cpuid|kvm|tcg] [--no-audit] [eb options] +eb-local [OPTION]... --cpu-target TARGET [--mask auto|cpuid|kvm|tcg] [--mask-allow-archspec-mismatch] [--no-audit] [eb options] eb-local eb [--] [eb options] eb-local --explain eb [--] [eb options] eb-local [OPTION]... env [--strict] [--json] @@ -58,7 +58,7 @@ directory you own. build that easyconfig with debug symbols and frame pointers (perf) or unoptimised (debug), as a module whose version ends in -perf or -debug - eb-local --cpu-target TARGET [--mask auto|cpuid|kvm|tcg] [--no-audit] [eb options] + eb-local --cpu-target TARGET [--mask auto|cpuid|kvm|tcg] [--mask-allow-archspec-mismatch] [--no-audit] [eb options] build for another CPU target on this machine: TARGET is an EESSI subdirectory (x86_64/amd/zen4) or its last component (zen4). The build sees that CPU through the @@ -250,6 +250,7 @@ After =eb=, every word goes to =eb= except =-h= and =--help=; after =eb --=, eve | =--variant NAME= | Before an easyconfig: build it as the =perf= or =debug= variant, described in the =--variant= section below. | | =--cpu-target TARGET= | Before an easyconfig: build for the CPU target TARGET on this machine, described in the =--cpu-target= section below. | | =--mask ROUTE= | With =--cpu-target=: =auto=, =cpuid=, =kvm= or =tcg=. | +| =--mask-allow-archspec-mismatch= | With =--cpu-target= on the kvm or tcg route: accept an archspec name that differs from the target. archspec reports =aarch64= under qemu-user for lack of =evtstrm=, so an aarch64 =--mask tcg= build needs it. | | =--no-audit= | With =--cpu-target=: skip the instruction audit after the build. | | =-h=, =--help=, =help= | Print the usage on stdout and exit 0. | | =--version= | Print the version line on stdout and exit 0. | @@ -362,7 +363,7 @@ After a successful build, =eb-local audit-isa DIR --target TARGET= runs on each Each installed directory gets =easybuild/eb-local-build-mode.json=, with =cpu_target=, =route=, =profile=, =host_cpu=, =kernel=, =eb_local_version= and =isa_audit= (=pass=, =fail= or =skipped=). =--explain= shows the route and the variables it sets, =EB_LOCAL_CPU_TARGET= and =EESSI_SOFTWARE_SUBDIR_OVERRIDE=. -The =sbatch= lines of =submit=, and the replay hints, carry =--cpu-target=, =--mask= and =--no-audit=. +The =sbatch= lines of =submit=, and the replay hints, carry =--cpu-target=, =--mask=, =--mask-allow-archspec-mismatch= and =--no-audit=. =eb-local doctor --cpu-target TARGET= reports whether CPUID faulting works here, whether =/dev/kvm= and the QEMU binaries exist, and which route =auto= would take. ** eb diff --git a/docs/reference/cli.md b/docs/reference/cli.md index 72dc295..98d6ee4 100644 --- a/docs/reference/cli.md +++ b/docs/reference/cli.md @@ -12,7 +12,7 @@ The repository's shell shim delegates every command to this Zig program. eb-local [OPTION]... [eb options] eb-local [OPTION]... --explain [eb options] eb-local [OPTION]... --variant perf|debug [eb options] -eb-local [OPTION]... --cpu-target TARGET [--mask auto|cpuid|kvm|tcg] [--no-audit] [eb options] +eb-local [OPTION]... --cpu-target TARGET [--mask auto|cpuid|kvm|tcg] [--mask-allow-archspec-mismatch] [--no-audit] [eb options] eb-local eb [--] [eb options] eb-local --explain eb [--] [eb options] eb-local [OPTION]... env [--strict] [--json] @@ -60,7 +60,7 @@ directory you own. build that easyconfig with debug symbols and frame pointers (perf) or unoptimised (debug), as a module whose version ends in -perf or -debug - eb-local --cpu-target TARGET [--mask auto|cpuid|kvm|tcg] [--no-audit] [eb options] + eb-local --cpu-target TARGET [--mask auto|cpuid|kvm|tcg] [--mask-allow-archspec-mismatch] [--no-audit] [eb options] build for another CPU target on this machine: TARGET is an EESSI subdirectory (x86_64/amd/zen4) or its last component (zen4). The build sees that CPU through the @@ -252,6 +252,7 @@ After `eb`, every word goes to `eb` except `-h` and `--help`; after `eb --`, eve | `--variant NAME` | Before an easyconfig: build it as the `perf` or `debug` variant, described in the `--variant` section below. | | `--cpu-target TARGET` | Before an easyconfig: build for the CPU target TARGET on this machine, described in the `--cpu-target` section below. | | `--mask ROUTE` | With `--cpu-target`: `auto`, `cpuid`, `kvm` or `tcg`. | +| `--mask-allow-archspec-mismatch` | With `--cpu-target` on the kvm or tcg route: accept an archspec name that differs from the target. archspec reports `aarch64` under qemu-user for lack of `evtstrm`, so an aarch64 `--mask tcg` build needs it. | | `--no-audit` | With `--cpu-target`: skip the instruction audit after the build. | | `-h`, `--help`, `help` | Print the usage on stdout and exit 0. | | `--version` | Print the version line on stdout and exit 0. | @@ -364,7 +365,7 @@ After a successful build, `eb-local audit-isa DIR --target TARGET` runs on each Each installed directory gets `easybuild/eb-local-build-mode.json`, with `cpu_target`, `route`, `profile`, `host_cpu`, `kernel`, `eb_local_version` and `isa_audit` (`pass`, `fail` or `skipped`). `--explain` shows the route and the variables it sets, `EB_LOCAL_CPU_TARGET` and `EESSI_SOFTWARE_SUBDIR_OVERRIDE`. -The `sbatch` lines of `submit`, and the replay hints, carry `--cpu-target`, `--mask` and `--no-audit`. +The `sbatch` lines of `submit`, and the replay hints, carry `--cpu-target`, `--mask`, `--mask-allow-archspec-mismatch` and `--no-audit`. `eb-local doctor --cpu-target TARGET` reports whether CPUID faulting works here, whether `/dev/kvm` and the QEMU binaries exist, and which route `auto` would take. ### eb diff --git a/src/cpumask.zig b/src/cpumask.zig index e809672..b448984 100644 --- a/src/cpumask.zig +++ b/src/cpumask.zig @@ -392,6 +392,8 @@ pub const Observed = struct { vendor: ?[]const u8 = null, /// Whether CPUID faulting is active in the probe. faulting: ?bool = null, + /// `--mask-allow-archspec-mismatch`: an archspec name other than the target's is noted, not refused. + archspec_allowed: bool = false, }; /// One preflight check and what it found. @@ -429,6 +431,8 @@ pub fn preflight(a: Allocator, p: Profile, route: Route, obs: Observed) []const const want = archspecName(p.subdir); if (std.mem.eql(u8, sp, want)) { add(&out, a, true, "archspec names {s}", .{want}); + } else if (obs.archspec_allowed) { + add(&out, a, true, "archspec names '{s}', not {s}; accepted by --mask-allow-archspec-mismatch", .{ sp, want }); } else add(&out, a, false, "archspec names '{s}', not {s}; an easyblock that asks archspec would build for another CPU than the tree is labelled for", .{ sp, want }); } else add(&out, a, true, "archspec is not importable here; not checked", .{}); const want_gcc = if (p.arch == .x86_64) p.gcc_march else p.gcc_cpu; @@ -663,7 +667,7 @@ pub fn namespaceWords(a: Allocator, unshare: []const u8, setpriv: ?[]const u8, f } /// The variables the masked command gets. -pub fn maskVariables(a: Allocator, p: Profile, libs: Libs, rules_path: []const u8, hooks_path: []const u8, self_exe: []const u8, route: Route) []const [2][]const u8 { +pub fn maskVariables(a: Allocator, p: Profile, libs: Libs, rules_path: []const u8, hooks_path: []const u8, self_exe: []const u8, route: Route, allow_archspec: bool) []const [2][]const u8 { var out: std.ArrayList([2][]const u8) = .empty; const add = struct { fn f(list: *std.ArrayList([2][]const u8), al: Allocator, k: []const u8, v: []const u8) void { @@ -672,6 +676,7 @@ pub fn maskVariables(a: Allocator, p: Profile, libs: Libs, rules_path: []const u }.f; add(&out, a, "EB_LOCAL_CPU_TARGET", p.subdir); add(&out, a, "EB_LOCAL_MASK_ROUTE", @tagName(route)); + if (allow_archspec) add(&out, a, "EB_LOCAL_ALLOW_ARCHSPEC", "1"); add(&out, a, "EB_LOCAL_PROBE", libs.probe); add(&out, a, "EB_LOCAL_SELF", self_exe); add(&out, a, "EB_LOCAL_HOOKS_FILE", hooks_path); @@ -1055,12 +1060,33 @@ test "mask variables set the preload only for the cpuid route" { return false; } }.f; - const cp = maskVariables(a, z4, libs, "/w/rules", "/w/hooks.py", "/bin/eb-local", .cpuid); + const cp = maskVariables(a, z4, libs, "/w/rules", "/w/hooks.py", "/bin/eb-local", .cpuid, false); try testing.expect(has(cp, "LD_PRELOAD")); try testing.expect(has(cp, "CPUIDMASK_RULES")); try testing.expect(has(cp, "CPUIDMASK_STRICT")); try testing.expect(has(cp, "EESSI_SOFTWARE_SUBDIR_OVERRIDE")); - const kv = maskVariables(a, z4, libs, "/w/rules", "/w/hooks.py", "/bin/eb-local", .kvm); + const kv = maskVariables(a, z4, libs, "/w/rules", "/w/hooks.py", "/bin/eb-local", .kvm, false); try testing.expect(!has(kv, "LD_PRELOAD")); try testing.expect(has(kv, "EB_LOCAL_CPU_TARGET")); } + +test "the archspec opt-in reaches the guest variables and relaxes only the archspec check" { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const n1 = findProfile(testProfiles(a), "aarch64/neoverse_n1").?; + const libs: Libs = .{ .preload = "", .probe = "", .dir = "" }; + const vars = maskVariables(a, n1, libs, "", "/w/hooks.py", "/bin/eb-local", .tcg, true); + var found = false; + for (vars) |v| if (std.mem.eql(u8, v[0], "EB_LOCAL_ALLOW_ARCHSPEC") and std.mem.eql(u8, v[1], "1")) { + found = true; + }; + try testing.expect(found); + const seen: Observed = .{ .devfd = true, .archdetect = "aarch64/neoverse_n1:aarch64/generic", .archspec = "aarch64", .gcc = "neoverse-n1" }; + try testing.expect(refused(preflight(a, n1, .tcg, seen))); + var allowed = seen; + allowed.archspec_allowed = true; + try testing.expect(!refused(preflight(a, n1, .tcg, allowed))); + allowed.gcc = "neoverse-v1"; + try testing.expect(refused(preflight(a, n1, .tcg, allowed))); +} diff --git a/src/main.zig b/src/main.zig index 018a3a1..72f9ab0 100644 --- a/src/main.zig +++ b/src/main.zig @@ -65,7 +65,7 @@ const usage_text = \\ build that easyconfig with debug symbols and frame \\ pointers (perf) or unoptimised (debug), as a module \\ whose version ends in -perf or -debug - \\ eb-local --cpu-target TARGET [--mask auto|cpuid|kvm|tcg] [--no-audit] [eb options] + \\ eb-local --cpu-target TARGET [--mask auto|cpuid|kvm|tcg] [--mask-allow-archspec-mismatch] [--no-audit] [eb options] \\ build for another CPU target on this machine: TARGET is \\ an EESSI subdirectory (x86_64/amd/zen4) or its last \\ component (zen4). The build sees that CPU through the @@ -736,6 +736,8 @@ const Global = struct { mask: cpumask.Mode = .auto, /// `--no-audit`: skip the instruction audit after a `--cpu-target` build. no_audit: bool = false, + /// `--mask-allow-archspec-mismatch`: the kvm and tcg routes accept an archspec name that differs from the target's. + mask_allow_archspec: bool = false, /// `env --strict`: refuse to print load lines when the EESSI init path is absent. env_strict: bool = false, /// One line of JSON on stdout instead of the human report. @@ -4645,7 +4647,9 @@ const build_script_tail = \\ esac \\ pf_gcc=$(gcc "$pf_flag=native" -Q --help=target 2>/dev/null | awk -v k="$pf_key" '$1 == k { v = $2 } END { print v }') || pf_gcc= \\ pf_probe=$("${EB_LOCAL_PROBE:-/nonexistent}" 2>/dev/null) || pf_probe= - \\ "$EB_LOCAL_SELF" __mask-preflight "$EB_LOCAL_CPU_TARGET" "$EB_LOCAL_MASK_ROUTE" "$pf_fd" "$pf_ad" "$pf_sp" "$pf_gcc" "$pf_probe" || exit 1 + \\ pf_allow= + \\ [ "${EB_LOCAL_ALLOW_ARCHSPEC:-}" = 1 ] && pf_allow=allow-archspec + \\ "$EB_LOCAL_SELF" __mask-preflight "$EB_LOCAL_CPU_TARGET" "$EB_LOCAL_MASK_ROUTE" "$pf_fd" "$pf_ad" "$pf_sp" "$pf_gcc" "$pf_probe" ${pf_allow:+"$pf_allow"} || exit 1 \\ ;; \\ esac \\fi @@ -4755,8 +4759,65 @@ const MaskPlan = struct { subdir: []const u8, route: cpumask.Route, profile: ?cpumask.Profile, + /// Pass `--allow-archspec-mismatch` to `__vm-run` and the preflight. + allow_archspec: bool = false, }; +/// The words that run COMMAND in a virtual machine presenting `subdir`: this +/// program's `__vm-run` helper with the route as its mode. +fn vmPrefix(a: Allocator, self_exe: []const u8, route: cpumask.Route, subdir: []const u8, allow_archspec: bool) []const []const u8 { + var out: std.ArrayList([]const u8) = .empty; + out.appendSlice(a, &.{ self_exe, "__vm-run", "--mode", @tagName(route), "--cpu-target", subdir }) catch oom(); + if (allow_archspec) out.append(a, "--allow-archspec-mismatch") catch oom(); + out.append(a, "--") catch oom(); + return out.items; +} + +/// What a build says when `__vm-run` ends with one of its own statuses, or +/// null for any other status. 2 is a refused request, 125 a virtual machine +/// that did not run the command, 126 a guest CPU that did not read as the +/// target. A build command that exits with one of these is reported the same +/// way, because the helper's statuses and the command's share one range. +fn vmStatusMessage(a: Allocator, route: cpumask.Route, subdir: []const u8, code: u8) ?[]const u8 { + return switch (code) { + 2 => str(a, "the {s} route refused the request for {s}; the line above says why", .{ @tagName(route), subdir }), + 125 => str(a, "the {s} route could not run the build for {s}: the virtual machine failed to start or reported no status; its console log is named above", .{ @tagName(route), subdir }), + 126 => str(a, "the {s} guest did not read as {s}, so the build command did not run{s}", .{ + @tagName(route), + subdir, + if (route == .tcg) "; if the line above is an archspec name under qemu-user, --mask-allow-archspec-mismatch accepts it" else "", + }), + else => null, + }; +} + +test "vmPrefix names the helper, mode, target and the opt-in" { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const plain = vmPrefix(a, "/bin/eb-local", .kvm, "x86_64/intel/icelake", false); + const want_plain = [_][]const u8{ "/bin/eb-local", "__vm-run", "--mode", "kvm", "--cpu-target", "x86_64/intel/icelake", "--" }; + try std.testing.expectEqual(want_plain.len, plain.len); + for (want_plain, plain) |w, g| try std.testing.expectEqualStrings(w, g); + const opt = vmPrefix(a, "/bin/eb-local", .tcg, "aarch64/neoverse_n1", true); + const want_opt = [_][]const u8{ "/bin/eb-local", "__vm-run", "--mode", "tcg", "--cpu-target", "aarch64/neoverse_n1", "--allow-archspec-mismatch", "--" }; + try std.testing.expectEqual(want_opt.len, opt.len); + for (want_opt, opt) |w, g| try std.testing.expectEqualStrings(w, g); +} + +test "vmStatusMessage maps the helper's own statuses and passes others" { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + try std.testing.expect(vmStatusMessage(a, .kvm, "x86_64/amd/zen4", 2) != null); + try std.testing.expect(vmStatusMessage(a, .kvm, "x86_64/amd/zen4", 125) != null); + const m126 = vmStatusMessage(a, .tcg, "aarch64/neoverse_n1", 126).?; + try std.testing.expect(std.mem.indexOf(u8, m126, "--mask-allow-archspec-mismatch") != null); + try std.testing.expect(std.mem.indexOf(u8, vmStatusMessage(a, .kvm, "x86_64/amd/zen4", 126).?, "--mask-allow-archspec-mismatch") == null); + try std.testing.expect(vmStatusMessage(a, .kvm, "x86_64/amd/zen4", 0) == null); + try std.testing.expect(vmStatusMessage(a, .kvm, "x86_64/amd/zen4", 1) == null); +} + /// Whether this binary has the `__vm-run` helper the kvm and tcg routes call. fn vmHelperKnown() bool { return subcommand("__vm-run") != null; @@ -4793,7 +4854,11 @@ fn maskDecide(c: Ctx, g: Global, want_audit: bool) MaskPlan { const profile = cpumask.findProfile(cpumask.builtinProfiles(c.a), subdir); const host = cpumask.readHost(c.a, hostSubdir(c), vmHelperKnown()) orelse die("--cpu-target works on x86_64 and aarch64 machines only", .{}); return switch (cpumask.choose(c.a, g.mask, subdir, profile, host)) { - .route => |r| .{ .subdir = subdir, .route = r, .profile = profile }, + .route => |r| blk: { + if (g.mask_allow_archspec and r != .kvm and r != .tcg) + die("--mask-allow-archspec-mismatch applies to the kvm and tcg routes; {s} builds with the {s} route", .{ subdir, @tagName(r) }); + break :blk .{ .subdir = subdir, .route = r, .profile = profile, .allow_archspec = g.mask_allow_archspec }; + }, .refuse => |m| die("--cpu-target {s}: {s}; nothing was built.", .{ subdir, m }), }; } @@ -4818,7 +4883,7 @@ fn maskMaterialize(c: Ctx, plan: MaskPlan, dir: []const u8) union(enum) { ok: Ma var rules_path: []const u8 = ""; var prefix: []const []const u8 = &.{}; if (plan.route == .kvm or plan.route == .tcg) { - prefix = &.{ self_exe, "__vm-run", "--mode", @tagName(plan.route), "--cpu-target", plan.subdir, "--" }; + prefix = vmPrefix(a, self_exe, plan.route, plan.subdir, plan.allow_archspec); } if (plan.route == .cpuid) { const profile = plan.profile.?; @@ -4837,7 +4902,7 @@ fn maskMaterialize(c: Ctx, plan: MaskPlan, dir: []const u8) union(enum) { ok: Ma const setpriv = proc.which(a, "setpriv", path_env) catch null; prefix = cpumask.namespaceWords(a, unshare, setpriv, fake); } - const vars = cpumask.maskVariables(a, plan.profile orelse .{ .subdir = plan.subdir, .arch = cpumask.archOf(plan.subdir) orelse .x86_64 }, libs, rules_path, hooks, self_exe, plan.route); + const vars = cpumask.maskVariables(a, plan.profile orelse .{ .subdir = plan.subdir, .arch = cpumask.archOf(plan.subdir) orelse .x86_64 }, libs, rules_path, hooks, self_exe, plan.route, plan.allow_archspec); return .{ .ok = .{ .vars = vars, .prefix = prefix } }; } @@ -4845,12 +4910,12 @@ fn maskMaterialize(c: Ctx, plan: MaskPlan, dir: []const u8) union(enum) { ok: Ma /// build script saw inside the mask, checked against the target. Prints one /// line per check and exits 1 when any fails. fn cmdMaskPreflight(c: Ctx, args: []const []const u8) u8 { - if (args.len != 7) die("__mask-preflight takes TARGET ROUTE DEVFD ARCHDETECT ARCHSPEC GCC PROBE", .{}); + if (args.len != 7 and args.len != 8) die("__mask-preflight takes TARGET ROUTE DEVFD ARCHDETECT ARCHSPEC GCC PROBE [allow-archspec]", .{}); const a = c.a; const target = args[0]; const route = std.meta.stringToEnum(cpumask.Route, args[1]) orelse die("__mask-preflight: unknown route {s}", .{args[1]}); const profile = cpumask.findProfile(cpumask.builtinProfiles(a), target) orelse die("no mask profile for {s}", .{target}); - var obs: cpumask.Observed = .{ .devfd = std.mem.eql(u8, args[2], "yes") }; + var obs: cpumask.Observed = .{ .devfd = std.mem.eql(u8, args[2], "yes"), .archspec_allowed = args.len == 8 and std.mem.eql(u8, args[7], "allow-archspec") }; if (args[3].len > 0) obs.archdetect = args[3]; if (args[4].len > 0) obs.archspec = std.mem.trim(u8, args[4], " \t\r\n"); if (args[5].len > 0) obs.gcc = std.mem.trim(u8, args[5], " \t\r\n"); @@ -5351,7 +5416,7 @@ fn cmdBuild(c: Ctx, s: config.Settings, g: Global, args: []const []const u8) u8 _ = env.swapRemove("EB_LOCAL_SITE_TOOLCHAINS"); _ = env.swapRemove("EB_LOCAL_VARIANT"); _ = env.swapRemove("EB_LOCAL_VARIANT_BLOCK"); - for ([_][]const u8{ "EB_LOCAL_CPU_TARGET", "EB_LOCAL_MASK_ROUTE", "EB_LOCAL_PROBE", "EB_LOCAL_SELF", "EB_LOCAL_HOOKS_FILE", "EB_LOCAL_BASE_HOOKS" }) |name| _ = env.swapRemove(name); + for ([_][]const u8{ "EB_LOCAL_CPU_TARGET", "EB_LOCAL_MASK_ROUTE", "EB_LOCAL_ALLOW_ARCHSPEC", "EB_LOCAL_PROBE", "EB_LOCAL_SELF", "EB_LOCAL_HOOKS_FILE", "EB_LOCAL_BASE_HOOKS" }) |name| _ = env.swapRemove(name); for (shell_startup) |name| _ = env.swapRemove(name); for (s.secrets.items) |sec| if (config.withheldSource(s, sec)) |name| { _ = env.swapRemove(name); @@ -5409,6 +5474,9 @@ fn cmdBuild(c: Ctx, s: config.Settings, g: Global, args: []const []const u8) u8 .signal => 1, .unreaped => 1, }; + if (mask_plan) |m| if ((m.route == .kvm or m.route == .tcg) and rc != 0) { + if (vmStatusMessage(a, m.route, m.subdir, rc)) |why| warn("--cpu-target {s}: {s}", .{ m.subdir, why }); + }; var audit_failed = false; if (mask_plan) |m| if (rc == 0) { if (!maskAfterBuild(c, g, m, p.prefix, started)) { @@ -6572,6 +6640,7 @@ fn maskOptionWords(a: Allocator, g: Global) []const []const u8 { var out: std.ArrayList([]const u8) = .empty; out.appendSlice(a, &.{ "--cpu-target", qSingleLine(a, t) }) catch oom(); if (g.mask != .auto) out.appendSlice(a, &.{ "--mask", @tagName(g.mask) }) catch oom(); + if (g.mask_allow_archspec) out.append(a, "--mask-allow-archspec-mismatch") catch oom(); if (g.no_audit) out.append(a, "--no-audit") catch oom(); return out.items; } @@ -7937,6 +8006,8 @@ fn runMain(init: std.process.Init) u8 { } else if ((std.mem.eql(u8, x, "--mask") or joined(x, "--mask") != null) and command == .build and rest.items.len == 0) { const v = if (joined(x, "--mask")) |j| j else value(args, &i, "--mask"); g.mask = std.meta.stringToEnum(cpumask.Mode, v) orelse die("--mask takes auto, cpuid, kvm or tcg", .{}); + } else if (std.mem.eql(u8, x, "--mask-allow-archspec-mismatch") and command == .build and rest.items.len == 0) { + g.mask_allow_archspec = true; } else if (std.mem.eql(u8, x, "--no-audit") and command == .build and rest.items.len == 0) { g.no_audit = true; } else if (command == .build and rest.items.len == 0 and subcommand(x) != null) { From c2457d9520ed593a3fd994de77d17406848f3c4f Mon Sep 17 00:00:00 2001 From: Rohit Goswami Date: Fri, 27 Nov 2026 01:16:29 +0100 Subject: [PATCH 12/17] docs: name EB_LOCAL_ALLOW_ARCHSPEC on the environment page --- docs/orgmode/reference/environment.org | 2 +- docs/reference/environment.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/orgmode/reference/environment.org b/docs/orgmode/reference/environment.org index 793bc43..6245f55 100644 --- a/docs/orgmode/reference/environment.org +++ b/docs/orgmode/reference/environment.org @@ -43,7 +43,7 @@ The site settings, =storage.*=, =build.site_toolchains= and =build.node_types=, | =EB_LOCAL_CONFIG= | Names a configuration file to read when =--config= does not. | | =EB_LOCAL_PIN_BUILDENV_PYTHON= | =1= prepends the stable private compatibility-layer =python3= directory after =dev= loads a build environment. | | =EB_LOCAL_KEEP_WORK= | =1= keeps the workspace of a build that succeeds. | -| =EB_LOCAL_CPU_TARGET=, =EB_LOCAL_MASK_ROUTE=, =EB_LOCAL_PROBE=, =EB_LOCAL_SELF=, =EB_LOCAL_HOOKS_FILE=, =EB_LOCAL_BASE_HOOKS= | Set by a build with =--cpu-target= for its script, as the target, the route, the CPUID probe, this program, the EasyBuild hooks file and the hooks the stack set; a value in your shell is dropped. | +| =EB_LOCAL_CPU_TARGET=, =EB_LOCAL_MASK_ROUTE=, =EB_LOCAL_ALLOW_ARCHSPEC=, =EB_LOCAL_PROBE=, =EB_LOCAL_SELF=, =EB_LOCAL_HOOKS_FILE=, =EB_LOCAL_BASE_HOOKS= | Set by a build with =--cpu-target= for its script, as the target, the route, whether the preflight accepts another archspec name (1 with =--mask-allow-archspec-mismatch=), the CPUID probe, this program, the EasyBuild hooks file and the hooks the stack set; a value in your shell is dropped. | | =EB_LOCAL_VARIANT=, =EB_LOCAL_VARIANT_BLOCK= | Set by a build with =--variant= for its script, which unsets them; a value in your shell is dropped. | | =EB_LOCAL_QEMU_DIR=, =EB_LOCAL_VIRTIOFSD= | Where the internal =__vm-run= finds =qemu-system-ARCH=, =qemu-ARCH= and =virtiofsd=: a directory searched before =PATH=, and the path of =virtiofsd=. | | =EB_LOCAL_VM_KERNEL=, =EB_LOCAL_VM_DIR=, =EB_LOCAL_VM_KEEP= | =__vm-run= under =kvm=: the kernel image to boot, with virtiofs and virtio-pci built in, where the running kernel's image is not readable; the directory for the job, on the root file system; =1= keeps the job directory. | diff --git a/docs/reference/environment.md b/docs/reference/environment.md index 6983aea..4e6b39f 100644 --- a/docs/reference/environment.md +++ b/docs/reference/environment.md @@ -45,7 +45,7 @@ The site settings, `storage.*`, `build.site_toolchains` and `build.node_types`, | `EB_LOCAL_CONFIG` | Names a configuration file to read when `--config` does not. | | `EB_LOCAL_PIN_BUILDENV_PYTHON` | `1` prepends the stable private compatibility-layer `python3` directory after `dev` loads a build environment. | | `EB_LOCAL_KEEP_WORK` | `1` keeps the workspace of a build that succeeds. | -| `EB_LOCAL_CPU_TARGET`, `EB_LOCAL_MASK_ROUTE`, `EB_LOCAL_PROBE`, `EB_LOCAL_SELF`, `EB_LOCAL_HOOKS_FILE`, `EB_LOCAL_BASE_HOOKS` | Set by a build with `--cpu-target` for its script, as the target, the route, the CPUID probe, this program, the EasyBuild hooks file and the hooks the stack set; a value in your shell is dropped. | +| `EB_LOCAL_CPU_TARGET`, `EB_LOCAL_MASK_ROUTE`, `EB_LOCAL_ALLOW_ARCHSPEC`, `EB_LOCAL_PROBE`, `EB_LOCAL_SELF`, `EB_LOCAL_HOOKS_FILE`, `EB_LOCAL_BASE_HOOKS` | Set by a build with `--cpu-target` for its script, as the target, the route, whether the preflight accepts another archspec name (1 with `--mask-allow-archspec-mismatch`), the CPUID probe, this program, the EasyBuild hooks file and the hooks the stack set; a value in your shell is dropped. | | `EB_LOCAL_VARIANT`, `EB_LOCAL_VARIANT_BLOCK` | Set by a build with `--variant` for its script, which unsets them; a value in your shell is dropped. | | `EB_LOCAL_QEMU_DIR`, `EB_LOCAL_VIRTIOFSD` | Where the internal `__vm-run` finds `qemu-system-ARCH`, `qemu-ARCH` and `virtiofsd`: a directory searched before `PATH`, and the path of `virtiofsd`. | | `EB_LOCAL_VM_KERNEL`, `EB_LOCAL_VM_DIR`, `EB_LOCAL_VM_KEEP` | `__vm-run` under `kvm`: the kernel image to boot, with virtiofs and virtio-pci built in, where the running kernel's image is not readable; the directory for the job, on the root file system; `1` keeps the job directory. | From 92609986c6bbd654c655d974372339134fd8a1b8 Mon Sep 17 00:00:00 2001 From: Rohit Goswami Date: Fri, 27 Nov 2026 01:38:24 +0100 Subject: [PATCH 13/17] fix(cpu-target): the kvm and tcg routes see the built-in __vm-run helper --- src/main.zig | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/main.zig b/src/main.zig index 72f9ab0..29f7c17 100644 --- a/src/main.zig +++ b/src/main.zig @@ -4819,8 +4819,14 @@ test "vmStatusMessage maps the helper's own statuses and passes others" { } /// Whether this binary has the `__vm-run` helper the kvm and tcg routes call. +/// The helper is dispatched before argument parsing and is not a `Command`, so +/// it is present whenever `vm.zig` is part of this program. fn vmHelperKnown() bool { - return subcommand("__vm-run") != null; + return @hasDecl(vm, "run"); +} + +test "the build that includes vm.zig offers the kvm and tcg routes" { + try std.testing.expect(vmHelperKnown()); } /// Whether this binary has the `audit-isa` command the audit step calls. From 2a48f853e56d69f7d89e9d6c3e0e245c915f34b1 Mon Sep 17 00:00:00 2001 From: Rohit Goswami Date: Fri, 27 Nov 2026 01:40:32 +0100 Subject: [PATCH 14/17] fix(cpu-target): the kvm and tcg preflight reads the guest vendor from /proc/cpuinfo --- src/main.zig | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/main.zig b/src/main.zig index 29f7c17..6b4de6e 100644 --- a/src/main.zig +++ b/src/main.zig @@ -4646,7 +4646,13 @@ const build_script_tail = \\ *) pf_flag=-march pf_key=-march= ;; \\ esac \\ pf_gcc=$(gcc "$pf_flag=native" -Q --help=target 2>/dev/null | awk -v k="$pf_key" '$1 == k { v = $2 } END { print v }') || pf_gcc= - \\ pf_probe=$("${EB_LOCAL_PROBE:-/nonexistent}" 2>/dev/null) || pf_probe= + \\ # The cpuid route compiles a probe; a virtual machine's CPUID is the + \\ # guest's own, so its vendor is what /proc/cpuinfo reports there. + \\ if [ "$EB_LOCAL_MASK_ROUTE" = cpuid ]; then + \\ pf_probe=$("${EB_LOCAL_PROBE:-/nonexistent}" 2>/dev/null) || pf_probe= + \\ else + \\ pf_probe=vendor=$(sed -n 's/^vendor_id[[:space:]]*:[[:space:]]*//p' /proc/cpuinfo 2>/dev/null | head -n 1) + \\ fi \\ pf_allow= \\ [ "${EB_LOCAL_ALLOW_ARCHSPEC:-}" = 1 ] && pf_allow=allow-archspec \\ "$EB_LOCAL_SELF" __mask-preflight "$EB_LOCAL_CPU_TARGET" "$EB_LOCAL_MASK_ROUTE" "$pf_fd" "$pf_ad" "$pf_sp" "$pf_gcc" "$pf_probe" ${pf_allow:+"$pf_allow"} || exit 1 From e6626851a4dada5867458b734fdd8964bea45553 Mon Sep 17 00:00:00 2001 From: Rohit Goswami Date: Fri, 27 Nov 2026 01:43:44 +0100 Subject: [PATCH 15/17] fix(cpu-target): the aarch64 preflight reads the CPU name before the extensions GCC appends --- src/cpumask.zig | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/cpumask.zig b/src/cpumask.zig index b448984..1624faf 100644 --- a/src/cpumask.zig +++ b/src/cpumask.zig @@ -437,7 +437,9 @@ pub fn preflight(a: Allocator, p: Profile, route: Route, obs: Observed) []const } else add(&out, a, true, "archspec is not importable here; not checked", .{}); const want_gcc = if (p.arch == .x86_64) p.gcc_march else p.gcc_cpu; const gcc_what = if (p.arch == .x86_64) "-march" else "-mcpu"; - if (obs.gcc) |g| { + if (obs.gcc) |gcc_full| { + // aarch64 GCC appends the extensions it enables: neoverse-n1+crc+crypto. + const g = if (p.arch == .aarch64) gcc_full[0 .. std.mem.indexOfScalar(u8, gcc_full, '+') orelse gcc_full.len] else gcc_full; if (std.mem.eql(u8, g, want_gcc)) { add(&out, a, true, "gcc {s}=native is {s}", .{ gcc_what, want_gcc }); } else add(&out, a, false, "gcc {s}=native is '{s}', not {s}", .{ gcc_what, g, want_gcc }); @@ -1087,6 +1089,10 @@ test "the archspec opt-in reaches the guest variables and relaxes only the archs var allowed = seen; allowed.archspec_allowed = true; try testing.expect(!refused(preflight(a, n1, .tcg, allowed))); + allowed.gcc = "neoverse-n1+crc+crypto"; + try testing.expect(!refused(preflight(a, n1, .tcg, allowed))); + allowed.gcc = "neoverse-v1+crc"; + try testing.expect(refused(preflight(a, n1, .tcg, allowed))); allowed.gcc = "neoverse-v1"; try testing.expect(refused(preflight(a, n1, .tcg, allowed))); } From f157f6b7877eeae95acb874e68888d68e34d93e4 Mon Sep 17 00:00:00 2001 From: Rohit Goswami Date: Fri, 27 Nov 2026 02:01:16 +0100 Subject: [PATCH 16/17] fix(secrets): redact logs written within one second before the build began --- src/main.zig | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/main.zig b/src/main.zig index 6b4de6e..c5ae47d 100644 --- a/src/main.zig +++ b/src/main.zig @@ -5362,6 +5362,9 @@ fn cmdBuild(c: Ctx, s: config.Settings, g: Global, args: []const []const u8) u8 } } const started: i64 = nowSecs(); + // File times have one-second resolution, so a log written in the second before + // the build began can carry a time one second below `started`; redaction reaches back that far. + const redact_since = started - 1; for (leftover_vars) |v| if (c.env.get(v)) |val| { if (ownInstallVar(c, s, p, v, val) == null) @@ -5506,10 +5509,10 @@ fn cmdBuild(c: Ctx, s: config.Settings, g: Global, args: []const []const u8) u8 } else if (values.len > 0) { var report: secrets.RedactReport = .{}; const tools: secrets.Tools = .{ .path = c.env.get("PATH") orelse "/usr/bin:/bin", .envp = c.envp }; - secrets.redactTree(a, d.logs, started, values, .all, tools, &report) catch |e| warn("cannot check {s} for secret values ({s}); inspect it before sharing", .{ d.logs, storage.describeError(e) }); + secrets.redactTree(a, d.logs, redact_since, values, .all, tools, &report) catch |e| warn("cannot check {s} for secret values ({s}); inspect it before sharing", .{ d.logs, storage.describeError(e) }); // EasyBuild keeps a copy of its log in each installation's easybuild/. const versions = std.fs.path.join(a, &.{ p.prefix, "versions" }) catch oom(); - secrets.redactTree(a, versions, started, values, .easybuild_dirs, tools, &report) catch |e| warn("cannot check {s} for secret values ({s}); inspect it before sharing", .{ versions, storage.describeError(e) }); + secrets.redactTree(a, versions, redact_since, values, .easybuild_dirs, tools, &report) catch |e| warn("cannot check {s} for secret values ({s}); inspect it before sharing", .{ versions, storage.describeError(e) }); for (report.too_deep.items) |f| warn("{s} is too deep to check for secret values; inspect it before sharing", .{f}); if (report.files > 0) say("eb-local: removed secret values from {d} log file(s)", .{report.files}); for (report.too_large.items) |f| warn("{s} is too large to check for secret values; inspect it before sharing", .{f}); From b62dc436419ca8c7b22b4582ba9033f0aec61b17 Mon Sep 17 00:00:00 2001 From: Rohit Goswami Date: Fri, 27 Nov 2026 04:28:12 +0100 Subject: [PATCH 17/17] ci(workstation): fetch the pigz source with retries and a checksum check before the build The zlib.net download intermittently handed the GitHub runner a file that failed EasyBuild's checksum (PRs 450, 451 and 452); the same URL gives the expected sha256 elsewhere. The job fetches it with retries, checks the sha256, and places it in eb-local's source path. --- .github/workflows/workstation.yml | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/.github/workflows/workstation.yml b/.github/workflows/workstation.yml index 77ae26b..a63b51b 100644 --- a/.github/workflows/workstation.yml +++ b/.github/workflows/workstation.yml @@ -34,6 +34,20 @@ jobs: run: | ! command -v sbatch ! env | grep -q '^SLURM_' + - name: fetch the pigz source, checked + # The download from zlib.net intermittently gives the runner a file + # that fails EasyBuild's checksum; fetch it here with retries and put + # the verified tarball where eb-local's source path looks first. + run: | + want=eb872b4f0e1f0ebe59c9f7bd8c506c4204893ba6a8492de31df416f0d5170fd0 + dir="$HOME/eessi/.eb-local/sources/p/pigz" + mkdir -p "$dir" + for i in 1 2 3 4 5 6; do + curl -fsSL --retry 3 -o "$dir/pigz-2.8.tar.gz" https://zlib.net/pigz/pigz-2.8.tar.gz || true + if [ "$(sha256sum "$dir/pigz-2.8.tar.gz" | cut -d' ' -f1)" = "$want" ]; then exit 0; fi + echo "attempt $i: checksum mismatch"; sleep $((i * 10)) + done + exit 1 - name: build pigz on the runner run: | export PATH="$RUNNER_TEMP/eb-local/bin:$PATH"