diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..bbe753b --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,7 @@ +# The workflows pin each action to a commit; this proposes the newer ones, once a month. +version: 2 +updates: + - package-ecosystem: github-actions + directory: / + schedule: + interval: monthly diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 1a877bc..1842499 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -8,6 +8,8 @@ on: branches: [main] pull_request: +# Actions are pinned to a commit, not a tag that can be moved: a build here becomes the setup people +# install. .github/dependabot.yml proposes the newer commits. permissions: contents: read @@ -15,16 +17,18 @@ jobs: test: runs-on: windows-latest steps: - - uses: actions/checkout@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false # Restores the compiled dependencies from the last run on main. Only main saves, so pull requests # read that cache but don't fill the repository's 10 GB with their own. - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 with: save-if: ${{ github.ref == 'refs/heads/main' }} - - run: cargo test --workspace --release + - run: cargo test --workspace --release --locked - run: choco install innosetup --no-progress -y - run: ./scripts/package.ps1 - - uses: actions/upload-artifact@v7 + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: name: camless-setup path: dist/* @@ -33,14 +37,16 @@ jobs: linux: runs-on: ubuntu-22.04 steps: - - uses: actions/checkout@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 with: save-if: ${{ github.ref == 'refs/heads/main' }} - run: sudo apt-get update && sudo apt-get install -y --no-install-recommends libwebkit2gtk-4.1-dev libgtk-3-dev libudev-dev - - run: cargo test --workspace --release + - run: cargo test --workspace --release --locked - run: sh scripts/package-linux.sh - - uses: actions/upload-artifact@v7 + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: name: camless-linux path: dist/camless-linux-x86_64.tar.gz* diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 399084b..15cd125 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -17,11 +17,16 @@ jobs: windows: runs-on: windows-latest steps: - - uses: actions/checkout@v7 - - run: cargo test --workspace --release + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - run: cargo test --workspace --release --locked - run: choco install innosetup --no-progress -y - - run: ./scripts/package.ps1 -Tag "${{ github.ref_name }}" - - uses: actions/upload-artifact@v7 + # The tag through the environment: written into the script, its name would run as part of it. + - run: ./scripts/package.ps1 -Tag "$env:TAG" + env: + TAG: ${{ github.ref_name }} + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: name: windows path: dist/camless-setup.exe* @@ -29,11 +34,15 @@ jobs: linux: runs-on: ubuntu-22.04 steps: - - uses: actions/checkout@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false - run: sudo apt-get update && sudo apt-get install -y --no-install-recommends libwebkit2gtk-4.1-dev libgtk-3-dev libudev-dev - - run: cargo test --workspace --release - - run: sh scripts/package-linux.sh "${{ github.ref_name }}" - - uses: actions/upload-artifact@v7 + - run: cargo test --workspace --release --locked + - run: sh scripts/package-linux.sh "$TAG" + env: + TAG: ${{ github.ref_name }} + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: name: linux path: dist/camless-linux-x86_64.tar.gz* @@ -45,7 +54,7 @@ jobs: permissions: contents: write steps: - - uses: actions/download-artifact@v8 + - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 with: path: dist merge-multiple: true diff --git a/Cargo.lock b/Cargo.lock index 12a5ce0..597cb9b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -885,7 +885,7 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1bd49230192a3797a9a4d6abe9b3eed6f7fa4c8a8a4947977c6f80025f92cbd8" dependencies = [ - "rustix 1.1.5", + "rustix 1.1.6", "windows-link", ] @@ -2129,7 +2129,7 @@ dependencies = [ "concurrent-queue", "hermit-abi", "pin-project-lite", - "rustix 1.1.5", + "rustix 1.1.6", "windows-sys 0.61.2", ] @@ -2319,9 +2319,9 @@ dependencies = [ [[package]] name = "rustix" -version = "1.1.5" +version = "1.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "891efababe418670775f199f0d233d84843c227a0949a883ce15b37c78d6629d" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" dependencies = [ "bitflags 2.13.2", "errno", @@ -3116,7 +3116,7 @@ checksum = "38a91b4eaddff87b1cd1074985e3713da4af2c49742d1b356b2c01670a67a078" dependencies = [ "cc", "downcast-rs", - "rustix 1.1.5", + "rustix 1.1.6", "scoped-tls", "smallvec", "wayland-sys", @@ -3129,7 +3129,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e3c36a0f861ad76d0901f2800b46321410d9f73f2ea88aac0650d86c32688073" dependencies = [ "bitflags 2.13.2", - "rustix 1.1.5", + "rustix 1.1.6", "wayland-backend", "wayland-scanner", ] @@ -3151,7 +3151,7 @@ version = "0.31.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4a52d18780be9b1314328a3de5f930b73d2200112e3849ca6cb11822793fb34d" dependencies = [ - "rustix 1.1.5", + "rustix 1.1.6", "wayland-client", "xcursor", ] @@ -3856,7 +3856,7 @@ dependencies = [ "libc", "libloading 0.8.9", "once_cell", - "rustix 1.1.5", + "rustix 1.1.6", "x11rb-protocol", ] diff --git a/docs/how-it-works.md b/docs/how-it-works.md index bdc2e33..beceaa9 100644 --- a/docs/how-it-works.md +++ b/docs/how-it-works.md @@ -56,7 +56,7 @@ When something this PC needs is missing, the app opens a dialog once each time i ## GPU fans `[devices] gpu`, off unless you turn it on, lets camless set the graphics card's fans. Experimental: nobody has run it on a card yet. Give them a curve on the GPU's temperature. -- On Windows, NVIDIA cards, through NVML (`nvml.dll`, which comes with the driver): `nvmlDeviceSetFanSpeed_v2` sets a fan's duty, within the card's `nvmlDeviceGetMinMaxFanSpeed`, and `nvmlDeviceSetDefaultFanSpeed_v2` gives it back to the card's curve. The rpm comes from `nvmlDeviceGetFanSpeedRPM`, on drivers that have it. Setting a fan needs administrator rights: without them, or on a card whose fans NVML does not set (`NVML_ERROR_NOT_SUPPORTED`, which no source rules out on GeForce cards), camless says so and leaves the fan out until the service starts again. Before it first sets a fan, camless leaves a file, `%APPDATA%\camless\taken-gpu-fans`: if camless crashes or is killed, the card keeps the last duty until a camless starts again, which gives every fan back to the card's curve, whatever the settings say by then. camless loads `nvml.dll` from System32, or from NVSMI on older drivers, by its full path. AMD cards on Windows need AMD's ADLX, which camless does not drive yet. +- On Windows, NVIDIA cards, through NVML (`nvml.dll`, which comes with the driver): `nvmlDeviceSetFanSpeed_v2` sets a fan's duty, within the card's `nvmlDeviceGetMinMaxFanSpeed`, and `nvmlDeviceSetDefaultFanSpeed_v2` gives it back to the card's curve. The rpm comes from `nvmlDeviceGetFanSpeedRPM`, on drivers that have it. Setting a fan needs administrator rights: without them, or on a card whose fans NVML does not set (`NVML_ERROR_NOT_SUPPORTED`, which no source rules out on GeForce cards), camless says so and leaves the fan out until the service starts again. Before it first sets a fan, camless leaves a file, `%APPDATA%\camless\taken-gpu-fans`: if camless crashes or is killed, the card keeps the last duty until a camless starts again, which gives every fan back to the card's curve, whatever the settings say by then. camless loads `nvml.dll` from System32, or from NVSMI on older drivers, by its full path, for the GPU's sensors too: a service that runs as administrator must not load one from a folder the user's programs can write to. AMD cards on Windows need AMD's ADLX, which camless does not drive yet. - On Linux, AMD cards, through the `amdgpu` driver's hwmon files, as the motherboard's headers: `pwm1_enable` 1 and `pwm1` for a duty, the mode it had to give it back. The same udev rule gives you those two files. Cards from the RX 7000 series on may not take a duty in `pwm1`: the kernel gives them a fan curve in `gpu_od` instead, which camless does not write. A card that refuses manual mode or the duty is left out once it refuses, until the service starts again. A crash is covered as on the motherboard. NVML needs root on Linux, which the service is not. - A card's fans are `gpu`, and a second card's `gpu#2`. camless gives a fan back when its curve is removed and when the service stops, the setting goes off, or another program that sets them starts: the motherboard's fan programs and MSI Afterburner. @@ -159,7 +159,11 @@ Each call returns a promise that resolves once camless has taken the message, or | `POST /v1/stop` | stops the service the way Ctrl+C does: host-driven fans to `failsafe_duty` or their fixed duty, the LCD back to its own screen; `Content-Type: application/json` only, so web pages cannot send it | | `POST /v1/lcd/frame` | one frame for the LCD in `frames` mode at its size (640×640 on the Kraken Elite), raw RGBA or RGB565 big-endian, `Content-Type: application/octet-stream`; 202, 409 without such an LCD, 429 when two frames are already waiting | -It listens on `127.0.0.1:30641` by default and binds to loopback only. It rejects foreign `Host` headers, so web pages cannot reach it through DNS rebinding. +It listens on `127.0.0.1:30641` by default and binds to loopback only. Web pages are kept out: +- A foreign `Host` header gets 421, so a page cannot reach it through DNS rebinding. +- A request a browser sends for a page elsewhere gets 403: one with an `Origin` other than the API's own address, or with `Sec-Fetch-Site` other than `same-origin` or `none`. Programs send neither header, and an address typed into a browser comes with `Sec-Fetch-Site: none`; a link to the API on a web page gets the 403. + +It has no password. Any program on this PC can read it, send frames and stop the service, and so can another user signed in to the same PC. ## The app's look diff --git a/scripts/package-linux.sh b/scripts/package-linux.sh index 279b4c1..a03a95f 100755 --- a/scripts/package-linux.sh +++ b/scripts/package-linux.sh @@ -19,7 +19,7 @@ if [ -n "$tag" ] && [ "$tag" != "v$version" ]; then exit 1 fi -cargo build --release --workspace --manifest-path "$root/Cargo.toml" +cargo build --release --workspace --locked --manifest-path "$root/Cargo.toml" target=${CARGO_TARGET_DIR:-$root/target}/release name=camless-linux-x86_64.tar.gz diff --git a/scripts/package.ps1 b/scripts/package.ps1 index 3748910..ba65d52 100644 --- a/scripts/package.ps1 +++ b/scripts/package.ps1 @@ -13,7 +13,7 @@ $version = $versions[0] if (@($versions | Select-Object -Unique).Count -ne 1) { throw "the crates are at different versions: $($versions -join ', ')" } if ($Tag -and $Tag -ne "v$version") { throw "tag $Tag does not match version $version in Cargo.toml" } -cargo build --release --workspace --manifest-path (Join-Path $root 'Cargo.toml') +cargo build --release --workspace --locked --manifest-path (Join-Path $root 'Cargo.toml') if ($LASTEXITCODE -ne 0) { throw 'cargo build failed' } $iscc = (Get-Command iscc -ErrorAction SilentlyContinue).Source diff --git a/src/api.rs b/src/api.rs index 4ab516c..ac56a64 100644 --- a/src/api.rs +++ b/src/api.rs @@ -67,6 +67,13 @@ fn handle( if !header(&req, "Host").is_some_and(|h| hosts.iter().any(|ok| ok.eq_ignore_ascii_case(h))) { return Ok(req.respond(Response::empty(421))?); } + // Nor does a page on the web get to ask at all: a browser says where a request + // comes from, and programs on this PC say nothing. + if from_another_site(header(&req, "Origin"), header(&req, "Sec-Fetch-Site"), hosts) { + // Someone who followed a link here reads this in their browser. + let msg = "camless's local API does not answer web pages. To see this address, type it into the address bar."; + return Ok(req.respond(Response::from_string(msg).with_status_code(403))?); + } let snapshot = || shared.lock().unwrap_or_else(|e| e.into_inner()).clone(); let url = req.url().to_string(); let (path, query) = url.split_once('?').unwrap_or((&url, "")); @@ -128,6 +135,16 @@ fn handle( } } +/// Whether a browser sent this for a page that is not the API's own: one with an +/// `Origin` other than the API's address, or one the browser marks as coming from +/// another site or another port (`Sec-Fetch-Site`). Such a page could not read the +/// answer, and the two POSTs already turn it away by content type; this keeps it from +/// every path, the ones added later too. A request with neither header is a program's. +fn from_another_site(origin: Option<&str>, fetch_site: Option<&str>, hosts: &[String]) -> bool { + let own = |o: &str| o.strip_prefix("http://").is_some_and(|h| hosts.iter().any(|ok| ok.eq_ignore_ascii_case(h))); + origin.is_some_and(|o| !own(o.trim())) || fetch_site.is_some_and(|s| !matches!(s.trim(), "same-origin" | "none")) +} + /// The body of `GET path` from the service at `addr`, for commands that ask the /// running service, the way the app asks it. pub fn get(addr: &str, path: &str) -> Result { @@ -146,12 +163,19 @@ pub fn get(addr: &str, path: &str) -> Result { Ok(body.to_string()) } +/// The largest time or span a history query may name, in seconds. +const MAX_SECS: i64 = 99_999_999_999; + /// The window a history query asks for, as (from, to, ids): the last `span` seconds, /// 600 by default, or `from` to `to` (Unix seconds, `to` now by default). `ids` is a /// comma-separated list of series. fn history_query(query: &str, now: i64) -> std::result::Result<(i64, i64, Option>), String> { let (mut span, mut from, mut to, mut ids) = (600, None, now, None); - let secs = |k: &str, v: &str| v.parse::().map_err(|_| format!("{k} {v:?} is not a number of seconds")); + // Times since 1970 and spans, so never negative, and no further than the year + // 5138: the arithmetic on them then stays far from the ends of an i64. + let secs = |k: &str, v: &str| { + v.parse::().ok().filter(|n| (0..=MAX_SECS).contains(n)).ok_or_else(|| format!("{k} {v:?} is not a number of seconds")) + }; for pair in query.split('&').filter(|p| !p.is_empty()) { let (k, v) = pair.split_once('=').unwrap_or((pair, "")); match k { @@ -260,5 +284,28 @@ mod tests { assert_eq!(history_query("from=1799999000", now), Ok((1_799_999_000, now, None))); assert!(history_query("from=1700003600&to=1700000000", now).is_err()); assert_eq!(percent_decode("a%2"), "a%2"); + // Nothing that would overflow further on. + for query in ["from=-9223372036854775808&to=-9223372036854775807", "to=-1", "span=-5", "from=100000000000", "span=9223372036854775807"] { + assert!(history_query(query, now).is_err(), "{query}"); + } + } + + #[test] + fn pages_on_the_web_are_turned_away() { + let hosts = ["127.0.0.1:30641".to_string(), "localhost:30641".to_string(), "[::1]:30641".to_string()]; + let other = |origin, site| from_another_site(origin, site, &hosts); + // Programs: the app, curl, a script that posts frames. + assert!(!other(None, None)); + // A page the API itself would serve, and an address typed into the browser. + assert!(!other(Some("http://127.0.0.1:30641"), Some("same-origin"))); + assert!(!other(Some("http://LOCALHOST:30641"), None)); + assert!(!other(None, Some("none"))); + // Pages elsewhere, with or without CORS, and ones on another port of this PC. + assert!(other(Some("https://example.com"), Some("cross-site"))); + assert!(other(None, Some("cross-site"))); + assert!(other(None, Some("same-site"))); + assert!(other(Some("http://localhost:8080"), None)); + assert!(other(Some("https://127.0.0.1:30641"), None)); + assert!(other(Some("null"), None)); } } diff --git a/src/drivers/gpu.rs b/src/drivers/gpu.rs index bd2a981..12783c7 100644 --- a/src/drivers/gpu.rs +++ b/src/drivers/gpu.rs @@ -110,23 +110,11 @@ mod nvidia { speed: u32, } - /// Where the driver puts `nvml.dll`: System32 since 2019, NVSMI before. A full - /// path, so no `nvml.dll` beside camless loads instead. - fn library() -> Result { - let system = std::env::var_os("SystemRoot").map(|r| PathBuf::from(r).join("System32").join("nvml.dll")); - let nvsmi = std::env::var_os("ProgramFiles").map(|p| PathBuf::from(p).join("NVIDIA Corporation").join("NVSMI").join("nvml.dll")); - for path in [system, nvsmi].into_iter().flatten().filter(|p| p.exists()) { - if let Ok(lib) = unsafe { Library::new(&path) } { - return Ok(lib); - } - } - bail!("nvml.dll not found: no NVIDIA driver") - } - impl Api { fn open() -> Result { unsafe { - let lib = library()?; + // By its full path, so no `nvml.dll` beside camless loads instead. + let lib = crate::sensors::nvml_library()?; let init: unsafe extern "C" fn() -> i32 = *lib.get(b"nvmlInit_v2\0")?; // Every function first, so a missing one returns before NVML starts. let api = Api { diff --git a/src/sensors.rs b/src/sensors.rs index 71d85f5..bb29ab7 100644 --- a/src/sensors.rs +++ b/src/sensors.rs @@ -4,7 +4,7 @@ //! and FanControl already install, and through hwmon and RAPL on Linux; CPU load and //! memory from the system. [`os`] holds what differs. -use anyhow::{bail, Context, Result}; +use anyhow::{bail, Result}; use camless_core::status::{PowerSource, Sensor, Unit}; use libloading::Library; use serde::Serialize; @@ -17,7 +17,7 @@ mod os; #[path = "sensors/windows.rs"] mod os; #[cfg(windows)] -pub use os::{cpu_maker, pawnio_module_file, reg_dword, reg_string, PAWNIO_LIB}; +pub use os::{cpu_maker, nvml as nvml_library, pawnio_module_file, reg_dword, reg_string, PAWNIO_LIB}; pub use os::{cpu_name, NO_CPU_TEMP}; /// Where camless reads the signed PawnIO module from: the config's path, or the @@ -262,7 +262,7 @@ fn nvml_ok(code: i32, what: &str) -> Result<()> { impl Nvml { fn open() -> Result { unsafe { - let lib = Library::new(os::NVML).with_context(|| format!("{} not found", os::NVML))?; + let lib = os::nvml()?; let init: unsafe extern "C" fn() -> i32 = *lib.get(b"nvmlInit_v2\0")?; nvml_ok(init(), "nvmlInit")?; let by_index: unsafe extern "C" fn(u32, *mut NvmlDevice) -> i32 = diff --git a/src/sensors/linux.rs b/src/sensors/linux.rs index 60d89ef..fcb7efa 100644 --- a/src/sensors/linux.rs +++ b/src/sensors/linux.rs @@ -13,6 +13,12 @@ use std::time::Instant; /// The library NVIDIA's driver installs. pub const NVML: &str = "libnvidia-ml.so.1"; +/// By its name, which the dynamic linker finds in the system's library folders; the +/// service runs as the user here, so there is nobody's rights to borrow. +pub fn nvml() -> Result { + unsafe { libloading::Library::new(NVML) }.with_context(|| format!("{NVML} not found")) +} + pub const NO_CPU_TEMP: &str = "no CPU temperature (no k10temp, zenpower or coretemp sensor)"; const HWMON: &str = "/sys/class/hwmon"; diff --git a/src/sensors/windows.rs b/src/sensors/windows.rs index a3e5494..608226b 100644 --- a/src/sensors/windows.rs +++ b/src/sensors/windows.rs @@ -7,6 +7,7 @@ use anyhow::{bail, Context, Result}; use libloading::Library; use std::ffi::c_void; use camless_core::status::{PowerSource, PowerStats}; +use std::path::PathBuf; use std::time::{Duration, Instant}; use windows_sys::Wdk::Graphics::Direct3D::{ D3DKMTCloseAdapter, D3DKMTEnumAdapters2, D3DKMTQueryAdapterInfo, D3DKMTQueryStatistics, D3DKMT_ADAPTERINFO, @@ -17,12 +18,37 @@ use windows_sys::Wdk::Graphics::Direct3D::{ }; use windows_sys::Win32::Foundation::{FILETIME, HANDLE, LUID, WAIT_ABANDONED, WAIT_OBJECT_0}; use windows_sys::Win32::System::Registry::{RegGetValueW, HKEY_LOCAL_MACHINE, RRF_RT_REG_DWORD, RRF_RT_REG_SZ}; -use windows_sys::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX}; +use windows_sys::Win32::System::SystemInformation::{GetSystemDirectoryW, GlobalMemoryStatusEx, MEMORYSTATUSEX}; use windows_sys::Win32::System::Threading::{CreateMutexW, GetSystemTimes, ReleaseMutex, WaitForSingleObject}; /// The library NVIDIA's driver installs. pub const NVML: &str = "nvml.dll"; +/// Windows' System32, as Windows names it. Not from `%SystemRoot%`: the service may +/// run as administrator, and a variable is whatever the user's programs set it to. +pub fn system_dir() -> Option { + use std::os::windows::ffi::OsStringExt; + let mut buf = [0u16; 260]; + let len = unsafe { GetSystemDirectoryW(buf.as_mut_ptr(), buf.len() as u32) } as usize; + (1..buf.len()).contains(&len).then(|| PathBuf::from(std::ffi::OsString::from_wide(&buf[..len]))) +} + +/// `nvml.dll` where NVIDIA's driver puts it: System32 since 2019, NVSMI in Program +/// Files before. By its full path: a bare name would also be looked for beside +/// camless and in every folder on the PATH, which the user's programs can write to, +/// and the service would load that one as administrator on a PC without the driver. +pub fn nvml() -> Result { + let system = system_dir().map(|d| d.join(NVML)); + let nvsmi = reg_string(r"SOFTWARE\Microsoft\Windows\CurrentVersion", "ProgramFilesDir") + .map(|p| PathBuf::from(p).join("NVIDIA Corporation").join("NVSMI").join(NVML)); + for path in [system, nvsmi].into_iter().flatten().filter(|p| p.is_file()) { + if let Ok(lib) = unsafe { Library::new(&path) } { + return Ok(lib); + } + } + bail!("{NVML} not found: no NVIDIA driver") +} + /// Without PawnIO and administrator rights there is no CPU temperature. pub const NO_CPU_TEMP: &str = "no CPU temperature (needs PawnIO and administrator rights)"; @@ -720,10 +746,7 @@ unsafe impl Send for AdlPower {} impl AdlPower { fn open(address: D3DKMT_ADAPTERADDRESS) -> Result { // A full path, so no atiadlxx.dll beside camless loads instead. - let path = std::env::var_os("SystemRoot") - .map(|r| std::path::PathBuf::from(r).join("System32").join("atiadlxx.dll")) - .filter(|p| p.exists()) - .context("atiadlxx.dll not found: no AMD driver")?; + let path = system_dir().map(|d| d.join("atiadlxx.dll")).filter(|p| p.is_file()).context("atiadlxx.dll not found: no AMD driver")?; unsafe { let lib = Library::new(&path).context("atiadlxx.dll does not load")?; let create: unsafe extern "C" fn(extern "C" fn(i32) -> *mut c_void, i32, *mut *mut c_void) -> i32 = @@ -912,6 +935,14 @@ impl Drop for WddmGpu { mod tests { use super::*; + /// Windows names its own folder, whatever `%SystemRoot%` says. + #[test] + fn system32_comes_from_windows() { + let dir = system_dir().expect("Windows names its system folder"); + assert!(dir.is_absolute() && dir.is_dir(), "{}", dir.display()); + assert!(dir.file_name().is_some_and(|n| n.eq_ignore_ascii_case("system32")), "{}", dir.display()); + } + // Built from the registers' layouts in Intel's SDM and AMD's PPR, not read from a // CPU. #[test]