From 140ffaf716e2fa8a2f13d55880ca0fc4521df6fe Mon Sep 17 00:00:00 2001 From: Tyler Smith <74526874+tylertms@users.noreply.github.com> Date: Fri, 20 Nov 2026 07:23:38 -0500 Subject: [PATCH] fix(gpu): the StelaGPU kext sets the length of a file it rewrites, since vnode_open leaves O_TRUNC to the open syscall and a shorter plugin kept the old one's tail, and a failed install stops naming its step and errno --- crates/stela-boot/src/engine/gpu/gate.rs | 6 +- crates/stela-contracts/src/gate.rs | 213 +++++++++++++++++++- guest/stela-gpu/kext/file_rewrite.h | 67 +++++++ guest/stela-gpu/kext/files.cpp | 84 ++++++-- guest/stela-gpu/kext/files.h | 10 +- guest/stela-gpu/kext/install.cpp | 52 +++-- guest/stela-gpu/kext/install_report.h | 47 +++++ guest/stela-gpu/kext/tests/file_rewrite.c | 234 ++++++++++++++++++++++ xtask/src/guest/app/tests.rs | 15 +- xtask/src/guest/sdk.rs | 2 +- 10 files changed, 681 insertions(+), 49 deletions(-) create mode 100644 guest/stela-gpu/kext/file_rewrite.h create mode 100644 guest/stela-gpu/kext/install_report.h create mode 100644 guest/stela-gpu/kext/tests/file_rewrite.c diff --git a/crates/stela-boot/src/engine/gpu/gate.rs b/crates/stela-boot/src/engine/gpu/gate.rs index e38278e450..39ca80cdfd 100644 --- a/crates/stela-boot/src/engine/gpu/gate.rs +++ b/crates/stela-boot/src/engine/gpu/gate.rs @@ -585,7 +585,7 @@ fn bundle(report: BundleReport) { BundleReport::Current => Report::Current, BundleReport::Updated => Report::Updated, BundleReport::Missing => Report::Missing, - BundleReport::Failed => Report::Failed, + BundleReport::Failed(_) => Report::Failed, }); match (decided, report) { (Decision::Continue(_), BundleReport::Updated) => { @@ -609,6 +609,10 @@ fn bundle(report: BundleReport) { super::super::service::request_restart(); } (Decision::StopMissing { attempted }, _) => stop(&bundle_repair::missing(attempted)), + (Decision::StopFailed, BundleReport::Failed(failure)) => stop(&format!( + "the StelaGPU kext could not install StelaGPU.bundle: {failure}; \ + its StelaGPU lines above name the file" + )), (Decision::StopFailed, _) => stop( "the StelaGPU kext could not install StelaGPU.bundle; its StelaGPU lines above say why", ), diff --git a/crates/stela-contracts/src/gate.rs b/crates/stela-contracts/src/gate.rs index 3f0dc29c35..e51663e476 100644 --- a/crates/stela-contracts/src/gate.rs +++ b/crates/stela-contracts/src/gate.rs @@ -87,17 +87,132 @@ pub enum BundleReport { /// directories for a kext. Missing, /// Reading or writing a file failed. - Failed, + Failed(BundleFailure), +} + +/// Where the kext's installation of the plugin failed, and why. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct BundleFailure { + pub step: BundleStep, + /// The guest kernel's errno; 0 for [`BundleStep::Differs`]. + pub errno: u16, +} + +/// A step of the kext's installation, by its `BUNDLE_STEP_` value. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum BundleStep { + Allocate, + Path, + Read, + Open, + Write, + Length, + Sync, + Close, + Verify, + Differs, +} + +impl BundleStep { + const ALL: [(u64, Self); 10] = [ + (window::BUNDLE_STEP_ALLOCATE, Self::Allocate), + (window::BUNDLE_STEP_PATH, Self::Path), + (window::BUNDLE_STEP_READ, Self::Read), + (window::BUNDLE_STEP_OPEN, Self::Open), + (window::BUNDLE_STEP_WRITE, Self::Write), + (window::BUNDLE_STEP_LENGTH, Self::Length), + (window::BUNDLE_STEP_SYNC, Self::Sync), + (window::BUNDLE_STEP_CLOSE, Self::Close), + (window::BUNDLE_STEP_VERIFY, Self::Verify), + (window::BUNDLE_STEP_DIFFERS, Self::Differs), + ]; + + /// What the kext was doing, in the words of a stop line. + pub fn describe(self) -> &'static str { + match self { + Self::Allocate => "allocating its buffers", + Self::Path => "spelling a file's path", + Self::Read => "reading the installed file", + Self::Open => "opening the file to write it", + Self::Write => "writing the file", + Self::Length => "setting the file's length", + Self::Sync => "flushing the file to disk", + Self::Close => "closing the file", + Self::Verify => "reading the written file back", + Self::Differs => "checking the written file", + } + } +} + +impl core::fmt::Display for BundleFailure { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + if self.step == BundleStep::Differs { + return f.write_str("a file it wrote reads back unlike its own"); + } + f.write_str(self.step.describe())?; + f.write_str(" failed with ")?; + match darwin_errno_name(self.errno) { + Some(name) => write!(f, "{name} ({})", self.errno), + None => write!(f, "errno {}", self.errno), + } + } +} + +/// The symbolic name of a Darwin errno a file operation answers. +pub fn darwin_errno_name(errno: u16) -> Option<&'static str> { + Some(match errno { + 1 => "EPERM", + 2 => "ENOENT", + 4 => "EINTR", + 5 => "EIO", + 6 => "ENXIO", + 9 => "EBADF", + 12 => "ENOMEM", + 13 => "EACCES", + 16 => "EBUSY", + 17 => "EEXIST", + 20 => "ENOTDIR", + 21 => "EISDIR", + 22 => "EINVAL", + 26 => "ETXTBSY", + 27 => "EFBIG", + 28 => "ENOSPC", + 30 => "EROFS", + 35 => "EAGAIN", + 45 => "ENOTSUP", + 62 => "ELOOP", + 63 => "ENAMETOOLONG", + 69 => "EDQUOT", + 70 => "ESTALE", + 79 => "EFTYPE", + 80 => "EAUTH", + _ => return None, + }) } impl BundleReport { - /// The report a store of `value` to [`window::BUNDLE`] makes. + /// The report a store of `value` to [`window::BUNDLE`] makes. A failure + /// names its step in the bits at [`window::BUNDLE_STEP_SHIFT`] and its + /// errno in those at [`window::BUNDLE_ERRNO_SHIFT`]; no other report + /// sets them. pub fn from_raw(value: u64) -> Option { - match value { + let kind = value & 0xff; + let step = (value >> window::BUNDLE_STEP_SHIFT) & 0xff; + let errno = (value >> window::BUNDLE_ERRNO_SHIFT) & 0xffff; + if value >> 32 != 0 || (kind != window::BUNDLE_FAILED && value != kind) { + return None; + } + match kind { window::BUNDLE_CURRENT => Some(Self::Current), window::BUNDLE_UPDATED => Some(Self::Updated), window::BUNDLE_MISSING => Some(Self::Missing), - window::BUNDLE_FAILED => Some(Self::Failed), + window::BUNDLE_FAILED => { + let (_, step) = BundleStep::ALL.into_iter().find(|&(raw, _)| raw == step)?; + Some(Self::Failed(BundleFailure { + step, + errno: errno as u16, + })) + } _ => None, } } @@ -275,7 +390,95 @@ pub mod window { BUNDLE_UPDATED = 2; /// `BUNDLE`: the plugin's directories are absent. BUNDLE_MISSING = 3; - /// `BUNDLE`: reading or writing a file of the plugin failed. + /// `BUNDLE`: reading or writing a file of the plugin failed. The + /// store also names the step, a `BUNDLE_STEP_` value, at + /// `BUNDLE_STEP_SHIFT` and the kernel's errno at + /// `BUNDLE_ERRNO_SHIFT`, 0 for `BUNDLE_STEP_DIFFERS`. BUNDLE_FAILED = 4; + /// `BUNDLE`: where a failure's step is, 8 bits. + BUNDLE_STEP_SHIFT = 8; + /// `BUNDLE`: where a failure's errno is, 16 bits. + BUNDLE_ERRNO_SHIFT = 16; + /// `BUNDLE` step: the installer's buffers could not be allocated. + BUNDLE_STEP_ALLOCATE = 1; + /// `BUNDLE` step: a file's path is longer than the kext's buffers. + BUNDLE_STEP_PATH = 2; + /// `BUNDLE` step: reading the file the plugin holds. + BUNDLE_STEP_READ = 3; + /// `BUNDLE` step: opening it for writing, or creating it. + BUNDLE_STEP_OPEN = 4; + /// `BUNDLE` step: writing its bytes. + BUNDLE_STEP_WRITE = 5; + /// `BUNDLE` step: setting its length, which cuts an older file's + /// tail. + BUNDLE_STEP_LENGTH = 6; + /// `BUNDLE` step: flushing it to disk. + BUNDLE_STEP_SYNC = 7; + /// `BUNDLE` step: closing it. + BUNDLE_STEP_CLOSE = 8; + /// `BUNDLE` step: reading it back. + BUNDLE_STEP_VERIFY = 9; + /// `BUNDLE` step: it read back with another length or digest. + BUNDLE_STEP_DIFFERS = 10; + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_bundle_failure_names_its_step_and_errno() { + let raw = |step: u64, errno: u64| { + window::BUNDLE_FAILED + | step << window::BUNDLE_STEP_SHIFT + | errno << window::BUNDLE_ERRNO_SHIFT + }; + let failure = |value| match BundleReport::from_raw(value) { + Some(BundleReport::Failed(failure)) => failure, + other => panic!("{value:#x}: {other:?}"), + }; + let write = failure(raw(window::BUNDLE_STEP_WRITE, 28)); + assert_eq!( + write, + BundleFailure { + step: BundleStep::Write, + errno: 28 + } + ); + assert_eq!( + alloc::format!("{write}"), + "writing the file failed with ENOSPC (28)" + ); + let differs = failure(raw(window::BUNDLE_STEP_DIFFERS, 0)); + assert_eq!( + alloc::format!("{differs}"), + "a file it wrote reads back unlike its own" + ); + let odd = failure(raw(window::BUNDLE_STEP_LENGTH, 0x1234)); + assert_eq!( + alloc::format!("{odd}"), + "setting the file's length failed with errno 4660" + ); + for (value, step) in BundleStep::ALL { + assert_eq!(failure(raw(value, 5)).step, step); + } + // A failure names a known step; no other report has the fields. + for value in [ + window::BUNDLE_FAILED, + raw(0, 5), + raw(11, 5), + raw(window::BUNDLE_STEP_WRITE, 5) | 1 << 32, + window::BUNDLE_CURRENT | window::BUNDLE_STEP_WRITE << window::BUNDLE_STEP_SHIFT, + window::BUNDLE_UPDATED | 5 << window::BUNDLE_ERRNO_SHIFT, + 0, + 5, + ] { + assert_eq!(BundleReport::from_raw(value), None, "{value:#x}"); + } + assert_eq!( + BundleReport::from_raw(window::BUNDLE_UPDATED), + Some(BundleReport::Updated) + ); } } diff --git a/guest/stela-gpu/kext/file_rewrite.h b/guest/stela-gpu/kext/file_rewrite.h new file mode 100644 index 0000000000..f0d356ef68 --- /dev/null +++ b/guest/stela-gpu/kext/file_rewrite.h @@ -0,0 +1,67 @@ +/* + * The steps of rewriting a file in place, in C without a library, so the + * kext (files.cpp) and the host's tests (tests/file_rewrite.c) run the same + * code. A failure names its step by the gate's `BUNDLE_STEP_` values. + * + * The kernel's vnode_open creates a file for O_CREAT but leaves an existing + * one's length alone whatever O_TRUNC says: it is vn_open_auth alone, and + * the open syscall (open1) is what sets the length to 0 after vn_open_auth + * returns. So a rewrite sets the length itself, after the bytes: a shorter + * file written over a longer one otherwise keeps the longer one's tail. + * + * The includer defines, over its file interface and before including this: + * stela_rewrite_open(file): opens or creates the file for writing + * stela_rewrite_write(file, bytes, offset, count, &left): writes `count` + * bytes at `offset`, `left` of them unwritten + * stela_rewrite_resize(file, length): sets the length + * stela_rewrite_sync(file): flushes the bytes and length to the disk + * stela_rewrite_close(file): closes what the open opened + * each answering 0 or an errno, and STELA_REWRITE_SHORT, the errno a write + * that left bytes unwritten without an error answers. + */ +#pragma once + +#include + +/* The bytes written at a time. */ +#define STELA_REWRITE_CHUNK (64 * 1024) + +/* + * Writes `length` bytes of `bytes` as the whole of `file`. On failure, answers + * the errno and sets `step` to the step that failed; the file is then neither + * the old content nor the new, and the next rewrite replaces it. + */ +static inline int +stela_rewrite(void *file, const unsigned char *bytes, unsigned long length, unsigned *step) +{ + *step = STELA_GATE_BUNDLE_STEP_OPEN; + int error = stela_rewrite_open(file); + if (error) { + return error; + } + *step = STELA_GATE_BUNDLE_STEP_WRITE; + for (unsigned long offset = 0; !error && offset < length;) { + unsigned long rest = length - offset; + int count = rest < STELA_REWRITE_CHUNK ? (int)rest : STELA_REWRITE_CHUNK; + int left = 0; + error = stela_rewrite_write(file, bytes + offset, offset, count, &left); + if (!error && left != 0) { + error = STELA_REWRITE_SHORT; + } + offset += (unsigned long)count; + } + if (!error) { + *step = STELA_GATE_BUNDLE_STEP_LENGTH; + error = stela_rewrite_resize(file, length); + } + if (!error) { + *step = STELA_GATE_BUNDLE_STEP_SYNC; + error = stela_rewrite_sync(file); + } + int closed = stela_rewrite_close(file); + if (!error && closed) { + *step = STELA_GATE_BUNDLE_STEP_CLOSE; + error = closed; + } + return error; +} diff --git a/guest/stela-gpu/kext/files.cpp b/guest/stela-gpu/kext/files.cpp index f1659729c6..1b292a694f 100644 --- a/guest/stela-gpu/kext/files.cpp +++ b/guest/stela-gpu/kext/files.cpp @@ -3,6 +3,8 @@ #include #include #include +#include +#include /* * Opens `path` without following its last component, and only as a regular @@ -75,29 +77,68 @@ stelaMatches(const char *path, const unsigned char sha256[SHA256_DIGEST_LENGTH], return error; } +namespace { +/* The file a rewrite opens, through the vnode KPI. */ +struct Rewrite { + const char *path; + int mode; + vfs_context_t context; + vnode_t vnode; +}; +} // namespace + +#define STELA_REWRITE_SHORT EIO + +static int +stela_rewrite_open(void *file) +{ + auto rewrite = static_cast(file); + // No O_TRUNC, which vnode_open ignores: the rewrite sets the length. + return openRegular(rewrite->path, FWRITE | O_CREAT, rewrite->mode, &rewrite->vnode, rewrite->context); +} + +static int +stela_rewrite_write(void *file, const unsigned char *bytes, unsigned long offset, int count, int *left) +{ + auto rewrite = static_cast(file); + // A write does not modify its source. + return vn_rdwr(UIO_WRITE, rewrite->vnode, const_cast(reinterpret_cast(bytes)), count, + off_t(offset), UIO_SYSSPACE, IO_NOAUTH, vfs_context_ucred(rewrite->context), left, + vfs_context_proc(rewrite->context)); +} + +static int +stela_rewrite_resize(void *file, unsigned long length) +{ + auto rewrite = static_cast(file); + struct vnode_attr attributes; + VATTR_INIT(&attributes); + VATTR_SET(&attributes, va_data_size, off_t(length)); + return vnode_setattr(rewrite->vnode, &attributes, rewrite->context); +} + +static int +stela_rewrite_sync(void *file) +{ + auto rewrite = static_cast(file); + return VNOP_FSYNC(rewrite->vnode, MNT_WAIT, rewrite->context); +} + +static int +stela_rewrite_close(void *file) +{ + auto rewrite = static_cast(file); + return vnode_close(rewrite->vnode, FWRITE, rewrite->context); +} + +#include "file_rewrite.h" + int stelaWriteFile(const char *path, const unsigned char *bytes, unsigned long length, unsigned mode, - vfs_context_t context) + vfs_context_t context, unsigned *step) { - vnode_t vnode = NULLVP; - int error = openRegular(path, FWRITE | O_CREAT | O_TRUNC, int(mode), &vnode, context); - if (error) { - return error; - } - for (unsigned long offset = 0; !error && offset < length;) { - int chunk = int(IOMin(length - offset, (unsigned long)kStelaChunk)); - int left = 0; - // A write does not modify its source. - error = vn_rdwr(UIO_WRITE, vnode, const_cast(reinterpret_cast(bytes + offset)), - chunk, offset, UIO_SYSSPACE, IO_NOAUTH | IO_SYNC, vfs_context_ucred(context), &left, - vfs_context_proc(context)); - if (!error && left != 0) { - error = EIO; - } - offset += chunk; - } - int closed = vnode_close(vnode, FWRITE, context); - return error ? error : closed; + Rewrite rewrite{path, int(mode), context, NULLVP}; + return stela_rewrite(&rewrite, bytes, length, step); } int @@ -140,7 +181,8 @@ stelaStage(const char *path, const unsigned char *bytes, unsigned long length, if (error && error != ENOENT) { return error; } - error = stelaWriteFile(path, bytes, length, mode, context); + unsigned step = 0; + error = stelaWriteFile(path, bytes, length, mode, context, &step); if (!error) { error = stelaMatches(path, sha256, length, context, buffer, &same); } diff --git a/guest/stela-gpu/kext/files.h b/guest/stela-gpu/kext/files.h index 1045d07dd2..6e2d8abb20 100644 --- a/guest/stela-gpu/kext/files.h +++ b/guest/stela-gpu/kext/files.h @@ -6,6 +6,8 @@ * The kernel exports vnode_open, vn_rdwr and vnode_lookup to kexts, but * nothing that creates, renames or removes a directory or a name: a kext can * create a file in an existing directory and rewrite one in place, no more. + * vnode_open also leaves O_TRUNC to the open syscall, so a rewrite sets the + * file's length through vnode_setattr (file_rewrite.h). * VNOP_MKDIR, VNOP_CREATE, VNOP_RENAME, VNOP_REMOVE and VNOP_SYMLINK are * XNU_KERNEL_PRIVATE in sys/vnode_if.h and absent from com.apple.kernel's * symbol table, which the auxiliary collection binds a kext's undefined @@ -39,9 +41,13 @@ int stelaDigestFile(const char *path, vfs_context_t context, char *buffer, int stelaMatches(const char *path, const unsigned char sha256[SHA256_DIGEST_LENGTH], unsigned long length, vfs_context_t context, char *buffer, bool *same); -/* Writes `length` bytes to `path` in place, creating it with `mode` if absent. */ +/* + * Makes `path` hold exactly `length` bytes, rewriting it in place or creating + * it with `mode`; a failure sets `step` to the gate's `BUNDLE_STEP_` value of + * the step that failed (file_rewrite.h). + */ int stelaWriteFile(const char *path, const unsigned char *bytes, unsigned long length, unsigned mode, - vfs_context_t context); + vfs_context_t context, unsigned *step); /* * Reads all of `path` into `buffer` of `capacity` bytes, answering EFBIG diff --git a/guest/stela-gpu/kext/install.cpp b/guest/stela-gpu/kext/install.cpp index 2fbc113ff6..20f9906754 100644 --- a/guest/stela-gpu/kext/install.cpp +++ b/guest/stela-gpu/kext/install.cpp @@ -4,14 +4,21 @@ * ever loads the plugin whose code this boot's trust cache lists. * * The kernel lets a kext open, create and write files but not create - * directories. The kext rewrites a stale file in place, which keeps its - * inode with its restricted flag and extended attributes, and creates a + * directories or rename. The kext rewrites a stale file in place, which keeps + * its inode with its restricted flag and extended attributes, and creates a * missing one; a plugin whose directories are absent it reports instead. + * + * A failed rewrite leaves a file that is neither the old plugin nor the new, + * which the boot then stops for, naming the step and errno. Keeping the old + * bytes would not let this boot go on, since its trust cache lists only the + * new plugin's code, and every later boot finds the file unlike its own and + * rewrites it whole, so nothing a failure leaves outlasts the next boot. */ #include "StelaGPU.h" #include "app_delivery.h" #include "compression.h" #include "files.h" +#include "install_report.h" #include #include @@ -29,6 +36,18 @@ static const char kPlugin[] = "/System/Volumes/Data/Library/GPUBundles/StelaGPU. /* How often the installer looks for the Data volume, in milliseconds. */ static const unsigned kMountPoll = 50; +/* Logs a failure at `step` of `path` with `error` and answers its report. */ +static uint64_t +failed(unsigned step, const char *path, int error) +{ + if (step == STELA_GATE_BUNDLE_STEP_DIFFERS) { + IOLog("StelaGPU: %s reads back unlike stela.efi's after it was written\n", path); + } else { + IOLog("StelaGPU: %s %s failed: %d\n", stela_bundle_step_name(step), path, error); + } + return stela_bundle_failure(step, error); +} + /* Installs each file that differs, answering the gate's BUNDLE report. */ static uint64_t install(vfs_context_t context, char *buffer) @@ -38,8 +57,7 @@ install(vfs_context_t context, char *buffer) char path[256]; int written = snprintf(path, sizeof path, "%s%s", kPlugin, file.path); if (written < 0 || size_t(written) >= sizeof path) { - IOLog("StelaGPU: the plugin path for %s is too long\n", file.path); - return STELA_GATE_BUNDLE_FAILED; + return failed(STELA_GATE_BUNDLE_STEP_PATH, file.path, ENAMETOOLONG); } bool same = false; int error = stelaMatches(path, file.sha256, file.length, context, buffer, &same); @@ -47,23 +65,23 @@ install(vfs_context_t context, char *buffer) continue; } if (error && error != ENOENT) { - IOLog("StelaGPU: reading %s failed: %d\n", path, error); - return STELA_GATE_BUNDLE_FAILED; + return failed(STELA_GATE_BUNDLE_STEP_READ, path, error); } - error = stelaWriteFile(path, file.bytes, file.length, file.mode, context); - if (error == ENOENT) { + unsigned step = 0; + error = stelaWriteFile(path, file.bytes, file.length, file.mode, context, &step); + if (error == ENOENT && step == STELA_GATE_BUNDLE_STEP_OPEN) { IOLog("StelaGPU: %s cannot be created: its directory is absent\n", path); return STELA_GATE_BUNDLE_MISSING; } - if (!error) { - error = stelaMatches(path, file.sha256, file.length, context, buffer, &same); - } - if (!error && !same) { - error = EIO; - } if (error) { - IOLog("StelaGPU: writing %s failed: %d\n", path, error); - return STELA_GATE_BUNDLE_FAILED; + return failed(step, path, error); + } + error = stelaMatches(path, file.sha256, file.length, context, buffer, &same); + if (error) { + return failed(STELA_GATE_BUNDLE_STEP_VERIFY, path, error); + } + if (!same) { + return failed(STELA_GATE_BUNDLE_STEP_DIFFERS, path, 0); } IOLog("StelaGPU: installed %s from stela.efi\n", path); report = STELA_GATE_BUNDLE_UPDATED; @@ -84,7 +102,7 @@ void StelaGPU::installPlugin(void *parameter, wait_result_t) { auto gpu = static_cast(parameter); - uint64_t report = STELA_GATE_BUNDLE_FAILED; + uint64_t report = stela_bundle_failure(STELA_GATE_BUNDLE_STEP_ALLOCATE, ENOMEM); vfs_context_t context = vfs_context_create(nullptr); auto buffer = static_cast(IOMallocData(kStelaChunk)); bool stopping = false; diff --git a/guest/stela-gpu/kext/install_report.h b/guest/stela-gpu/kext/install_report.h new file mode 100644 index 0000000000..d39b303fff --- /dev/null +++ b/guest/stela-gpu/kext/install_report.h @@ -0,0 +1,47 @@ +/* + * The gate's BUNDLE report of a failed installation of the Metal plugin, in C + * without a library, so the kext (install.cpp) and the host's tests + * (tests/file_rewrite.c) run the same code: the step that failed, by the + * gate's `BUNDLE_STEP_` values, and the kernel's errno. + */ +#pragma once + +#include + +/* The gate's BUNDLE report of a failure at `step` with `error`. */ +static inline unsigned long long +stela_bundle_failure(unsigned step, int error) +{ + return STELA_GATE_BUNDLE_FAILED | (unsigned long long)(step & 0xff) << STELA_GATE_BUNDLE_STEP_SHIFT | + (unsigned long long)(error & 0xffff) << STELA_GATE_BUNDLE_ERRNO_SHIFT; +} + +/* What the kext was doing at `step`, for its log line. */ +static inline const char * +stela_bundle_step_name(unsigned step) +{ + switch (step) { + case STELA_GATE_BUNDLE_STEP_ALLOCATE: + return "allocating for"; + case STELA_GATE_BUNDLE_STEP_PATH: + return "spelling the path of"; + case STELA_GATE_BUNDLE_STEP_READ: + return "reading"; + case STELA_GATE_BUNDLE_STEP_OPEN: + return "opening"; + case STELA_GATE_BUNDLE_STEP_WRITE: + return "writing"; + case STELA_GATE_BUNDLE_STEP_LENGTH: + return "setting the length of"; + case STELA_GATE_BUNDLE_STEP_SYNC: + return "flushing"; + case STELA_GATE_BUNDLE_STEP_CLOSE: + return "closing"; + case STELA_GATE_BUNDLE_STEP_VERIFY: + return "reading back"; + case STELA_GATE_BUNDLE_STEP_DIFFERS: + return "checking"; + default: + return "installing"; + } +} diff --git a/guest/stela-gpu/kext/tests/file_rewrite.c b/guest/stela-gpu/kext/tests/file_rewrite.c new file mode 100644 index 0000000000..4d7785c40d --- /dev/null +++ b/guest/stela-gpu/kext/tests/file_rewrite.c @@ -0,0 +1,234 @@ +/* + * Host tests of file_rewrite.h and install_report.h, which the kext compiles + * unchanged. xtask's `guest::app::tests::the_kext_c_code_passes_its_host_tests` + * builds and runs this with the host's clang, with the gate.h the kext + * builds against; it prints each failing check. + * + * The file model is the kernel's vnode KPI as the kext meets it: an open + * creates an absent file and leaves an existing one's bytes and length, as + * vnode_open does whatever O_TRUNC says, and only a resize cuts a tail. + */ +#include +#include +#include + +#define CAPACITY (300 * 1024) + +struct file { + int exists; + int open; + unsigned long length; + unsigned char bytes[CAPACITY]; + /* The errno each step answers, and the write call that fails. */ + int fail_open, fail_write, fail_resize, fail_sync, fail_close; + int failing_write; + /* A write that leaves bytes unwritten without an error. */ + int short_write; + int writes, closes, syncs; +}; + +static int +stela_rewrite_open(void *opaque) +{ + struct file *file = opaque; + if (file->fail_open) { + return file->fail_open; + } + file->exists = 1; + file->open = 1; + return 0; +} + +static int +stela_rewrite_write(void *opaque, const unsigned char *bytes, unsigned long offset, int count, int *left) +{ + struct file *file = opaque; + if (!file->open || offset + (unsigned long)count > CAPACITY) { + return EFAULT; + } + if (++file->writes == file->failing_write) { + return file->fail_write; + } + if (file->short_write && file->writes == file->failing_write + 1) { + count -= 1; + *left = 1; + } + memcpy(file->bytes + offset, bytes, (size_t)count); + if (offset + (unsigned long)count > file->length) { + file->length = offset + (unsigned long)count; + } + return 0; +} + +static int +stela_rewrite_resize(void *opaque, unsigned long length) +{ + struct file *file = opaque; + if (file->fail_resize) { + return file->fail_resize; + } + if (length > file->length) { + memset(file->bytes + file->length, 0, length - file->length); + } + file->length = length; + return 0; +} + +static int +stela_rewrite_sync(void *opaque) +{ + struct file *file = opaque; + file->syncs++; + return file->fail_sync; +} + +static int +stela_rewrite_close(void *opaque) +{ + struct file *file = opaque; + file->open = 0; + file->closes++; + return file->fail_close; +} + +#define STELA_REWRITE_SHORT EIO + +#include "../file_rewrite.h" +#include "../install_report.h" + +static int failures; + +#define CHECK(condition) \ + do { \ + if (!(condition)) { \ + printf("%s:%d: %s\n", __FILE__, __LINE__, #condition); \ + failures++; \ + } \ + } while (0) + +static struct file file; +static unsigned char old[CAPACITY], new[CAPACITY]; + +/* A file that holds `length` bytes of `old`, with no failures planned. */ +static void +existing(unsigned long length) +{ + memset(&file, 0, sizeof file); + file.exists = 1; + file.length = length; + memcpy(file.bytes, old, length); +} + +static int +holds(const unsigned char *bytes, unsigned long length) +{ + return file.length == length && !memcmp(file.bytes, bytes, length); +} + +/* + * A plugin written over one 16 bytes longer, as a stela.efi with an older + * plugin met a newer one's: the longer one's tail stayed, so the file read + * back 16 bytes long and the boot stopped. + */ +static void +shorter_over_longer(void) +{ + unsigned step = 0; + existing(CAPACITY); + CHECK(!stela_rewrite(&file, new, CAPACITY - 16, &step)); + CHECK(holds(new, CAPACITY - 16)); + CHECK(file.closes == 1 && file.syncs == 1 && !file.open); + /* Every size against every other, around the chunk. */ + const unsigned long sizes[] = {1, STELA_REWRITE_CHUNK - 1, STELA_REWRITE_CHUNK, STELA_REWRITE_CHUNK + 1, + 2 * STELA_REWRITE_CHUNK + 16, CAPACITY}; + for (unsigned i = 0; i < sizeof sizes / sizeof sizes[0]; i++) { + for (unsigned j = 0; j < sizeof sizes / sizeof sizes[0]; j++) { + existing(sizes[i]); + CHECK(!stela_rewrite(&file, new, sizes[j], &step)); + CHECK(holds(new, sizes[j])); + } + } +} + +static void +creates_an_absent_file(void) +{ + unsigned step = 0; + memset(&file, 0, sizeof file); + CHECK(!stela_rewrite(&file, new, 100, &step)); + CHECK(file.exists && holds(new, 100)); +} + +/* Each step's failure names that step and its errno, and closes once. */ +static void +failures_name_their_step(void) +{ + unsigned step = 0; + existing(1000); + file.fail_open = ENOENT; + CHECK(stela_rewrite(&file, new, 10, &step) == ENOENT && step == STELA_GATE_BUNDLE_STEP_OPEN); + CHECK(file.closes == 0 && holds(old, 1000)); + + existing(1000); + file.failing_write = 2; + file.fail_write = ENOSPC; + CHECK(stela_rewrite(&file, new, 3 * STELA_REWRITE_CHUNK, &step) == ENOSPC); + CHECK(step == STELA_GATE_BUNDLE_STEP_WRITE && file.writes == 2 && file.closes == 1 && !file.syncs); + + existing(1000); + file.failing_write = 0; + file.short_write = 1; + CHECK(stela_rewrite(&file, new, 3 * STELA_REWRITE_CHUNK, &step) == STELA_REWRITE_SHORT); + CHECK(step == STELA_GATE_BUNDLE_STEP_WRITE && file.writes == 1 && file.closes == 1); + + existing(1000); + file.fail_resize = EPERM; + CHECK(stela_rewrite(&file, new, 10, &step) == EPERM && step == STELA_GATE_BUNDLE_STEP_LENGTH); + CHECK(file.closes == 1 && !file.syncs); + + existing(1000); + file.fail_sync = EIO; + CHECK(stela_rewrite(&file, new, 10, &step) == EIO && step == STELA_GATE_BUNDLE_STEP_SYNC); + CHECK(file.closes == 1); + + existing(1000); + file.fail_close = EIO; + CHECK(stela_rewrite(&file, new, 10, &step) == EIO && step == STELA_GATE_BUNDLE_STEP_CLOSE); + + /* The first failure is the one named, not the close after it. */ + existing(1000); + file.fail_resize = EROFS; + file.fail_close = EIO; + CHECK(stela_rewrite(&file, new, 10, &step) == EROFS && step == STELA_GATE_BUNDLE_STEP_LENGTH); +} + +/* The report word is the one stela_contracts::gate::BundleReport reads. */ +static void +reports(void) +{ + CHECK(stela_bundle_failure(STELA_GATE_BUNDLE_STEP_WRITE, ENOSPC) == 0x1c0504ULL); + CHECK(stela_bundle_failure(STELA_GATE_BUNDLE_STEP_DIFFERS, 0) == 0xa04ULL); + CHECK(stela_bundle_failure(STELA_GATE_BUNDLE_STEP_ALLOCATE, ENOMEM) == 0xc0104ULL); + for (unsigned step = STELA_GATE_BUNDLE_STEP_ALLOCATE; step <= STELA_GATE_BUNDLE_STEP_DIFFERS; step++) { + CHECK(strcmp(stela_bundle_step_name(step), "installing") != 0); + } + CHECK(!strcmp(stela_bundle_step_name(0), "installing")); +} + +int +main(void) +{ + for (unsigned long i = 0; i < CAPACITY; i++) { + old[i] = (unsigned char)(i * 7 + 1); + new[i] = (unsigned char)(i * 13 + 5); + } + shorter_over_longer(); + creates_an_absent_file(); + failures_name_their_step(); + reports(); + if (failures) { + return 1; + } + printf("ok\n"); + return 0; +} diff --git a/xtask/src/guest/app/tests.rs b/xtask/src/guest/app/tests.rs index db0d901746..a76106ac64 100644 --- a/xtask/src/guest/app/tests.rs +++ b/xtask/src/guest/app/tests.rs @@ -294,14 +294,24 @@ fn the_job_installs_only_on_the_kexts_staged_report() { } /// Builds `guest/stela-gpu/kext/tests/.c` with the `clang` on PATH, a -/// hosted program that needs none of the build's other LLVM tools. +/// hosted program that needs none of the build's other LLVM tools, against +/// the `stela/gate.h` the kext builds with. fn kext_test(name: &str, built: &Path) -> PathBuf { let clang = crate::tools::which("clang").expect("a clang on PATH for the kext's host tests"); let source = crate::tools::root().join(format!("guest/stela-gpu/kext/tests/{name}.c")); + let include = built.join("include"); + fs::create_dir_all(include.join("stela")).unwrap(); + fs::write( + include.join("stela/gate.h"), + crate::guest::sdk::gate_header(), + ) + .unwrap(); let program = built.join(name); crate::tools::exec( Command::new(clang) - .args(["-std=c17", "-Wall", "-Wextra", "-Werror", "-o"]) + .args(["-std=c17", "-Wall", "-Wextra", "-Werror", "-I"]) + .arg(&include) + .arg("-o") .arg(&program) .arg(source), ) @@ -315,6 +325,7 @@ fn the_kext_c_code_passes_its_host_tests() { for name in [ "app_policy", "compression_policy", + "file_rewrite", "host_record", "plugin_report", ] { diff --git a/xtask/src/guest/sdk.rs b/xtask/src/guest/sdk.rs index 1cf373918d..d45894a903 100644 --- a/xtask/src/guest/sdk.rs +++ b/xtask/src/guest/sdk.rs @@ -205,7 +205,7 @@ fn without_parentheses(text: &str) -> String { .collect() } -fn gate_header() -> String { +pub(crate) fn gate_header() -> String { let mut header = String::from( "/* The StelaGPU gate window's layout, from stela_contracts::gate::window. */\n\ #pragma once\n",