diff --git a/AGENTS.md b/AGENTS.md index b212386..64799b2 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -149,6 +149,13 @@ This file says how to work here. The *why* is in `GameModeExecutor\FanControl` became `GameModeExecutorFanControl`, `target\release` a carriage return. Edit with a tool that takes literal strings, and grep the result. +- **A Windows path is written with single backslashes** wherever nothing + reads `\` as an escape: Rust raw strings (`r"C:\…"`, `format!(r"HKCU\{key}")`), + PowerShell, Markdown, TOML single quotes, the log. Escape only where the + format demands it, through one function: rc.exe's scripts (`rc_string` in + `build.rs`), PowerShell's single quotes (`shell::quoted`), JSON. A log + field is never `Debug`-formatted text: the formatter quotes text as + written, and a path given to `%` prints as Windows writes it. - A shell started by a packaged host — the Claude desktop app — may read `%APPDATA%` through the package's private copy. What the watcher runs is in its log; ask the maintainer for the real file. diff --git a/CHANGELOG.md b/CHANGELOG.md index eadc134..7966a73 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,11 @@ a section is written. ## [Unreleased] +### Fixed + +- The log writes Windows paths as Windows does, with single backslashes, + where its details doubled them; a command's arguments read as typed. + ## [0.5.0] - 2026-11-16 Windows' Startup list starts the watcher now, with a switch in Settings, diff --git a/build.rs b/build.rs index 3079461..4f60ce6 100644 --- a/build.rs +++ b/build.rs @@ -109,7 +109,10 @@ fn embed_resources(commit_short: &str, dirty: bool) { .unwrap_or_default(); let flags = if dirty { "0x8" } else { "0x0" }; // VS_FF_PRIVATEBUILD let private = if dirty { - " VALUE \"PrivateBuild\", \"Built from a tree with uncommitted changes\\0\"\n" + concat!( + r#" VALUE "PrivateBuild", "Built from a tree with uncommitted changes\0""#, + "\n" + ) } else { "" }; @@ -130,53 +133,54 @@ fn embed_resources(commit_short: &str, dirty: bool) { // application icon, and 1 is the convention for it. The numeric // constants are rc.exe's own, spelled out so no header is needed: // FILEOS 0x40004 is VOS_NT_WINDOWS32, FILETYPE 1 is VFT_APP, and the - // string block is en-US in Unicode. + // string block is en-US in Unicode. The script is rc.exe's language, + // where `\` begins an escape inside a quoted string: every value put + // in one goes through `rc_string`, and each `\0` written here is the + // terminator rc.exe expects. let contents = format!( - concat!( - "1 ICON \"{icon}\"\n", - "1 VERSIONINFO\n", - "FILEVERSION {major},{minor},{patch},0\n", - "PRODUCTVERSION {major},{minor},{patch},0\n", - "FILEFLAGSMASK 0x3f\n", - "FILEFLAGS {flags}\n", - "FILEOS 0x40004\n", - "FILETYPE 0x1\n", - "FILESUBTYPE 0x0\n", - "BEGIN\n", - " BLOCK \"StringFileInfo\"\n", - " BEGIN\n", - " BLOCK \"040904b0\"\n", - " BEGIN\n", - " VALUE \"CompanyName\", \"{author}\\0\"\n", - " VALUE \"FileDescription\", \"{description}\\0\"\n", - " VALUE \"FileVersion\", \"{version} ({commit})\\0\"\n", - " VALUE \"InternalName\", \"{name}\\0\"\n", - " VALUE \"LegalCopyright\", \"{copyright}. MIT License.\\0\"\n", - " VALUE \"OriginalFilename\", \"{name}.exe\\0\"\n", - " VALUE \"ProductName\", \"GameModeExecutor\\0\"\n", - " VALUE \"ProductVersion\", \"{version}\\0\"\n", - " VALUE \"Comments\", \"{repository}\\0\"\n", - "{private}", - " END\n", - " END\n", - " BLOCK \"VarFileInfo\"\n", - " BEGIN\n", - " VALUE \"Translation\", 0x409, 1200\n", - " END\n", - "END\n", - ), - icon = icon.display().to_string().replace('\\', "\\\\"), + r#"1 ICON "{icon}" +1 VERSIONINFO +FILEVERSION {major},{minor},{patch},0 +PRODUCTVERSION {major},{minor},{patch},0 +FILEFLAGSMASK 0x3f +FILEFLAGS {flags} +FILEOS 0x40004 +FILETYPE 0x1 +FILESUBTYPE 0x0 +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "040904b0" + BEGIN + VALUE "CompanyName", "{author}\0" + VALUE "FileDescription", "{description}\0" + VALUE "FileVersion", "{version} ({commit})\0" + VALUE "InternalName", "{name}\0" + VALUE "LegalCopyright", "{copyright}. MIT License.\0" + VALUE "OriginalFilename", "{name}.exe\0" + VALUE "ProductName", "GameModeExecutor\0" + VALUE "ProductVersion", "{version}\0" + VALUE "Comments", "{repository}\0" +{private} END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x409, 1200 + END +END +"#, + icon = rc_string(&icon.display().to_string()), major = major, minor = minor, patch = patch, flags = flags, - author = author, - description = description, - version = version, - commit = commit_short, - name = name, - copyright = copyright, - repository = repository, + author = rc_string(&author), + description = rc_string(description), + version = rc_string(&version), + commit = rc_string(commit_short), + name = rc_string(name), + copyright = rc_string(©right), + repository = rc_string(&repository), private = private, ); if std::fs::write(&script, contents).is_err() { @@ -201,6 +205,15 @@ fn embed_resources(commit_short: &str, dirty: bool) { } } +/// A value for a quoted string in rc.exe's script, where `\` begins an +/// escape as in C and a quote is written twice. The icon's path is the one +/// value with backslashes today; the others go through it too, so a quote +/// in a description or a backslash in a copyright line cannot break the +/// script. +fn rc_string(value: &str) -> String { + value.replace('\\', r"\\").replace('"', r#""""#) +} + /// Finds the SDK's resource compiler: the developer prompt's own variable /// first, then the newest version under the installed Windows Kit. fn find_resource_compiler() -> Option { diff --git a/src/actions.rs b/src/actions.rs index d7e24a9..08c988f 100644 --- a/src/actions.rs +++ b/src/actions.rs @@ -163,12 +163,33 @@ fn start(action: &Action, context: &ActionContext) -> Result { command.env(key, context.render(value)); } - tracing::debug!(target: target::COMMANDS, program, args = ?args, "Starting a command"); + tracing::debug!( + target: target::COMMANDS, + program, + args = %shown_arguments(&args), + "Starting a command" + ); command .spawn() .with_context(|| format!("cannot start `{program}`")) } +/// The arguments as a person would type them after the program, for the +/// log: one holding a space between quotes, nothing escaped, so a path +/// reads as Windows writes it. Not the command line `Command` builds. +fn shown_arguments(args: &[String]) -> String { + args.iter() + .map(|arg| { + if arg.is_empty() || arg.contains(char::is_whitespace) { + format!("\"{arg}\"") + } else { + arg.clone() + } + }) + .collect::>() + .join(" ") +} + /// `None` when the command was not waited for; otherwise whether it succeeded. fn join(action: &Action, mut child: Child) -> Option { if !action.wait { @@ -247,6 +268,16 @@ mod tests { Event { mode, actions } } + /// The recipe's own command, as the log shows it. + #[test] + fn the_arguments_read_in_the_log_as_typed() { + let args = [r"/Run", r"/TN", r"GameModeExecutor\FanControl Game", ""].map(str::to_owned); + assert_eq!( + shown_arguments(&args), + r#"/Run /TN "GameModeExecutor\FanControl Game" """# + ); + } + #[test] fn a_series_reports_each_waited_command_and_keeps_going_after_a_failure() { let outcome = run_all( diff --git a/src/bin/presence-probe.rs b/src/bin/presence-probe.rs index f6c6ca7..0f0f662 100644 --- a/src/bin/presence-probe.rs +++ b/src/bin/presence-probe.rs @@ -455,7 +455,7 @@ fn cmd_watch_games(seconds: u64, key: &str) -> windows::core::Result<()> { let root = match Key::open_current_user(key) { Ok(root) => root, Err(error) => { - log(&format!("watch-games: cannot open HKCU\\{key} ({error:#})")); + log(&format!(r"watch-games: cannot open HKCU\{key} ({error:#})")); return Ok(()); } }; diff --git a/src/detect/presence_writer.rs b/src/detect/presence_writer.rs index 0814b0b..ae51515 100644 --- a/src/detect/presence_writer.rs +++ b/src/detect/presence_writer.rs @@ -32,7 +32,7 @@ pub fn registered_exe() -> Result { .context("the presence writer server is not registered on this machine")?; let path = key .string_value(EXE_PATH_VALUE) - .with_context(|| format!("{SERVER_KEY}\\{EXE_PATH_VALUE} is empty"))?; + .with_context(|| format!(r"{SERVER_KEY}\{EXE_PATH_VALUE} is empty"))?; Ok(PathBuf::from(path)) } diff --git a/src/logging.rs b/src/logging.rs index 5f7a485..e486614 100644 --- a/src/logging.rs +++ b/src/logging.rs @@ -197,11 +197,14 @@ impl Collected { } impl Visit for Collected { + /// A text field between quotes, as written: `Debug` would escape every + /// backslash of a Windows path, and the log is read by people, not + /// parsed. fn record_str(&mut self, field: &Field, value: &str) { if field.name() == "message" { self.message.push_str(value); } else { - self.push_field(field.name(), format_args!("{value:?}")); + self.push_field(field.name(), format_args!("\"{value}\"")); } } @@ -525,6 +528,19 @@ mod tests { assert!(line.contains(r#"matched_by="exe path""#), "{line}"); } + /// A Windows path reads as Windows writes it: `Debug` once doubled every + /// backslash of a text field (until 2026-11-16). + #[test] + fn a_text_field_is_quoted_and_not_escaped() { + let line = render(true, || { + tracing::info!(target: target::GAME, path = r"D:\Games\Euro Truck Simulator 2\eurotrucks2.exe", "Game detected: eurotrucks2.exe"); + }); + assert!( + line.contains(r#"path="D:\Games\Euro Truck Simulator 2\eurotrucks2.exe""#), + "{line}" + ); + } + /// Optional data is the common case here -- a game Windows tracks but does /// not describe has no pid and no path -- so pin down how it renders /// rather than discovering `pid=Some(14552)` in a log someone is reading. diff --git a/src/registry.rs b/src/registry.rs index 5f30bf6..4a489a1 100644 --- a/src/registry.rs +++ b/src/registry.rs @@ -18,7 +18,7 @@ impl Key { CURRENT_USER .open(path) .map(Self) - .with_context(|| format!("cannot open HKCU\\{path}")) + .with_context(|| format!(r"cannot open HKCU\{path}")) } /// Open a key under `HKEY_LOCAL_MACHINE` for reading. @@ -26,7 +26,7 @@ impl Key { LOCAL_MACHINE .open(path) .map(Self) - .with_context(|| format!("cannot open HKLM\\{path}")) + .with_context(|| format!(r"cannot open HKLM\{path}")) } pub fn open_subkey(&self, name: &str) -> Result { diff --git a/src/startup.rs b/src/startup.rs index 7875a94..d492013 100644 --- a/src/startup.rs +++ b/src/startup.rs @@ -142,7 +142,7 @@ pub fn add(config_path: &Path, force: bool) -> Result { CURRENT_USER .create(RUN_KEY) .and_then(|key| key.set_string(VALUE_NAME, &line)) - .with_context(|| format!("cannot write `{VALUE_NAME}` under HKCU\\{RUN_KEY}"))?; + .with_context(|| format!(r"cannot write `{VALUE_NAME}` under HKCU\{RUN_KEY}"))?; if outcome == Registration::Added { tracing::info!( target: target::SETUP, @@ -219,7 +219,7 @@ fn remove_from(path: &str) -> Result { return Ok(false); } key.remove_value(VALUE_NAME) - .with_context(|| format!("cannot remove `{VALUE_NAME}` from HKCU\\{path}"))?; + .with_context(|| format!(r"cannot remove `{VALUE_NAME}` from HKCU\{path}"))?; Ok(true) } @@ -244,7 +244,7 @@ fn same_file(a: &Path, b: &Path) -> bool { /// The value's data: the twin and the configuration it reads, both quoted. fn command_line(exe: &Path, config: &Path) -> Result { - let line = format!("\"{}\" --config \"{}\"", exe.display(), config.display()); + let line = format!(r#""{}" --config "{}""#, exe.display(), config.display()); let length = line.encode_utf16().count(); if length > MAX_COMMAND_LINE { bail!( diff --git a/src/task.rs b/src/task.rs index a099d23..c0651f4 100644 --- a/src/task.rs +++ b/src/task.rs @@ -28,7 +28,7 @@ use windows::core::{BSTR, Interface}; /// The task an earlier version registered, folder included. The folder is /// left in place when the task goes: the elevated tasks a recipe asks for /// may live in it, and they are the user's. -pub const TASK_NAME: &str = "GameModeExecutor\\Watcher"; +pub const TASK_NAME: &str = r"GameModeExecutor\Watcher"; /// Whether that task is registered. `schtasks /Query` exits non-zero for a /// task that does not exist, which is the whole answer. @@ -57,7 +57,7 @@ pub fn configuration() -> Option { service.Connect(&none, &none, &none, &none)?; let (folder, name) = TASK_NAME.rsplit_once('\\').unwrap_or(("", TASK_NAME)); let task = service - .GetFolder(&BSTR::from(format!("\\{folder}")))? + .GetFolder(&BSTR::from(format!(r"\{folder}")))? .GetTask(&BSTR::from(name))?; // Task Scheduler counts actions from one. let action: IExecAction = task.Definition()?.Actions()?.get_Item(1)?.cast()?; diff --git a/src/win.rs b/src/win.rs index 47c4419..85fe8dd 100644 --- a/src/win.rs +++ b/src/win.rs @@ -558,7 +558,7 @@ pub struct SingleInstance { impl SingleInstance { /// Acquire the session-local mutex `name`, or fail if another process holds it. pub fn acquire(name: &str) -> Result { - let name = HSTRING::from(format!("Local\\{name}")); + let name = HSTRING::from(format!(r"Local\{name}")); // SAFETY: `name` is NUL-terminated and outlives the call; the handle is // owned by `SingleInstance` and closed on drop. let handle = unsafe { CreateMutexW(None, true, PCWSTR(name.as_ptr())) } @@ -580,7 +580,7 @@ impl SingleInstance { /// mutex creates nothing, and the handle is closed before returning so /// the object does not outlive the process that owns it. pub fn is_held(name: &str) -> bool { - let name = HSTRING::from(format!("Local\\{name}")); + let name = HSTRING::from(format!(r"Local\{name}")); // SAFETY: `name` is NUL-terminated and outlives the call; a handle // that comes back is closed here and kept nowhere. match unsafe { OpenMutexW(SYNCHRONIZATION_SYNCHRONIZE, false, PCWSTR(name.as_ptr())) } {