Skip to content
Open
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
83 changes: 72 additions & 11 deletions src/ctrace/CommandBuilder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<BuiltCommand> {
return buildWindowsCommand(ctracePath, inputFilePath, params);
}

/**
* Converts a Windows-style path to its WSL POSIX equivalent using `wslpath`.
* Falls back to a simple `/mnt/<drive>/` prefix substitution if the command fails.
Expand All @@ -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()}`);
}
Expand Down Expand Up @@ -129,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;

Expand All @@ -152,7 +196,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 };
Expand Down Expand Up @@ -203,7 +247,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 = '';
Expand Down Expand Up @@ -282,7 +326,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
Expand Down Expand Up @@ -315,12 +359,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) {
Expand All @@ -333,12 +372,34 @@ 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<BuiltCommand> {
const wBin = toWslPath(tempBin);
const wInput = toWslPath(inputFilePath);
const extraArgs = compileCommands ? ` --compile-commands ${shellEscapeArg(wInput)}` : '';

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);
}

Expand Down
23 changes: 23 additions & 0 deletions src/ctrace/RunOutcome.ts
Original file line number Diff line number Diff line change
@@ -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;
}
7 changes: 6 additions & 1 deletion src/ctrace/WorkspaceScanner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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 ?? '' });
Expand Down
50 changes: 42 additions & 8 deletions src/extension.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand All @@ -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) {

Expand Down Expand Up @@ -147,7 +148,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();
Expand All @@ -161,7 +162,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);
}
);
})
Expand Down Expand Up @@ -259,7 +267,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(
Expand All @@ -269,7 +281,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;
}
}
Expand Down Expand Up @@ -433,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) {
Expand Down Expand Up @@ -492,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.');
Expand Down Expand Up @@ -570,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
Expand Down Expand Up @@ -622,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}.`
);
Expand Down
Loading
Loading