From 5bc7c01515a5ea4609452e23928d9d1e658d7c84 Mon Sep 17 00:00:00 2001 From: Arthurvroum Date: Wed, 25 Nov 2026 03:52:12 +0100 Subject: [PATCH 1/2] fix: test WSL paths with spaces in both Windows branches and clean up on rejection Paths with spaces are accepted since the validator checks option names strictly and only rejects shell syntax in values. Two gaps remained: - In the temporary-copy branch, the CLI was copied before the arguments were validated, so a rejected argument left the copy behind. They are now validated first, and temporary files are removed on any failure. - Neither Windows branch was tested outside Windows. The calls to wsl.exe are now replaceable, so a report and a compile database under "C:\My Project" are checked to stay single arguments through the temporary-copy branch and through the branch that runs in the WSL distribution holding the source, on every platform. Fixes #39 --- src/ctrace/CommandBuilder.ts | 54 ++++++++++++++++++++----- src/test/wslCommand.test.ts | 78 ++++++++++++++++++++++++++++++++++++ 2 files changed, 122 insertions(+), 10 deletions(-) create mode 100644 src/test/wslCommand.test.ts diff --git a/src/ctrace/CommandBuilder.ts b/src/ctrace/CommandBuilder.ts index 7e5047a..ad90dc2 100755 --- a/src/ctrace/CommandBuilder.ts +++ b/src/ctrace/CommandBuilder.ts @@ -52,6 +52,23 @@ function shellEscapeArg(arg: string): string { return "'" + arg.replace(/'/g, "'\\''") + "'"; } +type WslExec = (args: string[], options: { encoding?: BufferEncoding; timeout: number }) => string | Buffer; + +let wslExec: WslExec = (args, options) => cp.execFileSync('wsl', args, options); + +/** + * Replaces the calls to wsl.exe, so the Windows command builders can be + * tested on any platform. + */ +export function setWslExecForTesting(fake: WslExec | null): void { + wslExec = fake ?? ((args, options) => cp.execFileSync('wsl', args, options)); +} + +/** The Windows builder, for tests on other platforms (with setMockWslAvailableForTesting). */ +export function buildWindowsCommandForTesting(ctracePath: string, inputFilePath: string, params: string): Promise { + return buildWindowsCommand(ctracePath, inputFilePath, params); +} + /** * Converts a Windows-style path to its WSL POSIX equivalent using `wslpath`. * Falls back to a simple `/mnt//` prefix substitution if the command fails. @@ -63,7 +80,7 @@ function toWslPath(winPath: string, distroName: string | null = null): string { ...(distroName ? ['-d', distroName] : []), 'wslpath', '-u', normalized, ]; - return cp.execFileSync('wsl', args, { timeout: 5000 }).toString().trim(); + return wslExec(args, { timeout: 5000 }).toString().trim(); } catch { return normalized.replace(/^([a-zA-Z]):/, (_, d) => `/mnt/${d.toLowerCase()}`); } @@ -152,7 +169,7 @@ export function isWslAvailable(): boolean { return cachedWslAvailable.result; } try { - const stdout = cp.execFileSync('wsl', ['-l', '-q'], { encoding: 'utf16le', timeout: 5000 }); + const stdout = wslExec(['-l', '-q'], { encoding: 'utf16le', timeout: 5000 }).toString(); const clean = stdout.replace(/[\u0000-\u001F\u007F-\u009F\uFEFF\uFFFD]/g, '').trim(); const available = Boolean(clean) && !/no installed distributions|no distribution/i.test(clean); cachedWslAvailable = { result: available, timestamp: now }; @@ -203,7 +220,7 @@ function trySmartDistroExecution( const clean = (s: string) => s.replace(/[\u0000-\u001F\u007F-\u009F\uFEFF\uFFFD]/g, '').trim(); // execFileSync avoids spawning a shell (cmd.exe); encoding:'utf16le' is // supported by Node's execFileSync just as it is by execSync. - const stdout = cp.execFileSync('wsl', ['-l', '-v'], { encoding: 'utf16le', timeout: 5000 }); + const stdout = wslExec(['-l', '-v'], { encoding: 'utf16le', timeout: 5000 }).toString(); const lines = stdout.split(/[\r\n]+/).filter(l => l.trim()); let defaultDistro = ''; @@ -282,7 +299,7 @@ function resolveDistroName(distro: string): string | null { const safeDistro = distro.replace(/["'`\\]/g, ''); if (!safeDistro) { return null; } try { - cp.execFileSync('wsl', ['-d', safeDistro, 'true'], { timeout: 5000 }); + wslExec(['-d', safeDistro, 'true'], { timeout: 5000 }); return safeDistro; } catch { // fall through @@ -315,12 +332,7 @@ async function buildFallbackCommand( const tempBin = path.join(os.tmpdir(), `ctrace-bin-${stamp}`); const lBin = `/tmp/ctrace-${stamp}`; - await fs.promises.copyFile(ctracePath, tempBin); - tempFiles.push(tempBin); - - const wBin = toWslPath(tempBin); - const wInput = toWslPath(inputFilePath); - + // Validated before the CLI is copied: a rejected argument leaves nothing behind. const validatedParamsTokens = parseAndValidateParams(params).map(token => { const eqIndex = token.indexOf('='); if (eqIndex > 0) { @@ -333,6 +345,28 @@ async function buildFallbackCommand( return token; }); const validatedParams = validatedParamsTokens.map(shellEscapeArg).join(' '); + + await fs.promises.copyFile(ctracePath, tempBin); + tempFiles.push(tempBin); + try { + return await finishFallbackCommand(ctracePath, inputFilePath, validatedParams, tempBin, lBin, tempFiles, compileCommands); + } catch (error) { + await Promise.all(tempFiles.map(file => fs.promises.unlink(file).catch(() => { /* already gone */ }))); + throw error; + } +} + +async function finishFallbackCommand( + ctracePath: string, + inputFilePath: string, + validatedParams: string, + tempBin: string, + lBin: string, + tempFiles: string[], + compileCommands: boolean +): Promise { + const wBin = toWslPath(tempBin); + const wInput = toWslPath(inputFilePath); const extraArgs = compileCommands ? ` --compile-commands ${shellEscapeArg(wInput)}` : ''; const libDir = getLibDirForBinary(ctracePath); diff --git a/src/test/wslCommand.test.ts b/src/test/wslCommand.test.ts new file mode 100644 index 0000000..4addff3 --- /dev/null +++ b/src/test/wslCommand.test.ts @@ -0,0 +1,78 @@ +import * as assert from 'assert'; +import * as fs from 'fs'; +import * as os from 'os'; +import * as path from 'path'; +import { buildWindowsCommandForTesting, setMockWslAvailableForTesting, setWslExecForTesting } from '../ctrace/CommandBuilder'; +import { shellQuoteArgs } from '../ctraceRunner'; + +/** + * The two Windows execution branches, on any platform, with a fake wsl.exe: + * a source in a WSL distribution (UNC path), and a Windows source run through + * a temporary copy of the CLI. + */ +suite('WSL command Test Suite', () => { + let work = ''; + let built: { command: string; tempFiles: string[] } | undefined; + + /** wslpath and the distribution list, as wsl.exe answers them. */ + const fakeWsl = (args: string[]) => { + if (args[0] === '-l') { return ' NAME STATE VERSION\n* Ubuntu Running 2\n Debian Stopped 2\n'; } + if (args.includes('wslpath')) { + const target = args[args.length - 1].replace(/\\/g, '/'); + const unc = target.match(/^\/\/wsl(?:\$|\.localhost)\/[^/]+(\/.*)$/i); + if (unc) { return unc[1]; } + return target.replace(/^([a-zA-Z]):/, (_m, drive: string) => `/mnt/${drive.toLowerCase()}`); + } + return ''; + }; + + setup(() => { + work = fs.mkdtempSync(path.join(os.tmpdir(), 'ctrace-wsl-')); + setMockWslAvailableForTesting(true); + setWslExecForTesting(fakeWsl); + built = undefined; + }); + + teardown(() => { + for (const file of built?.tempFiles ?? []) { fs.rmSync(file, { force: true }); } + setMockWslAvailableForTesting(null); + setWslExecForTesting(null); + fs.rmSync(work, { recursive: true, force: true }); + }); + + const script = () => fs.readFileSync(built!.tempFiles.find(file => file.endsWith('.sh'))!, 'utf8'); + const ctrace = () => { + const file = path.join(work, 'ctrace'); + fs.writeFileSync(file, 'binary'); + return file; + }; + + test('a Windows path with spaces stays one argument through the temporary-copy branch', async () => { + const args = ['--report-file=C:\\My Project\\report.json', '--compile-commands=C:\\My Project\\build\\compile_commands.json', '--static']; + built = await buildWindowsCommandForTesting(ctrace(), 'C:\\My Project\\src\\main.c', shellQuoteArgs(args)); + const text = script(); + assert.ok(text.includes("'--report-file=/mnt/c/My Project/report.json'"), text); + assert.ok(text.includes("'--compile-commands=/mnt/c/My Project/build/compile_commands.json'"), text); + assert.ok(text.includes("--input '/mnt/c/My Project/src/main.c'"), text); + assert.match(built.command, /^wsl --exec sh "/); + }); + + test('a source inside a WSL distribution with spaces runs in that distribution', async () => { + const args = ['--report-file=C:\\My Project\\report.json']; + built = await buildWindowsCommandForTesting(ctrace(), '\\\\wsl$\\Debian\\home\\me\\My Project\\main.c', shellQuoteArgs(args)); + const text = script(); + assert.ok(text.includes("--input '/home/me/My Project/main.c'"), text); + assert.ok(text.includes("'--report-file=/mnt/c/My Project/report.json'"), text); + assert.match(built.command, /^wsl -d "Debian" --exec sh "/, 'the non-default distribution must be used'); + }); + + test('an unsafe argument is still rejected, and leaves no temporary copy behind', async () => { + const before = new Set(fs.readdirSync(os.tmpdir()).filter(name => name.startsWith('ctrace-bin-'))); + await assert.rejects( + buildWindowsCommandForTesting(ctrace(), 'C:\\src\\main.c', shellQuoteArgs(['--report-file=C:\\x;rm -rf ~'])), + /Unsafe CLI parameter rejected/ + ); + const after = fs.readdirSync(os.tmpdir()).filter(name => name.startsWith('ctrace-bin-') && !before.has(name)); + assert.deepStrictEqual(after, [], 'the temporary CLI copy must be removed'); + }); +}); From 515cace87299ca242b2763ff6227996f9173d742 Mon Sep 17 00:00:00 2001 From: Arthurvroum Date: Wed, 25 Nov 2026 03:53:15 +0100 Subject: [PATCH 2/2] fix: check and install analyzers in the WSL distribution that runs the scan With two WSL distributions, a source under \\wsl$\ runs in that distribution, but the preflight and the installer always used the default one: checking or repairing tools there gave the wrong answer. - executionDistro() picks the distribution with the same rule as the command builder: the one of a WSL path when it is not the default, else the default (null). Ordinary Windows paths keep the default. - The preflight checks the analyzers there, and its Install button installs them there. The sidebar's install button uses the distribution of the active file. Builds on the replaceable wsl.exe calls of #39. Fixes #40 --- src/ctrace/CommandBuilder.ts | 27 +++++++++++++++++++++++++++ src/extension.ts | 21 ++++++++++++++++----- src/test/wslCommand.test.ts | 18 +++++++++++++++++- 3 files changed, 60 insertions(+), 6 deletions(-) diff --git a/src/ctrace/CommandBuilder.ts b/src/ctrace/CommandBuilder.ts index ad90dc2..967966d 100755 --- a/src/ctrace/CommandBuilder.ts +++ b/src/ctrace/CommandBuilder.ts @@ -146,6 +146,33 @@ function parseWslUNC(p: string): { distro: string; internalPath: string } | null return null; } +/** + * The WSL distribution a scan of these paths runs in: the one named by a + * WSL path (\\wsl$\Debian\...) when it is not the default one, else null + * for the default distribution. Same rule as trySmartDistroExecution(), so + * the analyzers are checked and installed where they will run. + */ +export function executionDistro(...paths: (string | undefined)[]): string | null { + const detected = paths.map(p => p ? parseWslUNC(p) : null).find(Boolean)?.distro; + if (!detected) { return null; } + try { + const clean = (s: string) => s.replace(/[\u0000-\u001F\u007F-\u009F\uFEFF\uFFFD]/g, '').trim(); + const lines = wslExec(['-l', '-v'], { encoding: 'utf16le', timeout: 5000 }).toString().split(/[\r\n]+/).filter(l => l.trim()); + let defaultDistro = ''; + let matched = ''; + for (const line of lines) { + if (line.includes('NAME') && line.includes('STATE')) { continue; } + const name = clean(line.replace('*', '').trim().split(/\s+/)[0] ?? ''); + if (line.trim().startsWith('*')) { defaultDistro = name; } + if (name.toLowerCase() === detected.toLowerCase()) { matched = name; } + } + if (!matched || matched === defaultDistro) { return null; } + return resolveDistroName(matched); + } catch { + return null; + } +} + let cachedWslAvailable: { result: boolean; timestamp: number } | null = null; let mockWslAvailable: boolean | null = null; diff --git a/src/extension.ts b/src/extension.ts index a498c0d..37efc8e 100755 --- a/src/extension.ts +++ b/src/extension.ts @@ -4,7 +4,7 @@ import * as path from 'path'; import { SidebarProvider } from './SidebarProvider'; import { locateBinary } from './ctrace/BinaryLocator'; -import { buildCommand, isWslAvailable } from './ctrace/CommandBuilder'; +import { buildCommand, executionDistro, isWslAvailable } from './ctrace/CommandBuilder'; import { runCommand, DEFAULT_TIMEOUT_MS } from './ctrace/AnalysisRunner'; import { parseSarifOutput } from './ctrace/SarifParser'; import { updateDiagnostics, clearDiagnostics, getFindingForDiagnostic, FindingRef } from './ctrace/DiagnosticsManager'; @@ -147,7 +147,7 @@ export function activate(context: vscode.ExtensionContext) { // ── Command: ctrace.installDependencies ────────────────────────────────── context.subscriptions.push( - vscode.commands.registerCommand('ctrace.installDependencies', async () => { + vscode.commands.registerCommand('ctrace.installDependencies', async (arg?: { distro?: string | null }) => { if (process.platform === 'win32' && !isWslAvailable()) { output.appendLine('[ctrace] Windows Subsystem for Linux (WSL) is required to install dependencies on Windows.'); promptWslInstallation(); @@ -161,7 +161,14 @@ export function activate(context: vscode.ExtensionContext) { cancellable: false, }, async (progress) => { - await installDependencies(output, progress); + // Install where the scan runs: the distribution a preflight + // asked for, else the one of the active file (WSL paths). + const activeFile = vscode.window.activeTextEditor?.document.uri.fsPath; + const distro = arg && 'distro' in arg + ? arg.distro ?? null + : process.platform === 'win32' ? executionDistro(activeFile) : null; + if (distro) { output.appendLine(`[ctrace] Installing the analyzers in the WSL distribution ${distro}.`); } + await installDependencies(output, progress, distro); } ); }) @@ -259,7 +266,11 @@ export function activate(context: vscode.ExtensionContext) { const requestedStaticTools: string[] = (uiState.staticTools ?? ['cppcheck', 'flawfinder', 'ikos', 'tscancode', 'ctrace_stack_analyzer']) .filter(tool => tool !== 'coretrace-python-analyzer'); if (hasCFiles && uiState.staticEnabled !== false && requestedStaticTools.length > 0) { - const depStatus = await checkDependencies(); + // The analyzers are checked in the distribution that will run the scan. + const toolsDistro = process.platform === 'win32' + ? executionDistro(scanWorkspace ? workspaceRoot : filesToAnalyze[0]) + : null; + const depStatus = await checkDependencies(toolsDistro); const missingRequested = requestedStaticTools.filter((t) => depStatus.missing.includes(t)); if (missingRequested.length > 0) { const action = await vscode.window.showWarningMessage( @@ -269,7 +280,7 @@ export function activate(context: vscode.ExtensionContext) { ); if (action === 'Install Analyzers') { sidebarProvider.postMessage({ type: 'analysis-done' }); - vscode.commands.executeCommand('ctrace.installDependencies'); + vscode.commands.executeCommand('ctrace.installDependencies', { distro: toolsDistro }); return; } } diff --git a/src/test/wslCommand.test.ts b/src/test/wslCommand.test.ts index 4addff3..4550c1c 100644 --- a/src/test/wslCommand.test.ts +++ b/src/test/wslCommand.test.ts @@ -2,7 +2,7 @@ import * as assert from 'assert'; import * as fs from 'fs'; import * as os from 'os'; import * as path from 'path'; -import { buildWindowsCommandForTesting, setMockWslAvailableForTesting, setWslExecForTesting } from '../ctrace/CommandBuilder'; +import { buildWindowsCommandForTesting, executionDistro, setMockWslAvailableForTesting, setWslExecForTesting } from '../ctrace/CommandBuilder'; import { shellQuoteArgs } from '../ctraceRunner'; /** @@ -66,6 +66,22 @@ suite('WSL command Test Suite', () => { assert.match(built.command, /^wsl -d "Debian" --exec sh "/, 'the non-default distribution must be used'); }); + test('the analyzers are checked in the distribution that runs the scan', () => { + // Debian is not the default: a scan of its files runs, and must be checked, there. + assert.strictEqual(executionDistro('\\\\wsl$\\Debian\\home\\me\\main.c'), 'Debian'); + assert.strictEqual(executionDistro('\\\\wsl.localhost\\debian\\home\\me\\main.c'), 'Debian'); + // The default distribution, an ordinary Windows path, or an unknown distribution keep the default (null). + assert.strictEqual(executionDistro('\\\\wsl$\\Ubuntu\\home\\me\\main.c'), null); + assert.strictEqual(executionDistro('C:\\My Project\\main.c'), null); + assert.strictEqual(executionDistro('\\\\wsl$\\Arch\\home\\me\\main.c'), null); + assert.strictEqual(executionDistro(undefined), null); + }); + + test('without wsl.exe, the default distribution is kept', () => { + setWslExecForTesting(() => { throw new Error('wsl.exe not found'); }); + assert.strictEqual(executionDistro('\\\\wsl$\\Debian\\home\\me\\main.c'), null); + }); + test('an unsafe argument is still rejected, and leaves no temporary copy behind', async () => { const before = new Set(fs.readdirSync(os.tmpdir()).filter(name => name.startsWith('ctrace-bin-'))); await assert.rejects(