phoebus_os/installer-rs/crates/phoebus-executor/src/live_nvidia.rs

805 lines
30 KiB
Rust

//! Validation and recording of the NVIDIA payload bundled in the live ISO.
//!
//! The live medium must already contain the driver's kernel modules (built for
//! the exact live kernel), userspace libraries, Wayland/EGL/GBM integration and
//! firmware: nothing is compiled or downloaded at boot. This verifier runs on
//! the assembled rootfs on every build, including a `PHOEBUS_REUSE_ROOTFS=1`
//! build, so a cached rootfs can never silently ship without the payload.
use std::path::{Path, PathBuf};
use phoebus_core::nvidia::NvidiaModuleFlavor;
use crate::error::{ExecError, Result};
/// What was found in the live rootfs. Written verbatim into
/// `/etc/phoebus/nvidia` so the bundled versions are inspectable on the medium.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LiveNvidiaPayload {
pub kernel_version: String,
pub driver_version: String,
pub flavor: String,
pub modules: Vec<String>,
pub userspace: Vec<String>,
pub firmware: Vec<String>,
}
impl LiveNvidiaPayload {
/// The `/etc/phoebus/nvidia` record.
pub fn record(&self) -> String {
let mut o = String::new();
o.push_str("# NVIDIA payload bundled in the Phoebus live medium.\n");
o.push_str("# Generated at build time; proves the ISO carries a driver\n");
o.push_str("# matching the live kernel instead of compiling one at boot.\n");
o.push_str(&format!("kernel_version={}\n", self.kernel_version));
o.push_str(&format!("driver_version={}\n", self.driver_version));
o.push_str(&format!("flavor={}\n", self.flavor));
for module in &self.modules {
o.push_str(&format!("module={module}\n"));
}
for lib in &self.userspace {
o.push_str(&format!("userspace={lib}\n"));
}
for fw in &self.firmware {
o.push_str(&format!("firmware={fw}\n"));
}
o
}
pub fn render(&self) -> String {
format!(
"NVIDIA live payload OK: driver {} ({}) for kernel {}; modules: {}; \
{} userspace file(s); {} firmware file(s)",
self.driver_version,
self.flavor,
self.kernel_version,
self.modules.join(", "),
self.userspace.len(),
self.firmware.len()
)
}
}
fn fail(message: String) -> ExecError {
ExecError::operation("live", "verify nvidia payload", message)
}
/// The one kernel directory that contains `modules.dep`.
///
/// Debian is merged-usr: `/lib` is a symlink to `usr/lib`, so both module roots
/// describe the same kernel. Versions are deduplicated so a merged-usr rootfs
/// is not mistaken for a multi-kernel image.
fn kernel_version(rootfs: &Path) -> Result<String> {
let mut candidates: std::collections::BTreeMap<String, PathBuf> =
std::collections::BTreeMap::new();
for modules_root in ["lib/modules", "usr/lib/modules"] {
let dir = rootfs.join(modules_root);
let Ok(entries) = std::fs::read_dir(&dir) else {
continue;
};
for entry in entries.flatten() {
let path = entry.path();
if !path.is_dir() || !path.join("modules.dep").exists() {
continue;
}
// Prefer a kernel that the live medium actually ships a vmlinuz for,
// so a stale build-only module tree cannot satisfy the check.
let version = entry.file_name().to_string_lossy().to_string();
if rootfs.join(format!("boot/vmlinuz-{version}")).exists() {
candidates.entry(version).or_insert(path);
}
}
}
match candidates.len() {
0 => Err(fail(
"no kernel with modules.dep and a matching /boot/vmlinuz was found".into(),
)),
1 => Ok(candidates.into_keys().next().unwrap_or_default()),
_ => Err(fail(format!(
"the live rootfs ships multiple kernels ({}); exactly one is expected",
candidates
.keys()
.map(String::as_str)
.collect::<Vec<_>>()
.join(", ")
))),
}
}
/// Walk `root` without following symlinks, collecting `(file name, path)`.
///
/// `DirEntry::file_type` does not follow symlinks, so a symlink inside the
/// rootfs can never make us walk the host, and every returned path is inside
/// `root` by construction.
fn walk_files(root: &Path, out: &mut Vec<(String, PathBuf)>) {
if let Ok(entries) = std::fs::read_dir(root) {
for entry in entries.flatten() {
let path = entry.path();
match entry.file_type() {
Ok(ft) if ft.is_dir() => walk_files(&path, out),
Ok(_) => {
if let Some(name) = path.file_name().and_then(|n| n.to_str()) {
out.push((name.to_string(), path));
}
}
Err(_) => {}
}
}
}
}
/// All files under `root`, as `(name, path)` pairs rooted inside it.
fn files_under(root: &Path) -> Vec<(String, PathBuf)> {
let mut out = Vec::new();
walk_files(root, &mut out);
out
}
/// Directory names directly under `root`.
fn dirs_under(root: &Path) -> Vec<String> {
let mut out = Vec::new();
if let Ok(entries) = std::fs::read_dir(root) {
for entry in entries.flatten() {
if entry.file_type().map(|t| t.is_dir()).unwrap_or(false) {
out.push(entry.file_name().to_string_lossy().to_string());
}
}
}
out
}
/// Read a rootfs-relative file, resolving symlinks **within** the rootfs.
fn read_in_rootfs(rootfs: &Path, rel: &str) -> Option<String> {
let mut current = rootfs.join(rel.trim_start_matches('/'));
for _ in 0..16 {
match std::fs::symlink_metadata(&current) {
Err(_) => return None,
Ok(meta) if meta.file_type().is_symlink() => {
let target = std::fs::read_link(&current).ok()?;
current = if target.is_absolute() {
rootfs.join(target.strip_prefix("/").unwrap_or(&target))
} else {
current.parent().unwrap_or(rootfs).join(target)
};
}
Ok(_) => return std::fs::read_to_string(&current).ok(),
}
}
None
}
/// Size of a file, or 0 when it is missing or unreadable (a broken symlink
/// included, because `metadata` follows symlinks).
fn size_of(path: &Path) -> u64 {
std::fs::metadata(path).map(|m| m.len()).unwrap_or(0)
}
/// The upstream part of a driver version: Debian's `550.163.01-1~deb13u1`
/// becomes `550.163.01`.
fn upstream_version(version: &str) -> &str {
version
.split(['-', '~', '+'])
.next()
.filter(|s| !s.is_empty())
.unwrap_or(version)
}
/// A dotted numeric version embedded in a shared-library name, e.g.
/// `libnvidia-glcore.so.550.163.01` -> `550.163.01`. `libGLX_nvidia.so.0`
/// yields `None` because a bare SONAME is not the driver version.
fn embedded_version(name: &str, prefix: &str) -> Option<String> {
let rest = name.strip_prefix(prefix)?;
let rest = rest.strip_prefix('.')?;
let version = rest.trim_end_matches(|c: char| c.is_ascii_alphabetic());
if version.is_empty()
|| !version.chars().next()?.is_ascii_digit()
|| !version.contains('.')
|| !version.chars().all(|c| c.is_ascii_digit() || c == '.')
{
return None;
}
Some(version.trim_end_matches('.').to_string())
}
/// The flavor a module name implies, when the name is Debian's renamed form.
fn flavor_from_module_name(name: &str) -> Option<&'static str> {
if name.contains("-open") || name.contains("nvidia-open") {
Some("open")
} else if name.starts_with("nvidia-current") {
Some("proprietary")
} else {
None
}
}
/// The logical NVIDIA module and the on-disk names that may provide it. Debian's
/// `nvidia-kernel-dkms` renames the DKMS output to `nvidia-current`,
/// `nvidia-current-modeset`, `nvidia-current-drm` and `nvidia-current-uvm`;
/// Gentoo and NVIDIA's own builds use the upstream names.
fn module_candidates(module: &str) -> Vec<&'static str> {
match module {
"nvidia" => vec!["nvidia", "nvidia-current"],
"nvidia_modeset" => vec!["nvidia_modeset", "nvidia-current-modeset"],
"nvidia_uvm" => vec!["nvidia_uvm", "nvidia-current-uvm"],
"nvidia_drm" => vec!["nvidia_drm", "nvidia-current-drm"],
_ => vec![],
}
}
fn name_matches(file: &str, module: &str) -> bool {
file == format!("{module}.ko") || file.starts_with(&format!("{module}.ko."))
}
/// A real kernel module or shared library is far larger than this. A tiny file
/// is a placeholder that must never satisfy the build gate.
const MIN_BINARY_BYTES: u64 = 4096;
/// Resolve a rootfs-relative path *within* the rootfs. Absolute symlinks are
/// clamped to the rootfs, never resolved against the host.
fn resolve_in_rootfs(rootfs: &Path, rel: &str) -> Option<PathBuf> {
let mut current = rootfs.join(rel.trim_start_matches('/'));
for _ in 0..16 {
match std::fs::symlink_metadata(&current) {
Err(_) => return None,
Ok(meta) if meta.file_type().is_symlink() => {
let target = std::fs::read_link(&current).ok()?;
current = if target.is_absolute() {
rootfs.join(target.strip_prefix("/").unwrap_or(&target))
} else {
current.parent().unwrap_or(rootfs).join(target)
};
}
Ok(_) => return Some(current),
}
}
None
}
/// The on-disk module file for a logical module: `(recorded label, file name,
/// path)`. The label is the canonical `<candidate>.ko`; the file name keeps the
/// compression/renaming suffix for the `modules.dep` check.
fn find_module_file(
files: &[(String, PathBuf)],
module: &str,
) -> Option<(String, String, PathBuf)> {
for candidate in module_candidates(module) {
if let Some((name, path)) = files.iter().find(|(n, _)| name_matches(n, candidate)) {
return Some((format!("{candidate}.ko"), name.clone(), path.clone()));
}
}
None
}
/// Verify that `rootfs` bundles a complete and *self-consistent* NVIDIA payload
/// for the one kernel it boots.
///
/// This is a compatibility gate, not a presence checklist: it rejects an
/// incomplete payload, placeholder files, a module tree built for another
/// kernel, a userspace/firmware version that does not match the bundled driver,
/// a flavor that contradicts the module naming, and a final boot configuration
/// that would not activate the driver. Any mismatch fails the build.
pub fn verify_live_nvidia(
rootfs: &Path,
driver_version: &str,
flavor: NvidiaModuleFlavor,
) -> Result<LiveNvidiaPayload> {
if !rootfs.is_dir() {
return Err(fail(format!(
"live rootfs {} does not exist",
rootfs.display()
)));
}
let kernel = kernel_version(rootfs)?;
let upstream = upstream_version(driver_version).to_string();
// Kernel modules built for exactly this kernel. Both module roots are
// scanned for a merged-usr image and deduplicated by name: `/lib` and
// `/usr/lib` describe the same tree, not two kernels.
let mut module_files: Vec<(String, PathBuf)> = Vec::new();
for modules_root in ["lib/modules", "usr/lib/modules"] {
let dir = rootfs.join(modules_root).join(&kernel);
if dir.is_dir() {
for (name, path) in files_under(&dir) {
if !module_files.iter().any(|(n, _)| n == &name) {
module_files.push((name, path));
}
}
}
}
if module_files.is_empty() {
return Err(fail(format!(
"no modules found for kernel {kernel}; the driver was not built for the live kernel"
)));
}
let required = ["nvidia", "nvidia_modeset", "nvidia_uvm", "nvidia_drm"];
let mut modules = Vec::new();
let mut found: Vec<(String, PathBuf)> = Vec::new();
let mut missing = Vec::new();
for module in required {
match find_module_file(&module_files, module) {
Some((label, file, path)) => {
let size = size_of(&path);
if size < MIN_BINARY_BYTES {
return Err(fail(format!(
"kernel module {file} is a placeholder ({size} bytes); the driver was not built"
)));
}
modules.push(label);
found.push((file, path));
}
None => missing.push(module),
}
}
if !missing.is_empty() {
return Err(fail(format!(
"kernel {kernel} is missing NVIDIA module(s): {}; expected a {flavor:?} build",
missing.join(", ")
)));
}
// Kernel compatibility: modules the kernel cannot resolve are useless. Every
// required module must be registered in this kernel's `modules.dep`.
let dep = read_in_rootfs(rootfs, &format!("lib/modules/{kernel}/modules.dep"))
.or_else(|| read_in_rootfs(rootfs, &format!("usr/lib/modules/{kernel}/modules.dep")))
.ok_or_else(|| {
fail(format!(
"kernel {kernel} has no readable modules.dep; the module tree is incomplete"
))
})?;
for (file, _) in &found {
if !dep.contains(file.as_str()) {
return Err(fail(format!(
"kernel {kernel} modules.dep does not register {file}; the driver was not built for this kernel"
)));
}
}
// Establish the actual flavor from the on-disk naming and reject a payload
// whose naming contradicts the flavor the build claims.
if let Some(observed) = found
.iter()
.find_map(|(file, _)| flavor_from_module_name(file))
{
if observed != flavor.as_str() {
return Err(fail(format!(
"the modules are a {observed} build but a {} payload was expected",
flavor.as_str()
)));
}
}
// Userspace: GLVND/GLX libraries, the management tool, and the Wayland/GBM
// EGL external-platform integration.
let lib_files = files_under(&rootfs.join("usr/lib"));
let mut userspace = Vec::new();
let mut missing_lib = Vec::new();
let mut glcore_version: Option<String> = None;
for prefix in [
"libnvidia-glcore.so",
"libGLX_nvidia.so",
"libnvidia-egl-gbm.so",
"libnvidia-egl-wayland.so",
] {
match lib_files.iter().find(|(n, _)| n.starts_with(prefix)) {
Some((name, path)) => {
let size = size_of(path);
if size < MIN_BINARY_BYTES {
return Err(fail(format!(
"userspace library {name} is a placeholder ({size} bytes)"
)));
}
if prefix == "libnvidia-glcore.so" {
glcore_version = embedded_version(name, prefix);
}
userspace.push(prefix.to_string());
}
None => missing_lib.push(prefix),
}
}
if !missing_lib.is_empty() {
return Err(fail(format!(
"userspace NVIDIA libraries are missing: {}",
missing_lib.join(", ")
)));
}
// The userspace driver version must match the module/firmware version, or
// the accelerated stack fails with an API mismatch.
if let Some(found_version) = &glcore_version {
if found_version != &upstream {
return Err(fail(format!(
"userspace library version {found_version} does not match the bundled driver {upstream}"
)));
}
}
match resolve_in_rootfs(rootfs, "usr/bin/nvidia-smi") {
Some(path) if size_of(&path) > 0 => userspace.push("nvidia-smi".into()),
Some(_) => return Err(fail("usr/bin/nvidia-smi is empty".into())),
None => {
return Err(fail(
"usr/bin/nvidia-smi is missing (nvidia-smi package not installed)".into(),
))
}
}
// EGL external-platform manifests drive Wayland/GBM interop.
let egl = files_under(&rootfs.join("usr/share/egl/egl_external_platform.d"));
for required_json in ["15_nvidia_gbm.json", "10_nvidia_wayland.json"] {
match egl.iter().find(|(n, _)| n == required_json) {
Some((_, path)) if size_of(path) > 0 => userspace.push(required_json.to_string()),
_ => {
return Err(fail(format!(
"EGL external-platform manifest {required_json} is missing or empty under usr/share/egl/egl_external_platform.d"
)))
}
}
}
// Firmware (GSP) is mandatory for the module to initialise, and its version
// directory names the driver it was built for.
let fw_root = rootfs.join("usr/lib/firmware/nvidia");
if files_under(&fw_root).is_empty() {
return Err(fail(
"no NVIDIA firmware found under usr/lib/firmware/nvidia (firmware-nvidia-gsp/graphics not installed)"
.into(),
));
}
let versions = dirs_under(&fw_root);
if !versions.is_empty() && !versions.iter().any(|v| v == &upstream) {
return Err(fail(format!(
"firmware directory {} does not match the bundled driver {upstream}",
versions.join(", ")
)));
}
let gsp: Vec<(String, PathBuf)> = files_under(&fw_root)
.into_iter()
.filter(|(n, _)| n.starts_with("gsp"))
.collect();
if gsp.is_empty() || gsp.iter().all(|(_, p)| size_of(p) == 0) {
return Err(fail(
"no non-empty GSP firmware (gsp_*.bin) found under usr/lib/firmware/nvidia".into(),
));
}
let firmware: Vec<String> = files_under(&fw_root)
.into_iter()
.filter(|(_, p)| size_of(p) > 0)
.map(|(n, _)| n)
.take(16)
.collect();
// The live-only load script must be present; a machine without an NVIDIA
// GPU must never record a failed unit.
let load =
resolve_in_rootfs(rootfs, "usr/local/bin/phoebus-nvidia-load").filter(|p| size_of(p) > 0);
if load.is_none() {
return Err(fail(
"usr/local/bin/phoebus-nvidia-load is missing or empty (gated driver load)".into(),
));
}
// The final boot configuration must carry the intended policy, not merely
// any nouveau blacklist somewhere: the load script and the fallback both
// depend on this exact file.
let conf = read_in_rootfs(rootfs, "etc/modprobe.d/phoebus-nvidia.conf").ok_or_else(|| {
fail("etc/modprobe.d/phoebus-nvidia.conf is missing; the live driver policy was not installed".into())
})?;
if !conf.contains("blacklist nouveau") {
return Err(fail(
"etc/modprobe.d/phoebus-nvidia.conf does not blacklist nouveau; the driver could be preempted"
.into(),
));
}
if !conf.contains("modeset=1") {
return Err(fail(
"etc/modprobe.d/phoebus-nvidia.conf does not enable nvidia_drm modeset".into(),
));
}
Ok(LiveNvidiaPayload {
kernel_version: kernel,
driver_version: driver_version.to_string(),
flavor: flavor.as_str().to_string(),
modules,
userspace,
firmware,
})
}
#[cfg(test)]
mod tests {
use super::*;
const KVER: &str = "6.16.7-amd64";
const DRIVER: &str = "550.163.01";
fn write_bytes(path: &Path, len: usize) {
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(path, vec![0u8; len]).unwrap();
}
fn touch(path: &Path) {
write_bytes(path, 8192);
}
/// Register every module file under `updates/dkms` in `modules.dep`, so a
/// fixture models a kernel whose module tree is coherent.
fn write_dep(kernel_dir: &Path) {
let dkms = kernel_dir.join("updates/dkms");
let mut lines = Vec::new();
if let Ok(entries) = std::fs::read_dir(&dkms) {
for entry in entries.flatten() {
lines.push(format!(
"updates/dkms/{}:",
entry.file_name().to_string_lossy()
));
}
}
lines.sort();
std::fs::write(kernel_dir.join("modules.dep"), lines.join("\n")).unwrap();
}
fn install_modules(root: &Path) {
let kernel = root.join(format!("lib/modules/{KVER}"));
std::fs::create_dir_all(&kernel).unwrap();
for m in ["nvidia", "nvidia_modeset", "nvidia_uvm", "nvidia_drm"] {
touch(&kernel.join(format!("updates/dkms/{m}.ko")));
}
write_dep(&kernel);
}
fn complete_rootfs(root: &Path) {
touch(&root.join(format!("boot/vmlinuz-{KVER}")));
install_modules(root);
for lib in [
format!("libnvidia-glcore.so.{DRIVER}"),
"libGLX_nvidia.so.0".to_string(),
"libnvidia-egl-gbm.so.1.1.2".to_string(),
"libnvidia-egl-wayland.so.1.1.21".to_string(),
] {
touch(&root.join("usr/lib/x86_64-linux-gnu").join(lib));
}
touch(&root.join("usr/bin/nvidia-smi"));
touch(&root.join("usr/share/egl/egl_external_platform.d/15_nvidia_gbm.json"));
touch(&root.join("usr/share/egl/egl_external_platform.d/10_nvidia_wayland.json"));
touch(&root.join(format!("usr/lib/firmware/nvidia/{DRIVER}/gsp_ga10x.bin")));
touch(&root.join("usr/local/bin/phoebus-nvidia-load"));
let conf = root.join("etc/modprobe.d/phoebus-nvidia.conf");
std::fs::create_dir_all(conf.parent().unwrap()).unwrap();
std::fs::write(&conf, b"blacklist nouveau\noptions nvidia_drm modeset=1\n").unwrap();
}
#[test]
fn complete_payload_is_accepted_and_recorded() {
let dir = tempfile::tempdir().unwrap();
complete_rootfs(dir.path());
let payload =
verify_live_nvidia(dir.path(), DRIVER, NvidiaModuleFlavor::Proprietary).unwrap();
assert_eq!(payload.kernel_version, KVER);
assert_eq!(payload.modules.len(), 4);
let record = payload.record();
assert!(record.contains("driver_version=550.163.01"));
assert!(record.contains("flavor=proprietary"));
}
#[test]
fn a_debian_revision_in_the_version_is_normalised() {
let dir = tempfile::tempdir().unwrap();
complete_rootfs(dir.path());
// The dpkg version carries a Debian revision; the libs and firmware do
// not.
verify_live_nvidia(
dir.path(),
"550.163.01-1~deb13u1",
NvidiaModuleFlavor::Proprietary,
)
.unwrap();
}
#[test]
fn missing_kernel_module_fails_the_build() {
let dir = tempfile::tempdir().unwrap();
complete_rootfs(dir.path());
std::fs::remove_file(
dir.path()
.join(format!("lib/modules/{KVER}/updates/dkms/nvidia_drm.ko")),
)
.unwrap();
let err = verify_live_nvidia(dir.path(), DRIVER, NvidiaModuleFlavor::Proprietary)
.unwrap_err()
.to_string();
assert!(err.contains("nvidia_drm"), "{err}");
}
#[test]
fn missing_userspace_or_firmware_fails() {
let dir = tempfile::tempdir().unwrap();
complete_rootfs(dir.path());
std::fs::remove_file(dir.path().join("usr/bin/nvidia-smi")).unwrap();
assert!(verify_live_nvidia(dir.path(), DRIVER, NvidiaModuleFlavor::Proprietary).is_err());
let dir2 = tempfile::tempdir().unwrap();
std::fs::create_dir_all(dir2.path().join("usr/lib/firmware")).unwrap();
complete_rootfs(dir2.path());
// Remove the firmware tree.
std::fs::remove_dir_all(dir2.path().join("usr/lib/firmware/nvidia")).unwrap();
let err = verify_live_nvidia(dir2.path(), DRIVER, NvidiaModuleFlavor::Proprietary)
.unwrap_err()
.to_string();
assert!(err.contains("firmware"), "{err}");
}
#[test]
fn merged_usr_kernel_roots_are_deduplicated() {
let dir = tempfile::tempdir().unwrap();
complete_rootfs(dir.path());
// Debian is merged-usr: the same kernel tree is visible under both
// /lib/modules and /usr/lib/modules. That must not look like two
// kernels.
let dst = dir.path().join(format!("usr/lib/modules/{KVER}"));
std::fs::create_dir_all(&dst).unwrap();
std::fs::write(dst.join("modules.dep"), b"").unwrap();
for m in ["nvidia", "nvidia_modeset", "nvidia_uvm", "nvidia_drm"] {
touch(&dst.join(format!("updates/dkms/{m}.ko")));
}
let payload =
verify_live_nvidia(dir.path(), DRIVER, NvidiaModuleFlavor::Proprietary).unwrap();
assert_eq!(payload.kernel_version, KVER);
}
#[test]
fn debian_renamed_modules_are_accepted_and_recorded() {
let dir = tempfile::tempdir().unwrap();
complete_rootfs(dir.path());
let kernel = dir.path().join(format!("lib/modules/{KVER}"));
let dkms = kernel.join("updates/dkms");
// Replace the upstream names with Debian's DKMS-renamed output.
for m in ["nvidia", "nvidia_modeset", "nvidia_uvm", "nvidia_drm"] {
std::fs::remove_file(dkms.join(format!("{m}.ko"))).unwrap();
}
for m in [
"nvidia-current",
"nvidia-current-modeset",
"nvidia-current-uvm",
"nvidia-current-drm",
] {
touch(&dkms.join(format!("{m}.ko.xz")));
}
write_dep(&kernel);
let payload =
verify_live_nvidia(dir.path(), DRIVER, NvidiaModuleFlavor::Proprietary).unwrap();
assert!(payload
.modules
.contains(&"nvidia-current-drm.ko".to_string()));
assert!(payload.modules.contains(&"nvidia-current.ko".to_string()));
}
#[test]
fn missing_kernel_is_reported() {
let dir = tempfile::tempdir().unwrap();
std::fs::create_dir_all(dir.path().join(format!("lib/modules/{KVER}"))).unwrap();
std::fs::write(
dir.path().join(format!("lib/modules/{KVER}/modules.dep")),
b"",
)
.unwrap();
let err = verify_live_nvidia(dir.path(), "550", NvidiaModuleFlavor::Proprietary)
.unwrap_err()
.to_string();
assert!(err.contains("vmlinuz"), "{err}");
}
#[test]
fn a_one_byte_module_placeholder_is_rejected() {
let dir = tempfile::tempdir().unwrap();
complete_rootfs(dir.path());
write_bytes(
&dir.path()
.join(format!("lib/modules/{KVER}/updates/dkms/nvidia.ko")),
1,
);
let err = verify_live_nvidia(dir.path(), DRIVER, NvidiaModuleFlavor::Proprietary)
.unwrap_err()
.to_string();
assert!(err.contains("placeholder"), "{err}");
}
#[test]
fn a_one_byte_userspace_placeholder_is_rejected() {
let dir = tempfile::tempdir().unwrap();
complete_rootfs(dir.path());
write_bytes(
&dir.path().join(format!(
"usr/lib/x86_64-linux-gnu/libnvidia-glcore.so.{DRIVER}"
)),
1,
);
let err = verify_live_nvidia(dir.path(), DRIVER, NvidiaModuleFlavor::Proprietary)
.unwrap_err()
.to_string();
assert!(err.contains("placeholder"), "{err}");
}
#[test]
fn a_userspace_version_mismatch_is_rejected() {
let dir = tempfile::tempdir().unwrap();
complete_rootfs(dir.path());
std::fs::rename(
dir.path().join(format!(
"usr/lib/x86_64-linux-gnu/libnvidia-glcore.so.{DRIVER}"
)),
dir.path()
.join("usr/lib/x86_64-linux-gnu/libnvidia-glcore.so.999.0.0"),
)
.unwrap();
let err = verify_live_nvidia(dir.path(), DRIVER, NvidiaModuleFlavor::Proprietary)
.unwrap_err()
.to_string();
assert!(err.contains("does not match"), "{err}");
}
#[test]
fn a_firmware_version_mismatch_is_rejected() {
let dir = tempfile::tempdir().unwrap();
complete_rootfs(dir.path());
std::fs::rename(
dir.path().join(format!("usr/lib/firmware/nvidia/{DRIVER}")),
dir.path().join("usr/lib/firmware/nvidia/999.0"),
)
.unwrap();
let err = verify_live_nvidia(dir.path(), DRIVER, NvidiaModuleFlavor::Proprietary)
.unwrap_err()
.to_string();
assert!(err.contains("does not match"), "{err}");
}
#[test]
fn a_stale_modules_dep_is_rejected() {
let dir = tempfile::tempdir().unwrap();
complete_rootfs(dir.path());
std::fs::write(
dir.path().join(format!("lib/modules/{KVER}/modules.dep")),
b"kernel/other.ko:\n",
)
.unwrap();
let err = verify_live_nvidia(dir.path(), DRIVER, NvidiaModuleFlavor::Proprietary)
.unwrap_err()
.to_string();
assert!(err.contains("modules.dep"), "{err}");
}
#[test]
fn a_contradictory_flavor_is_rejected() {
let dir = tempfile::tempdir().unwrap();
complete_rootfs(dir.path());
let kernel = dir.path().join(format!("lib/modules/{KVER}"));
let dkms = kernel.join("updates/dkms");
// Make the payload unmistakably Debian's proprietary build, then claim
// it is the open one.
for m in ["nvidia", "nvidia_modeset", "nvidia_uvm", "nvidia_drm"] {
std::fs::remove_file(dkms.join(format!("{m}.ko"))).unwrap();
}
for m in [
"nvidia-current",
"nvidia-current-modeset",
"nvidia-current-uvm",
"nvidia-current-drm",
] {
touch(&dkms.join(format!("{m}.ko.xz")));
}
write_dep(&kernel);
let err = verify_live_nvidia(dir.path(), DRIVER, NvidiaModuleFlavor::Open)
.unwrap_err()
.to_string();
assert!(err.contains("proprietary build"), "{err}");
}
#[test]
fn a_missing_final_modprobe_config_is_rejected() {
let dir = tempfile::tempdir().unwrap();
complete_rootfs(dir.path());
std::fs::remove_file(dir.path().join("etc/modprobe.d/phoebus-nvidia.conf")).unwrap();
let err = verify_live_nvidia(dir.path(), DRIVER, NvidiaModuleFlavor::Proprietary)
.unwrap_err()
.to_string();
assert!(err.contains("phoebus-nvidia.conf"), "{err}");
}
}