Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .cargo/config.toml
Original file line number Diff line number Diff line change
@@ -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"]
5 changes: 4 additions & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 checks: subsystem, DLL search, C runtime
.\scripts\build.ps1 release # + clean tree, stamped commit, dist\ zips, MSI built and validated
```

Expand Down Expand Up @@ -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.
Expand Down
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,13 @@ 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.
- 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

Expand Down
17 changes: 17 additions & 0 deletions build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
30 changes: 30 additions & 0 deletions docs/design/08-distribution.md
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,36 @@ 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.*

*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.*

*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
Expand Down
69 changes: 68 additions & 1 deletion scripts/build.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -217,6 +217,51 @@ function Invoke-Tests {
Write-Host " $($pages.Count) pages, every link resolves"
}

# --- reading a PE32+ image --------------------------------------------------

# 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" }
[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)
}

# 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')
Expand Down Expand Up @@ -260,6 +305,28 @@ 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)
}

# .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
Expand All @@ -277,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"
Expand Down
49 changes: 45 additions & 4 deletions src/shell.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand All @@ -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<Child> {
command(script)?
.spawn()
.context("cannot start the hidden shell")
}

/// The hidden Windows PowerShell for `script`, not yet started.
fn command(script: &str) -> Result<Command> {
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",
Expand All @@ -37,9 +52,8 @@ pub fn hidden(script: &str) -> Result<Child> {
"-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
Expand All @@ -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::<Vec<_>>(),
[
"-NoProfile",
"-NonInteractive",
"-WindowStyle",
"Hidden",
"-Command",
"exit"
]
);
}
}
42 changes: 33 additions & 9 deletions src/task.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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
Expand Down Expand Up @@ -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() {
Expand All @@ -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<Command> {
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::<Vec<_>>(),
["/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() {
Expand Down
Loading