From 57e76707fc1de9853afc51768229a770bf454188 Mon Sep 17 00:00:00 2001 From: Geoffrey Vancoetsem <10533139+geeooff@users.noreply.github.com> Date: Tue, 24 Nov 2026 02:46:17 +0100 Subject: [PATCH 1/3] Start PowerShell and schtasks.exe by full path from the system folder Given a bare name, std's Command searches the running executable's own folder before System32 and PATH, as Command::new documents, so a copy unpacked in Downloads would have run a powershell.exe or schtasks.exe lying beside it: the updater's after-exit shell, purge's, and the setup commands' removal of the old logon task. Both now come from the folder GetSystemDirectoryW names, with no fallback to the name. win::system_dir carries the rule, AGENTS.md the pitfall; a test per module checks the program each builds. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 3 +++ CHANGELOG.md | 3 +++ docs/design/08-distribution.md | 7 +++++ src/shell.rs | 49 +++++++++++++++++++++++++++++++--- src/task.rs | 42 ++++++++++++++++++++++------- src/win.rs | 34 ++++++++++++++++++++--- 6 files changed, 122 insertions(+), 16 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 64799b2..4ecab2c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -177,6 +177,9 @@ This file says how to work here. The *why* is in `src/open.rs`. - `FindWindow` cannot find a window class registered by another process; use `EnumWindows`. +- `Command::new` given a bare name searches the executable's own folder + before System32 and `PATH`: start a Windows program by full path, from + `win::system_dir`. - A process started after `WM_QUERYENDSESSION` dies with `STATUS_DLL_INIT_FAILED`: nothing runs at logoff, so the session marker runs the stop commands at the next start. diff --git a/CHANGELOG.md b/CHANGELOG.md index 7966a73..a07bf80 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,6 +19,9 @@ a section is written. - The log writes Windows paths as Windows does, with single backslashes, where its details doubled them; a command's arguments read as typed. +- Windows PowerShell and `schtasks.exe` are started from Windows' system + folder, never found by name: a copy unpacked in Downloads could run a + program of that name lying beside it. ## [0.5.0] - 2026-11-16 diff --git a/docs/design/08-distribution.md b/docs/design/08-distribution.md index 36a8580..be8b2ac 100644 --- a/docs/design/08-distribution.md +++ b/docs/design/08-distribution.md @@ -138,6 +138,13 @@ the single-instance mutex says when it has gone. Still to measure: the cost of an uninstall-time prompt, in tables — not built, and not missed so far. +*Since 2026-11-24 the hidden shell and `schtasks.exe` start by full path +from the system folder: given a bare name, std searches the executable's +own folder first (`Command::new`). Measured that day: the published 0.5.0, +copied beside a stand-in `schtasks.exe`, ran it while `purge` drew its +plan, and announced a logon task that does not exist; this build ran +Windows' own.* + **Run for real on 2026-09-17**, on the maintainer's hand-installed copy, after the recipe's `uninstall-tasks.ps1` and `uninstall-task`: it listed ten things and did them. Two lessons, both fixed the same evening: the diff --git a/src/shell.rs b/src/shell.rs index 390cce7..d8aff90 100644 --- a/src/shell.rs +++ b/src/shell.rs @@ -10,6 +10,12 @@ //! line, so std's quoting for `CommandLineToArgvW` carries it through //! intact. Seen the other way on 2026-09-17: a `cmd.exe` line with double //! quotes, escaped as `\"` by std, deleted nothing. +//! +//! Started by full path, `WindowsPowerShell\v1.0\powershell.exe` in the +//! system folder, where Windows keeps Windows PowerShell 5.1: given the bare +//! name, std would search this executable's own folder first, as +//! `Command::new` documents, and an unpacked copy may sit beside anything +//! there (`win::system_dir`). use std::path::Path; use std::process::{Child, Command}; @@ -26,9 +32,18 @@ pub fn quoted(path: &Path) -> String { /// for a caller that wants to know when it is done -- or that does not, /// and drops it. pub fn hidden(script: &str) -> Result { + command(script)? + .spawn() + .context("cannot start the hidden shell") +} + +/// The hidden Windows PowerShell for `script`, not yet started. +fn command(script: &str) -> Result { use std::os::windows::process::CommandExt; const CREATE_NO_WINDOW: u32 = 0x0800_0000; - Command::new("powershell.exe") + let mut command = + Command::new(crate::win::system_dir()?.join(r"WindowsPowerShell\v1.0\powershell.exe")); + command .args([ "-NoProfile", "-NonInteractive", @@ -37,9 +52,8 @@ pub fn hidden(script: &str) -> Result { "-Command", ]) .arg(script) - .creation_flags(CREATE_NO_WINDOW) - .spawn() - .context("cannot start the hidden shell") + .creation_flags(CREATE_NO_WINDOW); + Ok(command) } /// Run `steps` once the process `pid` has exited. Each step says for itself @@ -57,3 +71,30 @@ pub fn after_process(pid: u32, steps: &[String]) -> Result<()> { pub fn after_exit(steps: &[String]) -> Result<()> { after_process(std::process::id(), steps) } + +#[cfg(test)] +mod tests { + use super::*; + + /// Windows' own, by a full path in the system folder, whatever sits + /// beside the executable. + #[test] + fn the_shell_is_windows_powershell_by_full_path() { + let command = command("exit").unwrap(); + let program = Path::new(command.get_program()); + assert!(program.starts_with(crate::win::system_dir().unwrap())); + assert!(program.is_file(), "{}", program.display()); + assert!(program.ends_with("powershell.exe")); + assert_eq!( + command.get_args().collect::>(), + [ + "-NoProfile", + "-NonInteractive", + "-WindowStyle", + "Hidden", + "-Command", + "exit" + ] + ); + } +} diff --git a/src/task.rs b/src/task.rs index c0651f4..a7f82d4 100644 --- a/src/task.rs +++ b/src/task.rs @@ -12,6 +12,10 @@ //! upgrade, as Lot 8 promised. Read through Task Scheduler's own interface, //! which answers in UTF-16: `schtasks /Query /XML` writes through the //! console's code page, and a user name with an accent would not survive it. +//! +//! `schtasks.exe` is started by full path in the system folder: given the +//! bare name, std would search this executable's own folder first, as +//! `Command::new` documents (`win::system_dir`). use std::path::PathBuf; use std::process::Command; @@ -34,9 +38,8 @@ pub const TASK_NAME: &str = r"GameModeExecutor\Watcher"; /// task that does not exist, which is the whole answer. pub fn exists() -> bool { schtasks(&["/Query", "/TN", TASK_NAME]) - .output() - .map(|output| output.status.success()) - .unwrap_or(false) + .and_then(|mut command| Ok(command.output()?)) + .is_ok_and(|output| output.status.success()) } /// The configuration that task passes the watcher, if the task is there and @@ -120,7 +123,7 @@ pub fn remove_leftover() -> Result<()> { if !exists() { return Ok(()); } - let output = schtasks(&["/Delete", "/TN", TASK_NAME, "/F"]) + let output = schtasks(&["/Delete", "/TN", TASK_NAME, "/F"])? .output() .context("cannot run schtasks.exe")?; if !output.status.success() { @@ -136,23 +139,44 @@ pub fn remove_leftover() -> Result<()> { Ok(()) } -/// `schtasks.exe` with its output captured and no console window of its -/// own. A console program started from a parent that has no visible console +/// `schtasks.exe` from the system folder, with its output captured and no +/// console window of its own. A console program started from a parent that has no visible console /// -- the installer's custom action, the windowless watcher -- opens one for /// itself, and the user sees it flash: seen on 2026-09-18, on the first /// install from the package. -fn schtasks(args: &[&str]) -> Command { +fn schtasks(args: &[&str]) -> Result { use std::os::windows::process::CommandExt; const CREATE_NO_WINDOW: u32 = 0x0800_0000; - let mut command = Command::new("schtasks"); + let mut command = Command::new(crate::win::system_dir()?.join("schtasks.exe")); command.args(args).creation_flags(CREATE_NO_WINDOW); - command + Ok(command) } #[cfg(test)] mod tests { + use std::path::Path; + use super::*; + /// Windows' own, by a full path in the system folder, whatever sits + /// beside the executable. + #[test] + fn schtasks_is_windows_own_by_full_path() { + let command = schtasks(&["/Query", "/TN", TASK_NAME]).unwrap(); + let program = Path::new(command.get_program()); + assert!(program.starts_with(crate::win::system_dir().unwrap())); + assert!(program.is_file(), "{}", program.display()); + assert!(program.ends_with("schtasks.exe")); + assert_eq!( + command.get_args().collect::>(), + ["/Query", "/TN", TASK_NAME] + ); + // And it starts: `exists` reads a failed start as no task, so + // nothing else would tell. + let help = schtasks(&["/Query", "/?"]).unwrap().output().unwrap(); + assert!(help.status.success(), "{:?}", help.status); + } + /// What 0.4's `install-task` wrote, and what a person may have typed. #[test] fn the_configuration_is_read_from_the_tasks_arguments() { diff --git a/src/win.rs b/src/win.rs index 85fe8dd..b1639f9 100644 --- a/src/win.rs +++ b/src/win.rs @@ -1,20 +1,23 @@ //! Thin, safe wrappers around the few Win32 calls the program needs. -use std::ffi::c_void; +use std::ffi::{OsString, c_void}; +use std::os::windows::ffi::OsStringExt; +use std::path::PathBuf; use std::sync::atomic::{AtomicU8, Ordering}; use std::sync::{Arc, OnceLock}; use std::time::Duration; use anyhow::{Context, Result}; use windows::Win32::Foundation::{ - CloseHandle, ERROR_ALREADY_EXISTS, GetLastError, HANDLE, HWND, LPARAM, LRESULT, WAIT_OBJECT_0, - WAIT_TIMEOUT, WPARAM, + CloseHandle, ERROR_ALREADY_EXISTS, GetLastError, HANDLE, HWND, LPARAM, LRESULT, MAX_PATH, + WAIT_OBJECT_0, WAIT_TIMEOUT, WPARAM, }; use windows::Win32::Storage::FileSystem::{ FILE_NOTIFY_CHANGE_FILE_NAME, FILE_NOTIFY_CHANGE_LAST_WRITE, FILE_NOTIFY_CHANGE_SIZE, FindCloseChangeNotification, FindFirstChangeNotificationW, FindNextChangeNotification, }; use windows::Win32::System::LibraryLoader::GetModuleHandleW; +use windows::Win32::System::SystemInformation::GetSystemDirectoryW; use windows::Win32::System::Threading::{ CreateEventW, CreateMutexW, INFINITE, OpenMutexW, ResetEvent, SYNCHRONIZATION_SYNCHRONIZE, SetEvent, WaitForMultipleObjects, WaitForSingleObject, @@ -506,6 +509,31 @@ pub fn declare_dpi_awareness() { } } +/// The system folder, `C:\Windows\System32` on a stock install, where the +/// Windows programs this program starts -- Windows PowerShell, +/// `schtasks.exe` -- are found by full path. +/// +/// Never by bare name: std then searches the running executable's own +/// folder before the system folder and `PATH`, as `Command::new` documents, +/// and a copy unpacked in Downloads would run a `powershell.exe` planted +/// beside it. Asked of `GetSystemDirectoryW`, not read from `%SystemRoot%`, +/// which is whatever the parent process passed down; and no fallback to the +/// name, which would bring the search back. +pub fn system_dir() -> Result { + // MAX_PATH is the size Microsoft documents for this buffer. + let mut buffer = [0u16; MAX_PATH as usize]; + // SAFETY: the slice is the buffer and passes its own length; the call + // writes at most that many characters, the terminating zero included. + let len = unsafe { GetSystemDirectoryW(Some(&mut buffer)) } as usize; + if len == 0 || len >= buffer.len() { + anyhow::bail!( + "cannot find the system folder: {}", + std::io::Error::last_os_error() + ); + } + Ok(PathBuf::from(OsString::from_wide(&buffer[..len]))) +} + /// Pump messages until a quit is posted. Must run on the thread that created /// the window, which is the main thread. pub fn run_message_loop() { From 16559abc868a083e9db2216e313dd8cde953d673 Mon Sep 17 00:00:00 2001 From: Geoffrey Vancoetsem <10533139+geeooff@users.noreply.github.com> Date: Tue, 24 Nov 2026 03:00:04 +0100 Subject: [PATCH 2/3] Load the executables' DLLs from System32 only The imports that are not known DLLs -- msi.dll, winhttp.dll, bcrypt.dll, VCRUNTIME140.dll -- were looked for in the executable's own folder first, so a copy unpacked in Downloads loaded whatever lay beside it, before main. build.rs now links both executables with /DEPENDENTLOADFLAG:0x800 (LOAD_LIBRARY_SEARCH_SYSTEM32). Measured with a stand-in msi.dll beside a copy: the published 0.5.0 loaded it, this build does not. build.ps1 build reads the flag back from the PE load configuration, since losing it would change nothing anyone sees. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 2 +- CHANGELOG.md | 2 ++ build.rs | 17 ++++++++++++++ docs/design/08-distribution.md | 11 +++++++++ scripts/build.ps1 | 43 ++++++++++++++++++++++++++++++++++ 5 files changed, 74 insertions(+), 1 deletion(-) diff --git a/AGENTS.md b/AGENTS.md index 4ecab2c..214e428 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -112,7 +112,7 @@ This file says how to work here. The *why* is in ```powershell .\scripts\build.ps1 test # fmt, clippy -D warnings, tests, shipped config.toml files, doc links -.\scripts\build.ps1 build # + release build, PE subsystem check +.\scripts\build.ps1 build # + release build, PE subsystem and DLL search checks .\scripts\build.ps1 release # + clean tree, stamped commit, dist\ zips, MSI built and validated ``` diff --git a/CHANGELOG.md b/CHANGELOG.md index a07bf80..4c7d8c0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -22,6 +22,8 @@ a section is written. - Windows PowerShell and `schtasks.exe` are started from Windows' system folder, never found by name: a copy unpacked in Downloads could run a program of that name lying beside it. +- The DLLs the program needs are loaded from Windows' system folder only: + a copy unpacked in Downloads loaded an `msi.dll` lying beside it. ## [0.5.0] - 2026-11-16 diff --git a/build.rs b/build.rs index 4f60ce6..8a7146a 100644 --- a/build.rs +++ b/build.rs @@ -46,6 +46,23 @@ fn main() { println!("cargo:rustc-env=GIT_COMMIT_DISPLAY={display}"); embed_resources(&short, !dirty.is_empty()); + search_dlls_in_system32_only(); +} + +/// Where Windows looks for the DLLs the executables import: in System32 +/// only, `LOAD_LIBRARY_SEARCH_SYSTEM32` in the PE's load configuration, +/// which Windows 10 1607 and later honour for a module's static imports. +/// +/// Without it, an import that is not a known DLL -- `msi.dll`, `winhttp.dll`, +/// `bcrypt.dll` -- is looked for in the executable's own folder first, and a +/// copy unpacked in Downloads loads whatever lies beside it, before `main`. +/// Measured on 2026-11-24 with the published 0.5.0 and a stand-in `msi.dll` +/// (`docs/design/08-distribution.md`). `scripts/build.ps1 build` checks +/// that the flag is in both executables. +fn search_dlls_in_system32_only() { + if std::env::var("CARGO_CFG_TARGET_ENV").as_deref() == Ok("msvc") { + println!("cargo:rustc-link-arg-bins=/DEPENDENTLOADFLAG:0x800"); + } } /// The icon Explorer, the task bar and Alt-Tab show for the executables, and diff --git a/docs/design/08-distribution.md b/docs/design/08-distribution.md index be8b2ac..0090b5e 100644 --- a/docs/design/08-distribution.md +++ b/docs/design/08-distribution.md @@ -145,6 +145,17 @@ copied beside a stand-in `schtasks.exe`, ran it while `purge` drew its plan, and announced a logon task that does not exist; this build ran Windows' own.* +*The same day, the DLLs: those the executables import that are not known +DLLs — `msi.dll`, `winhttp.dll`, `bcrypt.dll`, `VCRUNTIME140.dll` — were +looked for in the executable's folder first. `build.rs` now links with +`/DEPENDENTLOADFLAG:0x800`, System32 only, which Microsoft documents for a +module's static imports from Windows 10 1607 without saying whether an +EXE's own count; measured, they do. A stand-in `msi.dll` beside a copy was +loaded by the published 0.5.0, at `--version`, before `main`, and not by +this build; a stand-in `bcryptprimitives.dll` by neither, a system DLL +having already brought Windows' own. `build.ps1 build` reads the flag back +from both executables.* + **Run for real on 2026-09-17**, on the maintainer's hand-installed copy, after the recipe's `uninstall-tasks.ps1` and `uninstall-task`: it listed ten things and did them. Two lessons, both fixed the same evening: the diff --git a/scripts/build.ps1 b/scripts/build.ps1 index 0bd6a14..242d450 100644 --- a/scripts/build.ps1 +++ b/scripts/build.ps1 @@ -217,6 +217,39 @@ function Invoke-Tests { Write-Host " $($pages.Count) pages, every link resolves" } +# --- reading a PE32+ image -------------------------------------------------- + +# The RVA of data directory $Index (10, the load configuration). +function Get-DirectoryRva([byte[]] $Bytes, [int] $Index) { + $optional = [BitConverter]::ToInt32($Bytes, 0x3C) + 24 + if ([BitConverter]::ToUInt16($Bytes, $optional) -ne 0x20B) { Fail "not a PE32+ image" } + [BitConverter]::ToUInt32($Bytes, $optional + 0x70 + 8 * $Index) +} + +# The file offset of an RVA, through the section that holds it. +function Get-FileOffset([byte[]] $Bytes, [uint32] $Rva) { + $pe = [BitConverter]::ToInt32($Bytes, 0x3C) + $table = $pe + 24 + [BitConverter]::ToUInt16($Bytes, $pe + 20) + for ($i = 0; $i -lt [BitConverter]::ToUInt16($Bytes, $pe + 6); $i++) { + $section = $table + 40 * $i + $start = [BitConverter]::ToUInt32($Bytes, $section + 12) + if ($Rva -ge $start -and $Rva -lt $start + [BitConverter]::ToUInt32($Bytes, $section + 8)) { + return [int]($Rva - $start + [BitConverter]::ToUInt32($Bytes, $section + 20)) + } + } + Fail ("RVA 0x{0:X} is in no section" -f $Rva) +} + +# DependentLoadFlags, the word at 0x4E of IMAGE_LOAD_CONFIG_DIRECTORY64, or 0 +# when the image has none. +function Get-DependentLoadFlags([byte[]] $Bytes) { + $rva = Get-DirectoryRva $Bytes 10 + if ($rva -eq 0) { return 0 } + $offset = Get-FileOffset $Bytes $rva + if ([BitConverter]::ToUInt32($Bytes, $offset) -lt 0x50) { return 0 } + [int][BitConverter]::ToUInt16($Bytes, $offset + 0x4E) +} + function Invoke-Build { Step "Release build" Run 'cargo' @('build', '--release') @@ -260,6 +293,16 @@ function Invoke-Build { Write-Host (" {0,-24} {1}" -f $name, $label[$subsystem]) } + # build.rs has Windows look for the executables' DLLs in System32 only. + # Losing the flag is silent: the program runs the same, and loads an + # msi.dll planted beside it again. + Step "DLLs are looked for in System32 only" + foreach ($name in $expected.Keys | Sort-Object) { + $flags = Get-DependentLoadFlags ([System.IO.File]::ReadAllBytes((Join-Path $root "target\release\$name"))) + if ($flags -ne 0x800) { Fail ("$name has dependent load flags 0x{0:X}, expected 0x800" -f $flags) } + Write-Host (" {0,-24} 0x{1:X}, LOAD_LIBRARY_SEARCH_SYSTEM32" -f $name, $flags) + } + # build.rs writes a version block into each executable: the Properties # dialog reads it, and Windows Installer's repair and upgrade rules need # versioned files. A miss is only a warning at build time, so it is From ffdadbaa8e7cb8b3f4adf2782f5c5f2587e1fbad Mon Sep 17 00:00:00 2001 From: Geoffrey Vancoetsem <10533139+geeooff@users.noreply.github.com> Date: Tue, 24 Nov 2026 03:02:47 +0100 Subject: [PATCH 3/3] Link the C runtime into the executables The dynamic runtime needs VCRUNTIME140.dll, which comes with the Visual C++ Redistributable, not with Windows, and the package never installed it: on a Windows without it the program would not start. A .cargo/config.toml now builds every MSVC target with +crt-static, the switch Rust documents; each executable grows by 97 KB, to 1.65 MB. A hybrid (vcruntime static, the UCRT from Windows) would weigh 22 KB and keep the UCRT serviced by Windows Update, at the price of two linker overrides; the design record has the figures. build.ps1 build checks that no executable imports a DLL of the Redistributable. Co-Authored-By: Claude Opus 5.5 --- .cargo/config.toml | 7 +++++++ AGENTS.md | 2 +- CHANGELOG.md | 2 ++ docs/design/08-distribution.md | 12 ++++++++++++ scripts/build.ps1 | 28 ++++++++++++++++++++++++++-- 5 files changed, 48 insertions(+), 3 deletions(-) create mode 100644 .cargo/config.toml diff --git a/.cargo/config.toml b/.cargo/config.toml new file mode 100644 index 0000000..2301b05 --- /dev/null +++ b/.cargo/config.toml @@ -0,0 +1,7 @@ +# The C runtime linked into the executables, rather than VCRUNTIME140.dll +# from the Visual C++ Redistributable, which Windows does not carry and the +# package does not install: without it, the program would not start. +# `scripts/build.ps1 build` checks that no executable imports a DLL of the +# Redistributable; docs/design/08-distribution.md has the figures. +[target.'cfg(all(windows, target_env = "msvc"))'] +rustflags = ["-C", "target-feature=+crt-static"] diff --git a/AGENTS.md b/AGENTS.md index 214e428..96c5888 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -112,7 +112,7 @@ This file says how to work here. The *why* is in ```powershell .\scripts\build.ps1 test # fmt, clippy -D warnings, tests, shipped config.toml files, doc links -.\scripts\build.ps1 build # + release build, PE subsystem and DLL search checks +.\scripts\build.ps1 build # + release build, PE checks: subsystem, DLL search, C runtime .\scripts\build.ps1 release # + clean tree, stamped commit, dist\ zips, MSI built and validated ``` diff --git a/CHANGELOG.md b/CHANGELOG.md index 4c7d8c0..711425d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -24,6 +24,8 @@ a section is written. program of that name lying beside it. - The DLLs the program needs are loaded from Windows' system folder only: a copy unpacked in Downloads loaded an `msi.dll` lying beside it. +- The program no longer needs the Visual C++ Redistributable: the C + runtime is built in. ## [0.5.0] - 2026-11-16 diff --git a/docs/design/08-distribution.md b/docs/design/08-distribution.md index 0090b5e..d736384 100644 --- a/docs/design/08-distribution.md +++ b/docs/design/08-distribution.md @@ -156,6 +156,18 @@ this build; a stand-in `bcryptprimitives.dll` by neither, a system DLL having already brought Windows' own. `build.ps1 build` reads the flag back from both executables.* +*And the C runtime, linked in since the same day (`+crt-static`, +`.cargo/config.toml`). `VCRUNTIME140.dll` comes with the Visual C++ +Redistributable, which the package never installed: here the System32 +copy is the Redistributable's, 14.51, and Windows' component store holds +only .NET's private `vcruntime140_clr0400.dll`. Measured on release +builds: 1,588,736 bytes dynamic, 1,685,504 static (+97 KB each). A hybrid +— vcruntime linked in, the UCRT taken from Windows, which services it — +weighs 1,610,752, at the price of two linker overrides; the static runtime +was preferred as the one switch Rust documents. Not measured: a start on +a Windows without the Redistributable; the import table no longer names +it, and `build.ps1 build` checks that it stays so.* + **Run for real on 2026-09-17**, on the maintainer's hand-installed copy, after the recipe's `uninstall-tasks.ps1` and `uninstall-task`: it listed ten things and did them. Two lessons, both fixed the same evening: the diff --git a/scripts/build.ps1 b/scripts/build.ps1 index 242d450..cb68f63 100644 --- a/scripts/build.ps1 +++ b/scripts/build.ps1 @@ -219,7 +219,7 @@ function Invoke-Tests { # --- reading a PE32+ image -------------------------------------------------- -# The RVA of data directory $Index (10, the load configuration). +# The RVA of data directory $Index (1, the imports; 10, the load configuration). function Get-DirectoryRva([byte[]] $Bytes, [int] $Index) { $optional = [BitConverter]::ToInt32($Bytes, 0x3C) + 24 if ([BitConverter]::ToUInt16($Bytes, $optional) -ne 0x20B) { Fail "not a PE32+ image" } @@ -250,6 +250,18 @@ function Get-DependentLoadFlags([byte[]] $Bytes) { [int][BitConverter]::ToUInt16($Bytes, $offset + 0x4E) } +# The names of the DLLs an image imports: one IMAGE_IMPORT_DESCRIPTOR of 20 +# bytes each, the name's RVA at offset 12, until the empty one. +function Get-ImportedDlls([byte[]] $Bytes) { + $offset = Get-FileOffset $Bytes (Get-DirectoryRva $Bytes 1) + while (($name = [BitConverter]::ToUInt32($Bytes, $offset + 12)) -ne 0) { + $start = Get-FileOffset $Bytes $name + $end = [Array]::IndexOf($Bytes, [byte] 0, $start) + [Text.Encoding]::ASCII.GetString($Bytes, $start, $end - $start) + $offset += 20 + } +} + function Invoke-Build { Step "Release build" Run 'cargo' @('build', '--release') @@ -303,6 +315,18 @@ function Invoke-Build { Write-Host (" {0,-24} 0x{1:X}, LOAD_LIBRARY_SEARCH_SYSTEM32" -f $name, $flags) } + # .cargo/config.toml links the C runtime in. Losing it is silent where + # the Visual C++ Redistributable is installed, as it is on most + # development machines; on a Windows without it, the program would not + # start. + Step "The C runtime is built in" + foreach ($name in $expected.Keys | Sort-Object) { + $dlls = @(Get-ImportedDlls ([System.IO.File]::ReadAllBytes((Join-Path $root "target\release\$name")))) + $redistributable = $dlls | Where-Object { $_ -match '^(vcruntime|msvcp)\d' } + if ($redistributable) { Fail "$name imports $($redistributable -join ', '), from the Visual C++ Redistributable" } + Write-Host (" {0,-24} {1} DLLs imported, none from the Redistributable" -f $name, $dlls.Count) + } + # build.rs writes a version block into each executable: the Properties # dialog reads it, and Windows Installer's repair and upgrade rules need # versioned files. A miss is only a warning at build time, so it is @@ -320,7 +344,7 @@ function Invoke-Build { } # The release profile -- opt-level z, LTO, strip, panic = abort -- keeps - # each binary near 1.1 MB. Losing it is silent: everything still builds and + # each binary near 1.6 MB, the C runtime included. Losing it is silent: everything still builds and # runs, only twice as large and unwinding on panic, which the FATAL hook was # not designed for. It happened once, from an editing slip in Cargo.toml. Step "Binaries are release-profile sized"