From 5bc7c01515a5ea4609452e23928d9d1e658d7c84 Mon Sep 17 00:00:00 2001 From: Arthurvroum Date: Wed, 25 Nov 2026 03:52:12 +0100 Subject: [PATCH 1/3] 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/3] 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( From 160b6222bae89c433b05fb81c073332eacc2c7e5 Mon Sep 17 00:00:00 2001 From: Arthurvroum Date: Wed, 25 Nov 2026 03:54:59 +0100 Subject: [PATCH 3/3] fix: report incomplete scans and keep their results out of the cache When a selected tool cannot run, ctrace still writes the SARIF of the others and exits 3. The extension announced a complete analysis, and the incremental scan cached the partial report, so the file was never retried. On WSL, the fallback script ended with its cleanup command, whose status hid the CLI's. - Exit 3 marks the file incomplete: its findings are shown, and the run ends with "Analysis incomplete", naming the tools that could not run from ctrace's output. Exit 2 (completed with findings) is unchanged. - Only complete analyses are cached; an incomplete file is analysed again on the next scan. Cache entries written before this flag existed may be partial, so they are redone once. - The WSL fallback script keeps ctrace's exit status after cleaning up. Builds on the WSL command changes of #39 and #40. Fixes #34 --- src/ctrace/CommandBuilder.ts | 2 +- src/ctrace/RunOutcome.ts | 23 ++++++++ src/ctrace/WorkspaceScanner.ts | 7 ++- src/extension.ts | 29 ++++++++- src/test-workspace/incomplete.test.ts | 84 +++++++++++++++++++++++++++ src/test/findings.test.ts | 25 +++++++- src/test/runOutcome.test.ts | 24 ++++++++ src/test/wslCommand.test.ts | 2 + 8 files changed, 189 insertions(+), 7 deletions(-) create mode 100644 src/ctrace/RunOutcome.ts create mode 100644 src/test-workspace/incomplete.test.ts create mode 100644 src/test/runOutcome.test.ts diff --git a/src/ctrace/CommandBuilder.ts b/src/ctrace/CommandBuilder.ts index 967966d..92bd49c 100755 --- a/src/ctrace/CommandBuilder.ts +++ b/src/ctrace/CommandBuilder.ts @@ -399,7 +399,7 @@ async function finishFallbackCommand( const libDir = getLibDirForBinary(ctracePath); const libEnv = libDir ? `export LD_LIBRARY_PATH=${shellEscapeArg(toWslPath(libDir))}:"$LD_LIBRARY_PATH" && ` : ''; - const script = `${wslToolEnvironment()}${libEnv}cp ${shellEscapeArg(wBin)} ${shellEscapeArg(lBin)} && chmod +x ${shellEscapeArg(lBin)} && ${shellEscapeArg(lBin)} --input ${shellEscapeArg(wInput)}${extraArgs} ${validatedParams}; rm -f ${shellEscapeArg(lBin)}`; + const script = `${wslToolEnvironment()}${libEnv}cp ${shellEscapeArg(wBin)} ${shellEscapeArg(lBin)} && chmod +x ${shellEscapeArg(lBin)} && ${shellEscapeArg(lBin)} --input ${shellEscapeArg(wInput)}${extraArgs} ${validatedParams}; status=$?; rm -f ${shellEscapeArg(lBin)}; exit "$status"`; return await writeWslScript(script, null, tempFiles); } diff --git a/src/ctrace/RunOutcome.ts b/src/ctrace/RunOutcome.ts new file mode 100644 index 0000000..756f89c --- /dev/null +++ b/src/ctrace/RunOutcome.ts @@ -0,0 +1,23 @@ +/** ctrace exit codes (--fail-on): 2 = completed with findings, 3 = a tool could not run. */ +export const EXIT_FINDINGS = 2; +export const EXIT_INCOMPLETE = 3; + +/** + * The tools ctrace names as not run, from lines like + * "[ERROR] Analysis incomplete: tscancode could not run (exit code 3)" and + * "Error: Command not found in PATH: ikos". + */ +export function failedTools(output: string): string[] { + const tools: string[] = []; + const add = (name: string) => { + const tool = name.trim(); + if (tool && !tools.includes(tool)) { tools.push(tool); } + }; + for (const match of output.matchAll(/Analysis incomplete:\s*(.+?)\s+could not run/gi)) { + match[1].split(/\s*,\s*|\s+and\s+/).forEach(add); + } + for (const match of output.matchAll(/Command not found in PATH:\s*([\w.+-]+)/gi)) { + add(match[1]); + } + return tools; +} diff --git a/src/ctrace/WorkspaceScanner.ts b/src/ctrace/WorkspaceScanner.ts index bf58c8f..61aa3a8 100755 --- a/src/ctrace/WorkspaceScanner.ts +++ b/src/ctrace/WorkspaceScanner.ts @@ -18,6 +18,11 @@ export interface WorkspaceFile { export interface CachedFileAnalysis { sarif: SarifLog; stack: StackReport | null; + /** + * Every requested tool ran. Only complete analyses are cached; entries + * saved before this flag existed may hold partial results and are redone. + */ + complete?: boolean; } export interface PartitionResult { @@ -113,7 +118,7 @@ export async function partitionFiles(files: string[], contextKey: string): Promi for (const fsPath of files) { const hash = await fileContentHash(fsPath); const entry = _analysisCache.get(fsPath); - if (hash && entry && entry.hash === hash && entry.contextKey === contextKey) { + if (hash && entry && entry.hash === hash && entry.contextKey === contextKey && entry.analysis.complete === true) { cached.set(fsPath, entry.analysis); } else { changed.push({ fsPath, hash: hash ?? '' }); diff --git a/src/extension.ts b/src/extension.ts index 37efc8e..5a2c05f 100755 --- a/src/extension.ts +++ b/src/extension.ts @@ -29,6 +29,7 @@ import { checkDependencies, installDependencies } from './ctrace/DependencyInsta import { StackManager } from './ctrace/StackManager'; import { parseStackReport, mergeStackReports } from './ctrace/StackParser'; import { FindingsStore } from './ctrace/FindingsStore'; +import { EXIT_INCOMPLETE, failedTools } from './ctrace/RunOutcome'; export function activate(context: vscode.ExtensionContext) { @@ -444,6 +445,8 @@ export function activate(context: vscode.ExtensionContext) { const step = queue.length > 0 ? 100 / queue.length : 100; let hadToolExecutionWarning = false; + // Files whose run exited 3: their findings are shown, but some tools did not run. + const incompleteRuns: { file: string; tools: string[] }[] = []; try { for (let i = 0; i < queue.length; i++) { if (token.isCancellationRequested) { @@ -503,6 +506,12 @@ export function activate(context: vscode.ExtensionContext) { output.appendLine(`[exit ${exitCode ?? 0}]`); const combined = (stdout || '') + (stderr || ''); + const incomplete = exitCode === EXIT_INCOMPLETE; + if (incomplete) { + const tools = failedTools(combined); + incompleteRuns.push({ file: fileName, tools }); + output.appendLine(`[ctrace] Incomplete analysis of ${fileName}: ${tools.length ? `${tools.join(', ')} could not run` : 'a tool could not run'}.`); + } if (/(?:command not found|unrecognized command line option|cannot execute binary file|execvp: No such file or directory|can't open file '.*(?:flawfinder|ikos|tscancode|cppcheck).*':\s*\[Errno 2\] No such file or directory|\/opt\/homebrew\/bin\/cppcheck:\s*(?:No such file or directory|not found))/i.test(combined)) { hadToolExecutionWarning = true; output.appendLine('[ctrace warning] Note: one or more static analysis tools (e.g. cppcheck/flawfinder/ikos/tscancode) could not be executed by ctrace.'); @@ -581,8 +590,9 @@ export function activate(context: vscode.ExtensionContext) { allSarif.push(sarif); lastSarifByFile.set(fp, sarif); updateDiagnostics(sarif, diagnosticCollection, fp, !scanWorkspace, { isIgnored }); - if (incremental && !killed && queue[i].hash) { - cacheFileAnalysis(queue[i], contextKeys[language] ?? '', { sarif, stack: fileStack }); + // An incomplete result is not cached: the next scan retries the file. + if (incremental && !killed && !incomplete && queue[i].hash) { + cacheFileAnalysis(queue[i], contextKeys[language] ?? '', { sarif, stack: fileStack, complete: true }); } } else if (!scanWorkspace) { // Single-file mode: report parse failure immediately @@ -633,7 +643,20 @@ export function activate(context: vscode.ExtensionContext) { ? ` across ${filesToAnalyze.length} files` : '') + (cachedCount > 0 ? ` (${cachedCount} unchanged, reused from cache)` : ''); - if (total > 0) { + if (incompleteRuns.length > 0) { + const tools = [...new Set(incompleteRuns.flatMap(run => run.tools))]; + const which = tools.length > 0 ? tools.join(', ') : 'some tools'; + const files = incompleteRuns.length === 1 ? incompleteRuns[0].file : `${incompleteRuns.length} files`; + vscode.window.showWarningMessage( + `Analysis incomplete — ${total} issue${total === 1 ? '' : 's'} found${filesSuffix}, but ${which} could not run on ${files}: their findings are missing. See the Ctrace output channel.` + ); + sidebarProvider.postMessage({ + type: 'analysis-status', + status: 'error', + message: 'Analysis incomplete', + detail: `${which} could not run on ${files}`, + }); + } else if (total > 0) { vscode.window.showInformationMessage( `Analysis complete — ${total} issue${total > 1 ? 's' : ''} found${filesSuffix}.` ); diff --git a/src/test-workspace/incomplete.test.ts b/src/test-workspace/incomplete.test.ts new file mode 100644 index 0000000..be1d8de --- /dev/null +++ b/src/test-workspace/incomplete.test.ts @@ -0,0 +1,84 @@ +import * as assert from 'assert'; +import * as fs from 'fs'; +import * as os from 'os'; +import * as path from 'path'; +import * as vscode from 'vscode'; +import * as AnalysisRunner from '../ctrace/AnalysisRunner'; +import * as BinaryUpdater from '../ctrace/BinaryUpdater'; +import { setMockWslAvailableForTesting } from '../ctrace/CommandBuilder'; +import { setScanDirectoryForTesting } from '../ctraceRunner'; + +/** Workspace scans where ctrace exits 3 (a tool could not run) on one file. */ +suite('Incomplete scans', function () { + this.timeout(60000); + + const runner = AnalysisRunner as { runCommand: typeof AnalysisRunner.runCommand }; + const updater = BinaryUpdater as { ensureBinary: typeof BinaryUpdater.ensureBinary }; + const originalRunCommand = runner.runCommand; + const originalEnsureBinary = updater.ensureBinary; + let work = ''; + let root = ''; + let launched: string[] = []; + + const inputOf = (command: string) => command.match(/--input '([^']+)'/)?.[1] ?? ''; + const sarifFor = (file: string) => JSON.stringify({ + $schema: 'https://json.schemastore.org/sarif-2.1.0.json', + version: '2.1.0', + runs: [{ + tool: { driver: { name: 'cppcheck' } }, + results: [{ + ruleId: 'partialRule', level: 'warning', message: { text: `found in ${path.basename(file)}` }, + locations: [{ physicalLocation: { artifactLocation: { uri: file }, region: { startLine: 1 } } }], + }], + }], + }); + const scan = () => vscode.commands.executeCommand('ctrace.runWorkspaceAnalysis', { + // No C tool selected: the C dependency check would wait for an answer. + uiState: { staticTools: ['coretrace-python-analyzer'], dynamicEnabled: false }, + }); + const analysed = () => launched.filter(c => c.includes('--sarif-format')).map(c => path.basename(inputOf(c))).sort(); + + suiteSetup(async () => { + root = vscode.workspace.workspaceFolders![0].uri.fsPath; + work = fs.mkdtempSync(path.join(os.tmpdir(), 'ctrace-incomplete-')); + const fakeBinary = path.join(work, 'ctrace'); + fs.writeFileSync(fakeBinary, '#!/bin/sh\n', { mode: 0o755 }); + updater.ensureBinary = async () => fakeBinary; + runner.runCommand = async (command: string) => { + launched.push(command); + if (!command.includes('--sarif-format')) { return { stdout: '', stderr: '', exitCode: 0 }; } + const file = inputOf(command); + // sample.c: findings, but tscancode could not run. app.py: complete, with findings. + return file.endsWith('sample.c') + ? { stdout: sarifFor(file), stderr: '[ERROR] Analysis incomplete: tscancode could not run (exit code 3)', exitCode: 3 } + : { stdout: sarifFor(file), stderr: '', exitCode: 2 }; + }; + setMockWslAvailableForTesting(true); + setScanDirectoryForTesting(path.join(work, 'scan')); + await vscode.extensions.getExtension('CoreTrace.coretrace')!.activate(); + }); + + suiteTeardown(() => { + runner.runCommand = originalRunCommand; + updater.ensureBinary = originalEnsureBinary; + setMockWslAvailableForTesting(null); + setScanDirectoryForTesting(undefined); + fs.rmSync(work, { recursive: true, force: true }); + }); + + test('the findings of an incomplete file are shown, and the file is retried on the next scan', async function () { + if (process.platform === 'win32') { this.skip(); } + await vscode.commands.executeCommand('ctrace.clearAnalysisCache'); + launched = []; + await scan(); + assert.deepStrictEqual(analysed(), ['app.py', 'sample.c']); + const diagnostics = vscode.languages.getDiagnostics(vscode.Uri.file(path.join(root, 'sample.c'))) + .filter(d => d.source?.startsWith('CoreTrace')); + assert.strictEqual(diagnostics.length, 1, 'the available findings of the incomplete file must be shown'); + + launched = []; + await scan(); + // app.py (exit 2, complete) comes from the cache; sample.c (exit 3) is analysed again. + assert.deepStrictEqual(analysed(), ['sample.c']); + }); +}); diff --git a/src/test/findings.test.ts b/src/test/findings.test.ts index 3fda5c6..4e663fc 100644 --- a/src/test/findings.test.ts +++ b/src/test/findings.test.ts @@ -193,7 +193,7 @@ suite('Incremental workspace scan Test Suite', () => { let partition = await partitionFiles([a, b], 'key1'); assert.deepStrictEqual(partition.changed.map(f => f.fsPath), [a, b]); for (const file of partition.changed) { - cacheFileAnalysis(file, 'key1', { sarif: emptySarif(path.basename(file.fsPath)), stack: null }); + cacheFileAnalysis(file, 'key1', { sarif: emptySarif(path.basename(file.fsPath)), stack: null, complete: true }); } partition = await partitionFiles([a, b], 'key1'); @@ -221,7 +221,7 @@ suite('Incremental workspace scan Test Suite', () => { try { await initAnalysisCache(storage); for (const file of (await partitionFiles([a, gone], 'key')).changed) { - cacheFileAnalysis(file, 'key', { sarif: emptySarif('x'), stack: null }); + cacheFileAnalysis(file, 'key', { sarif: emptySarif('x'), stack: null, complete: true }); } fs.unlinkSync(gone); await persistAnalysisCache(); @@ -242,6 +242,27 @@ suite('Incremental workspace scan Test Suite', () => { } }); + test('incomplete analyses, and entries saved before the flag existed, are analysed again', async () => { + const dir = tempDir('ctrace-incr-'); + const done = path.join(dir, 'done.c'); + const partial = path.join(dir, 'partial.c'); + const legacy = path.join(dir, 'legacy.c'); + for (const file of [done, partial, legacy]) { fs.writeFileSync(file, `int ${path.basename(file, '.c')};`); } + try { + const [d, p, l] = (await partitionFiles([done, partial, legacy], 'key')).changed; + cacheFileAnalysis(d, 'key', { sarif: emptySarif('done'), stack: null, complete: true }); + cacheFileAnalysis(p, 'key', { sarif: emptySarif('partial'), stack: null, complete: false }); + // As written by a version without the flag. + cacheFileAnalysis(l, 'key', { sarif: emptySarif('legacy'), stack: null }); + + const partition = await partitionFiles([done, partial, legacy], 'key'); + assert.deepStrictEqual([...partition.cached.keys()], [done]); + assert.deepStrictEqual(partition.changed.map(f => f.fsPath).sort(), [legacy, partial].sort()); + } finally { + fs.rmSync(dir, { recursive: true, force: true }); + } + }); + test('context key changes with the options and the dependency files', async () => { const dir = tempDir('ctrace-incr-'); const compdb = path.join(dir, 'compile_commands.json'); diff --git a/src/test/runOutcome.test.ts b/src/test/runOutcome.test.ts new file mode 100644 index 0000000..d06f85b --- /dev/null +++ b/src/test/runOutcome.test.ts @@ -0,0 +1,24 @@ +import * as assert from 'assert'; +import { failedTools } from '../ctrace/RunOutcome'; + +suite('Run outcome Test Suite', () => { + test('the tools that could not run are read from ctrace output', () => { + // As printed by ctrace 0.85 with tscancode missing. + const output = [ + '|42| == CoreTrace == [INFO] (cppcheck) Diagnostics summary: info=0, warning=0, error=1', + 'Error: Command not found in PATH: tscancode', + '|42| == CoreTrace == [ERROR] Analysis incomplete: tscancode could not run (exit code 3)', + ].join('\n'); + assert.deepStrictEqual(failedTools(output), ['tscancode']); + }); + + test('several tools in one line or several lines are all named once', () => { + const output = 'Analysis incomplete: ikos, tscancode and coretrace-runtime-analyzer could not run (exit code 3)\n' + + 'Error: Command not found in PATH: coretrace-runtime-analyzer'; + assert.deepStrictEqual(failedTools(output), ['ikos', 'tscancode', 'coretrace-runtime-analyzer']); + }); + + test('a complete run names no tool', () => { + assert.deepStrictEqual(failedTools('[INFO] Verdict: info=0, warning=1, error=0, fail-on=error (exit code 0)'), []); + }); +}); diff --git a/src/test/wslCommand.test.ts b/src/test/wslCommand.test.ts index 4550c1c..5253045 100644 --- a/src/test/wslCommand.test.ts +++ b/src/test/wslCommand.test.ts @@ -55,6 +55,8 @@ suite('WSL command Test Suite', () => { 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 "/); + // The script cleans up its copy after ctrace but exits with ctrace's code. + assert.match(text, /; status=\$\?; rm -f '[^']+'; exit "\$status"\n?$/, text); }); test('a source inside a WSL distribution with spaces runs in that distribution', async () => {