diff --git a/media/main.js b/media/main.js
index 1ca549a..0e1c340 100755
--- a/media/main.js
+++ b/media/main.js
@@ -5,6 +5,7 @@
const runBtn = document.getElementById('run-btn');
const runLabel = document.getElementById('run-label');
const resultsContainer = document.getElementById('results-container');
+ const coverageNote = document.getElementById('coverage-note');
const vulnList = document.getElementById('vuln-list');
const vulnCount = document.getElementById('vuln-count');
const findingsSearch = document.getElementById('findings-search');
@@ -89,6 +90,7 @@
let settingsSearchRestore = null;
let analysisProfile = 'full';
let findings = [];
+ let appliedDynamicSetting = persistedState.appliedDynamicSetting;
let ignoredCount = 0;
let currentStatus = 'ready';
let isRunning = false;
@@ -402,6 +404,7 @@
function saveUiState() {
vscode.setState({
+ appliedDynamicSetting,
uiState: readCtraceUiState(),
scanWorkspace,
knownStaticTools: [...document.querySelectorAll('.static-tool')].map(tool => tool.value),
@@ -665,7 +668,7 @@
setRunning(true);
break;
case 'analysis-result':
- handleAnalysisResult(msg.data, msg.restored === true, msg.savedAt, msg.refresh === true);
+ handleAnalysisResult(msg.data, msg.restored === true, msg.savedAt, msg.refresh === true, msg.coverageNote);
break;
case 'clear-results':
clearDisplayedResults();
@@ -691,6 +694,15 @@
fileLabel.textContent = lastFileName;
}
break;
+ case 'set-dynamic-analysis':
+ if (msg.id !== appliedDynamicSetting) {
+ document.querySelectorAll('.dynamic-tool').forEach(tool => { tool.checked = msg.enabled === true; });
+ updateAnalysisModeStyles();
+ appliedDynamicSetting = msg.id;
+ saveUiState();
+ }
+ vscode.postMessage({ type: 'dynamic-setting-saved', id: msg.id });
+ break;
case 'compile-commands-selected':
setValue('compile-commands-path', msg.path || '');
saveUiState();
@@ -775,12 +787,16 @@
}
}
- function handleAnalysisResult(sarif, restored = false, savedAt, refresh = false) {
+ function handleAnalysisResult(sarif, restored = false, savedAt, refresh = false, omittedCoverage) {
+ coverageNote.textContent = omittedCoverage || '';
+ coverageNote.hidden = !omittedCoverage;
// A refresh only re-applies the ignore list: keep the current status.
if (!refresh) {
setRunning(false);
const savedLabel = Number.isFinite(savedAt) ? new Date(savedAt).toLocaleString() : 'Saved results';
- setStatus(restored ? 'Last analysis' : 'Analysis complete', restored ? savedLabel : 'Findings are shown below', 'success');
+ const title = omittedCoverage ? 'Partial analysis' : 'Analysis complete';
+ setStatus(restored ? (omittedCoverage ? 'Last partial analysis' : 'Last analysis') : title,
+ restored ? savedLabel : 'Findings are shown below', omittedCoverage ? 'warning' : 'success');
setProgress(100);
}
@@ -818,18 +834,14 @@
updateSummary(findings);
renderFilteredFindings();
- if (count === 0 && vulnList) {
- vulnList.innerHTML = '
No issues detected for the selected scope.';
- appendIgnoredNotice();
- if (typeof lucide !== 'undefined') { lucide.createIcons(); }
- }
-
if (tabVulnBadge) {
tabVulnBadge.textContent = String(count);
}
}
function clearDisplayedResults() {
+ coverageNote.hidden = true;
+ coverageNote.textContent = '';
findings = [];
stackModel = null;
stackExpanded = new Set();
@@ -1291,7 +1303,14 @@
if (findings.length > 0 && filtered.length === 0 && vulnList) {
vulnList.innerHTML = 'No findings match the current filters.';
}
- if (findings.length > 0) { appendIgnoredNotice(); }
+ if (findings.length === 0) {
+ const message = coverageNote.hidden ? 'No issues detected for the selected scope.' : 'No issues detected by the tools that ran.';
+ const item = document.createElement('li');
+ item.className = 'info-item';
+ item.textContent = message;
+ vulnList.appendChild(item);
+ }
+ appendIgnoredNotice();
}
function appendIgnoredNotice() {
diff --git a/media/style.css b/media/style.css
index a871db8..7674e00 100755
--- a/media/style.css
+++ b/media/style.css
@@ -1377,6 +1377,8 @@ select:focus-visible {
animation: status-pulse 1.4s ease-in-out infinite;
}
+#coverage-note { color: var(--vscode-editorWarning-foreground); }
+.status-dot.warning { background: var(--vscode-editorWarning-foreground); }
.status-dot.error { background: var(--vscode-errorForeground, #f14c4c); }
.status-dot.success { background: var(--vscode-charts-green, #73c991); }
diff --git a/src/SidebarProvider.ts b/src/SidebarProvider.ts
index 1bb6610..51dcdba 100755
--- a/src/SidebarProvider.ts
+++ b/src/SidebarProvider.ts
@@ -1,15 +1,33 @@
+import { randomUUID } from "crypto";
import * as vscode from "vscode";
import { isUpdatingBinary } from "./ctrace/BinaryUpdater";
import { StackManager } from "./ctrace/StackManager";
import { FindingsStore } from "./ctrace/FindingsStore";
+const PENDING_DISABLE = "coretrace.pendingDisableDynamic";
+
export class SidebarProvider implements vscode.WebviewViewProvider, vscode.Disposable {
_view?: vscode.WebviewView;
private _disposables: vscode.Disposable[] = [];
private _ready = false;
private _pendingMessages: any[] = [];
- constructor(private readonly _extensionUri: vscode.Uri, private readonly _findingsStore: FindingsStore) {}
+ constructor(private readonly _extensionUri: vscode.Uri, private readonly _findingsStore: FindingsStore,
+ private readonly _state: vscode.Memento) {}
+
+ public async disableDynamicAnalysis(): Promise {
+ await this._state.update(PENDING_DISABLE, randomUUID());
+ this.deliverPendingSetting();
+ }
+
+ private deliverPendingSetting(): void {
+ const id = this._state.get(PENDING_DISABLE);
+ if (id && this._view?.visible && this._ready) {
+ // A document can disappear between the visibility check and delivery.
+ void Promise.resolve(this._view.webview.postMessage({ type: 'set-dynamic-analysis', enabled: false, id }))
+ .catch(() => { /* Retry on visibility or webview-ready until acknowledged. */ });
+ }
+ }
public dispose(): void {
while (this._disposables.length) {
@@ -61,6 +79,7 @@ export class SidebarProvider implements vscode.WebviewViewProvider, vscode.Dispo
// Keep it updated whenever the user switches tabs
const activeEditorListener = vscode.window.onDidChangeActiveTextEditor(postActiveFile);
this._disposables.push(activeEditorListener);
+ webviewView.onDidChangeVisibility(() => this.deliverPendingSetting());
webviewView.onDidDispose(() => {
activeEditorListener.dispose();
if (this._view === webviewView) {
@@ -73,11 +92,12 @@ export class SidebarProvider implements vscode.WebviewViewProvider, vscode.Dispo
switch (data.type) {
case "webview-ready": {
this._ready = true;
+ this.deliverPendingSetting();
syncBinaryStatus();
postActiveFile(vscode.window.activeTextEditor);
const savedFindings = this._findingsStore.get();
if (savedFindings && !this._pendingMessages.some(message => message.type === "analysis-result" || message.type === "clear-results")) {
- webviewView.webview.postMessage({ type: "analysis-result", data: savedFindings.report, restored: true, savedAt: savedFindings.savedAt });
+ webviewView.webview.postMessage({ type: "analysis-result", data: savedFindings.report, coverageNote: savedFindings.coverageNote, restored: true, savedAt: savedFindings.savedAt });
}
const latestStack = StackManager.instance.getLatestReport();
if (latestStack && !this._pendingMessages.some(message => message.type === "stack-data")) {
@@ -88,6 +108,12 @@ export class SidebarProvider implements vscode.WebviewViewProvider, vscode.Dispo
}
break;
}
+ case "dynamic-setting-saved": {
+ if (typeof data.id === "string" && data.id === this._state.get(PENDING_DISABLE)) {
+ await this._state.update(PENDING_DISABLE, undefined);
+ }
+ break;
+ }
case "onInfo": {
if (!data.value) {
return;
@@ -108,7 +134,12 @@ export class SidebarProvider implements vscode.WebviewViewProvider, vscode.Dispo
console.warn(`[CoreTrace] Blocked unauthorized command from webview: ${data.command}`);
return;
}
- vscode.commands.executeCommand(data.command, data.params);
+ // Runs started here may change the sidebar's settings (Turn Off Dynamic Analysis).
+ const isRun = data.command === 'ctrace.runAnalysis' || data.command === 'ctrace.runWorkspaceAnalysis';
+ const params = isRun && typeof data.params === 'object' && data.params !== null && !Array.isArray(data.params)
+ ? { ...data.params, fromSidebar: true }
+ : data.params;
+ vscode.commands.executeCommand(data.command, params);
break;
}
case "ignore-finding": {
@@ -519,6 +550,7 @@ export class SidebarProvider implements vscode.WebviewViewProvider, vscode.Dispo
+
diff --git a/src/ctrace/CommandBuilder.ts b/src/ctrace/CommandBuilder.ts
index 7e5047a..04fc984 100755
--- a/src/ctrace/CommandBuilder.ts
+++ b/src/ctrace/CommandBuilder.ts
@@ -48,7 +48,7 @@ export function parseAndValidateParams(raw: string): string[] {
* Wraps the value in single quotes and escapes any literal single quotes.
* Only used for WSL execution paths that cannot avoid spawning a shell.
*/
-function shellEscapeArg(arg: string): string {
+export function shellEscapeArg(arg: string): string {
return "'" + arg.replace(/'/g, "'\\''") + "'";
}
@@ -61,7 +61,7 @@ function toWslPath(winPath: string, distroName: string | null = null): string {
try {
const args = [
...(distroName ? ['-d', distroName] : []),
- 'wslpath', '-u', normalized,
+ '--exec', 'wslpath', '-u', normalized,
];
return cp.execFileSync('wsl', args, { timeout: 5000 }).toString().trim();
} catch {
@@ -85,16 +85,22 @@ export async function buildCommand(
ctracePath: string,
inputFilePath: string,
params: string,
- compileCommands = false
+ compileCommands = false,
+ target?: ExecutionTarget
): Promise
{
if (process.platform !== 'win32') {
return buildNativeCommand(ctracePath, inputFilePath, params, compileCommands);
}
- return await buildWindowsCommand(ctracePath, inputFilePath, params, compileCommands);
+ return await buildWindowsCommand(ctracePath, inputFilePath, params, compileCommands, target);
}
// ─── Linux / macOS ───────────────────────────────────────────────────────────
+export function enterToolsDirectory(): string {
+ const dir = process.platform === 'win32' ? '"$HOME/.coretrace/tools"' : shellEscapeArg(path.join(os.homedir(), '.coretrace', 'tools'));
+ return `cd ${dir} 2>/dev/null || true; `;
+}
+
function buildNativeCommand(
ctracePath: string,
inputFilePath: string,
@@ -109,8 +115,7 @@ function buildNativeCommand(
const toolsDir = path.posix.join(os.homedir().replace(/\\/g, '/'), '.coretrace', 'tools');
const q = (p: string) => shellEscapeArg(`${toolsDir}/${p}`);
const envExports = `export CORETRACE_CPPCHECK_BIN='/opt/homebrew/bin/cppcheck' CORETRACE_IKOS_BIN=${q('ikos/src/ikos-build/bin/ikos')} CORETRACE_TSCANCODE_BIN=${q('tscancode/src/tscancode/trunk/tscancode')} CORETRACE_FLAWFINDER_SCRIPT=${q('flawfinder/src/flawfinder-build/flawfinder.py')} && `;
- const cdTools = `cd ${shellEscapeArg(toolsDir)} 2>/dev/null || true; `;
- const command = `${cdTools}${envExports}chmod +x ${bin} && ${bin} --input ${input}${extraArgs} ${params}`;
+ const command = `${enterToolsDirectory()}${envExports}chmod +x ${bin} && ${bin} --input ${input}${extraArgs} ${params}`;
return { command, tempFiles: [] };
}
@@ -167,7 +172,8 @@ async function buildWindowsCommand(
ctracePath: string,
inputFilePath: string,
params: string,
- compileCommands = false
+ compileCommands: boolean,
+ target = executionTarget(ctracePath, inputFilePath)
): Promise {
if (!isWslAvailable()) {
throw new Error('Windows Subsystem for Linux (WSL) is required to run Ctrace on Windows. Please install WSL (run "wsl --install" or visit https://learn.microsoft.com/windows/wsl/install).');
@@ -175,30 +181,20 @@ async function buildWindowsCommand(
const tempFiles: string[] = [];
- const binWsl = parseWslUNC(ctracePath);
- const inputWsl = parseWslUNC(inputFilePath);
- const detectedDistro = binWsl?.distro ?? inputWsl?.distro;
-
- if (detectedDistro) {
- const result = trySmartDistroExecution(ctracePath, inputFilePath, params, detectedDistro, binWsl, inputWsl, compileCommands);
- if (result) {
- return await writeWslScript(result.script, result.distro, tempFiles);
- }
+ if (target.uncDistro) {
+ const script = buildDistroScript(ctracePath, inputFilePath, params, target, compileCommands);
+ return await writeWslScript(script, target.distro, tempFiles);
}
// Fallback: copy files to Windows temp folder, run via default WSL distro
return await buildFallbackCommand(ctracePath, inputFilePath, params, tempFiles, compileCommands);
}
-function trySmartDistroExecution(
- ctracePath: string,
- inputFilePath: string,
- params: string,
- detectedDistro: string,
- binWsl: { distro: string; internalPath: string } | null,
- inputWsl: { distro: string; internalPath: string } | null,
- compileCommands: boolean
-): { script: string; distro: string | null } | null {
+/**
+ * The WSL distribution named in a `\\wsl$\\…` path, if reachable:
+ * `distro` is null for the default one, else its sanitized name.
+ */
+function matchWslDistro(detectedDistro: string): { distro: string | null } | null {
try {
const clean = (s: string) => s.replace(/[\u0000-\u001F\u007F-\u009F\uFEFF\uFFFD]/g, '').trim();
// execFileSync avoids spawning a shell (cmd.exe); encoding:'utf16le' is
@@ -222,50 +218,80 @@ function trySmartDistroExecution(
}
if (!matchedDistro) { return null; }
+ if (matchedDistro === defaultDistro) { return { distro: null }; }
+ const distro = resolveDistroName(matchedDistro);
+ return distro === null ? null : { distro };
+ } catch {
+ return null;
+ }
+}
- const isDefault = matchedDistro === defaultDistro;
- const safeDistroName = isDefault ? null : resolveDistroName(matchedDistro);
- if (!isDefault && safeDistroName === null) { return null; }
-
- const resolvePath = (origPath: string, wsl: { distro: string; internalPath: string } | null): string => {
- if (wsl?.distro === detectedDistro) { return wsl.internalPath; }
- return toWslPath(origPath, isDefault ? null : safeDistroName);
- };
-
- const finalBin = binWsl?.distro === detectedDistro ? binWsl.internalPath : resolvePath(ctracePath, binWsl);
- const finalInput = inputWsl?.distro === detectedDistro ? inputWsl.internalPath : resolvePath(inputFilePath, inputWsl);
-
- const validatedParamsTokens = parseAndValidateParams(params).map(token => {
- const eqIndex = token.indexOf('=');
- if (eqIndex > 0) {
- const key = token.substring(0, eqIndex);
- const val = token.substring(eqIndex + 1);
- const wsl = parseWslUNC(val);
- if (wsl || val.match(/^[a-zA-Z]:[\\/]/)) {
- const finalVal = wsl?.distro === detectedDistro ? wsl.internalPath : resolvePath(val, wsl);
- return `${key}=${finalVal}`;
- }
- }
- return token;
- });
- const validatedParams = validatedParamsTokens.map(shellEscapeArg).join(' ');
-
- const extraArgs = compileCommands ? ` --compile-commands ${shellEscapeArg(finalInput)}` : '';
-
- const libDir = getLibDirForBinary(ctracePath);
- let libEnv = '';
- if (libDir) {
- const wslLib = binWsl?.distro === detectedDistro
- ? path.posix.join(path.posix.dirname(binWsl.internalPath), '..', 'lib')
- : resolvePath(libDir, null);
- libEnv = `export LD_LIBRARY_PATH=${shellEscapeArg(wslLib)}:"$LD_LIBRARY_PATH" && `;
+/** The WSL distribution named in a path, if any. */
+export function wslDistroOf(p: string): string | undefined {
+ return parseWslUNC(p)?.distro;
+}
+
+export interface ExecutionTarget {
+ binary: string;
+ distro: string | null;
+ /** Includes the default distro's name when the command uses its UNC path. */
+ uncDistro?: string;
+}
+
+export function pathInExecutionTarget(file: string, target: ExecutionTarget): string {
+ if (process.platform !== 'win32') { return file; }
+ const unc = parseWslUNC(file);
+ if (unc && unc.distro.toLowerCase() === target.uncDistro?.toLowerCase()) { return unc.internalPath; }
+ if (!unc && path.posix.isAbsolute(file)) { return file; }
+ return toWslPath(file, target.distro);
+}
+
+/**
+ * Where buildCommand runs ctrace for this input: the WSL distribution (null:
+ * the default one, or the host off Windows) and the path of ctrace there.
+ */
+export function executionTarget(ctracePath: string, inputFilePath: string): ExecutionTarget {
+ if (process.platform !== 'win32') { return { distro: null, binary: ctracePath }; }
+ const binWsl = parseWslUNC(ctracePath);
+ const detectedDistro = binWsl?.distro ?? parseWslUNC(inputFilePath)?.distro;
+ const target = detectedDistro ? matchWslDistro(detectedDistro) : null;
+ if (target) {
+ const binary = binWsl && binWsl.distro === detectedDistro ? binWsl.internalPath : toWslPath(ctracePath, target.distro);
+ return { distro: target.distro, binary, uncDistro: detectedDistro };
+ }
+ // The fallback runs a copy of ctrace from /tmp, with no release next to it.
+ return { distro: null, binary: '/tmp/ctrace' };
+}
+
+function buildDistroScript(
+ ctracePath: string,
+ inputFilePath: string,
+ params: string,
+ target: ExecutionTarget,
+ compileCommands: boolean
+): string {
+ const finalInput = pathInExecutionTarget(inputFilePath, target);
+ const validatedParamsTokens = parseAndValidateParams(params).map(token => {
+ const eqIndex = token.indexOf('=');
+ if (eqIndex < 0) { return token; }
+ const val = token.slice(eqIndex + 1);
+ if (parseWslUNC(val) || /^[a-zA-Z]:[\\/]/.test(val)) {
+ return token.slice(0, eqIndex + 1) + pathInExecutionTarget(val, target);
}
+ return token;
+ });
+ const validatedParams = validatedParamsTokens.map(shellEscapeArg).join(' ');
- const script = `${wslToolEnvironment()}${libEnv}chmod +x ${shellEscapeArg(finalBin)} && ${shellEscapeArg(finalBin)} --input ${shellEscapeArg(finalInput)}${extraArgs} ${validatedParams}`;
- return { script, distro: isDefault ? null : safeDistroName };
- } catch {
- return null;
+ const extraArgs = compileCommands ? ` --compile-commands ${shellEscapeArg(finalInput)}` : '';
+
+ const libDir = getLibDirForBinary(ctracePath);
+ let libEnv = '';
+ if (libDir) {
+ const wslLib = pathInExecutionTarget(libDir, target);
+ libEnv = `export LD_LIBRARY_PATH=${shellEscapeArg(wslLib)}:"$LD_LIBRARY_PATH" && `;
}
+
+ return `${wslToolEnvironment()}${libEnv}chmod +x ${shellEscapeArg(target.binary)} && ${shellEscapeArg(target.binary)} --input ${shellEscapeArg(finalInput)}${extraArgs} ${validatedParams}`;
}
/**
@@ -344,7 +370,7 @@ async function buildFallbackCommand(
function wslToolEnvironment(): string {
const toolsDir = '$HOME/.coretrace/tools';
- return `cd "${toolsDir}" 2>/dev/null || true; export CORETRACE_CPPCHECK_BIN=/opt/homebrew/bin/cppcheck CORETRACE_IKOS_BIN="${toolsDir}/ikos/src/ikos-build/bin/ikos" CORETRACE_TSCANCODE_BIN="${toolsDir}/tscancode/src/tscancode/trunk/tscancode" CORETRACE_FLAWFINDER_SCRIPT="${toolsDir}/flawfinder/src/flawfinder-build/flawfinder.py" && `;
+ return `${enterToolsDirectory()}export CORETRACE_CPPCHECK_BIN=/opt/homebrew/bin/cppcheck CORETRACE_IKOS_BIN="${toolsDir}/ikos/src/ikos-build/bin/ikos" CORETRACE_TSCANCODE_BIN="${toolsDir}/tscancode/src/tscancode/trunk/tscancode" CORETRACE_FLAWFINDER_SCRIPT="${toolsDir}/flawfinder/src/flawfinder-build/flawfinder.py" && `;
}
async function writeWslScript(script: string, distro: string | null, tempFiles: string[]): Promise {
diff --git a/src/ctrace/DependencyInstaller.ts b/src/ctrace/DependencyInstaller.ts
index c4b91fc..d662caa 100644
--- a/src/ctrace/DependencyInstaller.ts
+++ b/src/ctrace/DependencyInstaller.ts
@@ -40,10 +40,10 @@ export interface DependencyStatus {
*/
export function execShellCommand(
cmd: string,
- options: { asRoot?: boolean; distro?: string | null; onData?: (chunk: string) => void } = {}
+ options: { asRoot?: boolean; distro?: string | null; cwd?: string; onData?: (chunk: string) => void } = {}
): Promise<{ stdout: string; stderr: string; code: number }> {
return new Promise((resolve) => {
- let processName = 'sh';
+ let processName = '/bin/sh';
let processArgs: string[] = ['-c', cmd];
if (process.platform === 'win32') {
@@ -70,7 +70,7 @@ export function execShellCommand(
delete env.GIT_OBJECT_DIRECTORY;
delete env.GIT_PREFIX;
- const child = cp.spawn(processName, processArgs, { env });
+ const child = cp.spawn(processName, processArgs, { env, cwd: options.cwd });
if (process.platform === 'win32') {
child.stdin?.on('error', () => { /* WSL may exit before consuming stdin */ });
child.stdin?.end(cmd);
@@ -91,7 +91,7 @@ export function execShellCommand(
});
child.on('close', (code) => {
- resolve({ stdout, stderr, code: code ?? 0 });
+ resolve({ stdout, stderr, code: code ?? 1 });
});
child.on('error', (err) => {
diff --git a/src/ctrace/FindingsStore.ts b/src/ctrace/FindingsStore.ts
index b67159c..fd2aca2 100644
--- a/src/ctrace/FindingsStore.ts
+++ b/src/ctrace/FindingsStore.ts
@@ -5,6 +5,7 @@ const STORAGE_KEY = 'coretrace.latestFindings.v1';
export interface FindingsSnapshot {
savedAt: number;
+ coverageNote?: string;
report: SarifLog;
}
@@ -18,7 +19,7 @@ export class FindingsStore {
? value : null;
}
- public async save(report: SarifLog, savedAt = Date.now()): Promise {
+ public async save(report: SarifLog, savedAt = Date.now(), coverageNote?: string): Promise {
const results: SarifResult[] = (report.runs ?? []).flatMap(run => run.results ?? []).map(result => {
const location = result.locations?.[0]?.physicalLocation;
const props = result.properties;
@@ -41,7 +42,7 @@ export class FindingsStore {
};
});
await this.state.update(STORAGE_KEY, {
- savedAt,
+ savedAt, coverageNote,
report: {
version: '2.1.0',
runs: [{ tool: { driver: { name: 'CoreTrace' } }, results }],
diff --git a/src/ctrace/RuntimeAnalyzer.ts b/src/ctrace/RuntimeAnalyzer.ts
new file mode 100644
index 0000000..10ade6f
--- /dev/null
+++ b/src/ctrace/RuntimeAnalyzer.ts
@@ -0,0 +1,47 @@
+import { enterToolsDirectory, shellEscapeArg } from './CommandBuilder';
+import { execShellCommand } from './DependencyInstaller';
+
+export const RUNTIME_ANALYZER = 'coretrace-runtime-analyzer';
+
+/** Where a release (`/bin/ctrace`) puts the runtime analyzer, relative to ctrace's directory. */
+export const BUNDLED_RUNTIME_ANALYZER = `../libexec/coretrace/${RUNTIME_ANALYZER}/bin/runtime-analyzer`;
+
+/**
+ * A POSIX shell script that exits 0 when ctrace at `ctracePath` would find an
+ * executable runtime analyzer, by ctrace's own rules: the configured path
+ * alone when set; else the copy of its release or build tree, then PATH.
+ */
+export function runtimeAnalyzerProbe(ctracePath: string, configured?: string): string {
+ const executable = (file: string) => `[ -f ${file} ] && [ -x ${file} ]`;
+ // ctrace searches nonempty PATH entries for files, including names that are shell builtins.
+ const onPath = (name: string) => 'rest=${PATH-}:; while [ -n "$rest" ]; do '
+ + 'dir=${rest%%:*}; rest=${rest#*:}; [ -n "$dir" ] || continue; '
+ + `p="$dir"/${shellEscapeArg(name)}; ${executable('"$p"')} && exit 0; done; exit 1`;
+ if (configured) {
+ return configured.includes('/') ? executable(shellEscapeArg(configured)) : onPath(configured);
+ }
+ const bin = shellEscapeArg(ctracePath);
+ const bundled = [BUNDLED_RUNTIME_ANALYZER, BUNDLED_RUNTIME_ANALYZER.replace('../', '')]
+ .map(relative => `"$d"/${shellEscapeArg(relative)}`).join(' ');
+ return `b=$(command -p readlink -f ${bin} 2>/dev/null) || b=${bin}; d=\${b%/*}; `
+ + `for c in ${bundled}; do ${executable('"$c"')} && exit 0; done; ${onPath(RUNTIME_ANALYZER)}`;
+}
+
+type Shell = (command: string, distro: string | null) => Promise<{ code: number }>;
+
+/**
+ * Whether ctrace can run dynamic analysis where it runs (`distro` inside WSL
+ * on Windows, null for the default one). macOS releases do not include it.
+ */
+export async function isRuntimeAnalyzerAvailable(
+ target: { binary: string; distro: string | null },
+ configured: string | undefined,
+ cwd: string,
+ shell: Shell = (command, distro) => execShellCommand(command, { distro, cwd })
+): Promise {
+ try {
+ return (await shell(enterToolsDirectory() + runtimeAnalyzerProbe(target.binary, configured), target.distro)).code === 0;
+ } catch {
+ return false;
+ }
+}
diff --git a/src/ctraceRunner.ts b/src/ctraceRunner.ts
index 89408c1..a8a4ca2 100755
--- a/src/ctraceRunner.ts
+++ b/src/ctraceRunner.ts
@@ -2,6 +2,7 @@ import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
import * as vscode from 'vscode';
+import { RUNTIME_ANALYZER } from './ctrace/RuntimeAnalyzer';
import { cleanFunctionName } from './utils/symbolExtractor';
export type AnalysisProfile = 'fast' | 'full';
@@ -42,6 +43,8 @@ export interface CtraceUIState {
analysisProfile?: AnalysisProfile;
reportFile?: string;
configFile?: string;
+ /** Set when the runtime analyzer cannot be found: the run's config must not ask for it either. */
+ skipRuntimeAnalyzer?: boolean;
}
const DEFAULT_PROFILE: AnalysisProfile = 'full';
@@ -56,7 +59,7 @@ const ALLOWED_INVOKE_TOOLS = new Set([
'coretrace-python-analyzer',
]);
const STATIC_TOOLS = ['cppcheck', 'flawfinder', 'ikos', 'tscancode', 'ctrace_stack_analyzer', 'coretrace-python-analyzer'];
-const DYNAMIC_TOOLS = ['coretrace-runtime-analyzer'];
+const DYNAMIC_TOOLS = [RUNTIME_ANALYZER];
export type SourceLanguage = 'c' | 'python';
@@ -90,20 +93,41 @@ export function sourceLanguage(filePath: string): SourceLanguage | undefined {
/** Brace list of the extensions a workspace scan looks for, e.g. "{c,cpp,py}". */
export function workspaceSourceExtensions(languages: SourceLanguage[]): string {
- return `{${languages.flatMap(language => SOURCE_EXTENSIONS[language]).map(ext => ext.slice(1)).join(',')}}`;
+ const extensions = languages.flatMap(language => SOURCE_EXTENSIONS[language]).map(ext => ext.slice(1));
+ return extensions.length === 1 ? extensions[0] : `{${extensions.join(',')}}`;
}
/** Python environments and caches: third-party code, not the user's. */
export const PYTHON_EXCLUDED_DIRS = ['.venv', 'venv', '__pycache__', 'site-packages', '.tox', '.nox', '.mypy_cache', '.pytest_cache'];
/**
- * Whether a run with these settings analyses files of `language`. C and C++
- * files are always sent, as before; Python files need the Python analyzer.
+ * Whether any selected analyzer can process files of this language.
*/
-export function analysesLanguage(uiState: CtraceUIState, language: SourceLanguage): boolean {
- if (language === 'c') { return true; }
- return uiState.staticEnabled !== false
- && (uiState.staticTools === undefined || uiState.staticTools.includes(PYTHON_ANALYZER));
+export function analysesLanguage(uiState: CtraceUIState, language: SourceLanguage, config = {}): boolean {
+ const tools = effectiveAnalyzers(uiState, config, language);
+ return tools.static || (language === 'c' && tools.runtime);
+}
+
+function selectedTools(uiState: CtraceUIState, language: SourceLanguage) {
+ // Only the tools of this file's language count: a C run with every C
+ // tool selected is a full --static run, whatever the Python analyzer says.
+ const languageTools = TOOLS_BY_LANGUAGE[language];
+ const staticTools = normalizeTools(uiState.staticTools, STATIC_TOOLS).filter(tool => languageTools.static.includes(tool));
+ const dynamicTools = normalizeTools(uiState.dynamicTools, DYNAMIC_TOOLS).filter(tool => languageTools.dynamic.includes(tool));
+ const allStatic = uiState.staticEnabled !== false && staticTools.length > 0 && staticTools.length === languageTools.static.length;
+ const allDynamic = uiState.dynamicEnabled !== false && dynamicTools.length > 0 && dynamicTools.length === languageTools.dynamic.length;
+ const partialTools = [
+ ...(uiState.staticEnabled !== false && !allStatic ? staticTools : []),
+ ...(uiState.dynamicEnabled !== false && !allDynamic ? dynamicTools : []),
+ ];
+ const invokedTools = [...partialTools, ...(Array.isArray(uiState.invokedTools) ? uiState.invokedTools : [])]
+ .filter((tool, index, tools): tool is string =>
+ typeof tool === 'string' &&
+ ALLOWED_INVOKE_TOOLS.has(tool) &&
+ (languageTools.static.includes(tool) || languageTools.dynamic.includes(tool)) &&
+ tools.indexOf(tool) === index
+ );
+ return { allStatic, allDynamic, invokedTools };
}
/**
@@ -129,24 +153,9 @@ export function buildCtraceArgs(
args.push(`--entry-points=${entryPoints.join(',')}`);
}
- // Only the tools of this file's language count: a C run with every C
- // tool selected is a full --static run, whatever the Python analyzer says.
- const languageTools = TOOLS_BY_LANGUAGE[language];
- const staticTools = normalizeTools(uiState.staticTools, STATIC_TOOLS).filter(tool => languageTools.static.includes(tool));
- const dynamicTools = normalizeTools(uiState.dynamicTools, DYNAMIC_TOOLS).filter(tool => languageTools.dynamic.includes(tool));
- const partialTools: string[] = [];
-
- if (uiState.staticEnabled !== false && languageTools.static.length > 0 && staticTools.length === languageTools.static.length) {
- args.push('--static');
- } else if (uiState.staticEnabled !== false) {
- partialTools.push(...staticTools);
- }
-
- if (uiState.dynamicEnabled !== false && languageTools.dynamic.length > 0 && dynamicTools.length === languageTools.dynamic.length) {
- args.push('--dyn');
- } else if (uiState.dynamicEnabled !== false) {
- partialTools.push(...dynamicTools);
- }
+ const { allStatic, allDynamic, invokedTools } = selectedTools(uiState, language);
+ if (allStatic) { args.push('--static'); }
+ if (allDynamic) { args.push('--dyn'); }
args.push('--sarif-format');
args.push(`--report-file=${requiredReportFile(uiState.reportFile)}`);
@@ -165,13 +174,6 @@ export function buildCtraceArgs(
if (uiState.timing === true) { args.push('--timing'); }
if (uiState.demangle === true) { args.push('--demangle'); }
- const invokedTools = [...partialTools, ...(uiState.invokedTools ?? [])]
- .filter((tool, index, tools): tool is string =>
- typeof tool === 'string' &&
- ALLOWED_INVOKE_TOOLS.has(tool) &&
- (languageTools.static.includes(tool) || languageTools.dynamic.includes(tool)) &&
- tools.indexOf(tool) === index
- );
if (invokedTools.length > 0) {
args.push(`--invoke=${invokedTools.join(',')}`);
}
@@ -359,6 +361,77 @@ function toInternalPath(p: string): string {
return normalized.replace(/^([a-zA-Z]):(?=\/|$)/, (_match, drive: string) => `/mnt/${drive.toLowerCase()}`);
}
+export function readCtraceConfig(file?: string): Record {
+ if (!file) { return {}; }
+ try {
+ const data = JSON.parse(fs.readFileSync(file, 'utf8').replace(/^\uFEFF/, ''));
+ if (!data || typeof data !== 'object' || Array.isArray(data)) { throw new Error('expected a JSON object'); }
+ return data;
+ } catch (e) {
+ throw new ScanSetupError(`Could not read ctrace configuration ${file}: ${(e as Error).message}`);
+ }
+}
+
+function invokedList(value: unknown): unknown[] {
+ if (Array.isArray(value)) { return value; }
+ return typeof value === 'string' ? [value] : [];
+}
+
+/** ctrace applies CLI flags over the matching config fields, including the whole invoke list. */
+export function effectiveAnalyzers(uiState: CtraceUIState, config: Record, language: SourceLanguage = 'c') {
+ const { allStatic, allDynamic, invokedTools } = selectedTools(uiState, language);
+ const analysis = config.analysis ?? {};
+ const invoked = invokedTools.length ? invokedTools : invokedList(analysis.invoke ?? config.invoke);
+ const configDynamic = (analysis.dynamic !== undefined ? analysis.dynamic : analysis.dynamic_analysis) === true || invoked.includes(RUNTIME_ANALYZER);
+ const runtimePath = config.tools?.[RUNTIME_ANALYZER]?.path;
+ const staticEnabled = allStatic || (analysis.static !== undefined ? analysis.static : analysis.static_analysis) === true;
+ return {
+ runtime: allDynamic || configDynamic,
+ configDynamic,
+ runtimePath: typeof runtimePath === 'string' && runtimePath.length ? runtimePath : undefined,
+ stack: staticEnabled || invoked.includes('ctrace_stack_analyzer'),
+ static: staticEnabled
+ || invoked.some(tool => (language === 'c' && tool === 'coretrace-concurrency-analyzer') || (typeof tool === 'string' && TOOLS_BY_LANGUAGE[language].static.includes(tool))),
+ };
+}
+
+function removeRuntimeAnalyzer(config: Record): boolean {
+ const analysis = config.analysis;
+ let changed = false;
+ if (analysis?.dynamic === true || analysis?.dynamic_analysis === true) {
+ analysis.dynamic = false;
+ delete analysis.dynamic_analysis;
+ changed = true;
+ }
+ for (const section of [config, analysis]) {
+ const invoked = invokedList(section?.invoke);
+ if (invoked.includes(RUNTIME_ANALYZER)) {
+ section.invoke = invoked.filter(tool => tool !== RUNTIME_ANALYZER);
+ changed = true;
+ }
+ }
+ return changed;
+}
+
+/** Only these CLI config fields resolve against the JSON file's directory. */
+function preserveConfigPaths(config: Record, configFile: string): void {
+ const base = path.posix.dirname(configFile);
+ const resolve = (value: unknown) => typeof value === 'string' && value && !path.posix.isAbsolute(value)
+ ? path.posix.join(base, value) : value;
+ for (const section of [config, config.files]) {
+ if (section?.input != null) {
+ section.input = Array.isArray(section.input) ? section.input.map(resolve) : resolve(section.input);
+ }
+ }
+ if (config.files?.compile_commands) { config.files.compile_commands = resolve(config.files.compile_commands); }
+ const stack = config.stack_analyzer ?? config['stack-analyzer'] ?? config.tools?.ctrace_stack_analyzer ?? config.tools?.stack_analyzer;
+ const pathKeys = ['config', 'compile_commands', 'compdb', 'resource_model', 'escape_model', 'buffer_model',
+ 'resource_summary_cache_dir', 'compile_ir_cache_dir', 'base_dir', 'dump_ir'];
+ for (const key of Object.keys(stack ?? {})) {
+ if (pathKeys.includes(key.replace(/-/g, '_'))) { stack[key] = resolve(stack[key]); }
+ }
+}
+
/**
* Writes the JSON config that carries the settings ctrace has no CLI flag
* for (include directories, macros, filters…).
@@ -371,14 +444,16 @@ export function generateConfigFileIfNeeded(
configPath: string,
uiState: CtraceUIState,
workspaceRoot?: string,
- vscodeConfig?: vscode.WorkspaceConfiguration
+ vscodeConfig?: vscode.WorkspaceConfiguration,
+ userConfig = readCtraceConfig(uiState.configFile),
+ targetPath: (file: string) => string = file => path.win32.isAbsolute(file) && !path.posix.isAbsolute(file) ? toInternalPath(file) : file
): boolean {
const parseList = (val?: string) => {
if (!val || typeof val !== 'string') { return []; }
return val.split(/[\n,;]+/).map(s => s.trim()).filter(Boolean);
};
- const internalRoot = workspaceRoot ? toInternalPath(workspaceRoot) : undefined;
+ const internalRoot = workspaceRoot ? targetPath(workspaceRoot) : undefined;
const rawIncludes = parseList(uiState.extraIncludes).map(s => s.replace(/^-I/, '').trim()).filter(Boolean);
const includeDirs: string[] = [];
@@ -390,7 +465,7 @@ export function generateConfigFileIfNeeded(
if (internalRoot && !isAbsolute) {
resolved = path.posix.join(internalRoot, item.replace(/\\/g, '/'));
}
- const internal = toInternalPath(resolved);
+ const internal = isAbsolute ? targetPath(resolved) : resolved;
if (!includeDirs.includes(internal)) {
includeDirs.push(internal);
extraArgs.push(`-I${internal}`);
@@ -412,7 +487,7 @@ export function generateConfigFileIfNeeded(
const resolveDir = (dir: string): string => {
const isAbsolute = path.isAbsolute(dir) || dir.startsWith('/') || /^[a-zA-Z]:/.test(dir);
const resolved = internalRoot && !isAbsolute ? path.posix.join(internalRoot, dir.replace(/\\/g, '/')) : dir;
- return toInternalPath(resolved).replace(/(?<=.)\/+$/, '');
+ return (isAbsolute ? targetPath(resolved) : resolved).replace(/(?<=.)\/+$/, '');
};
const onlyDirs = parseList(uiState.onlyDir).map(resolveDir);
const excludeDirs = parseList(uiState.excludeDir).map(resolveDir);
@@ -444,20 +519,17 @@ export function generateConfigFileIfNeeded(
Boolean(resourceSummaryMemoryOnly)
);
- if (!hasAnyConfig) {
- return false;
- }
+ const configData = structuredClone(userConfig);
+ // The user's file can enable dynamic analysis on its own: ctrace would
+ // still start the missing analyzer, so the run gets a copy without it.
+ const dropsRuntimeAnalyzer = uiState.skipRuntimeAnalyzer === true && removeRuntimeAnalyzer(configData);
- let configData: Record = {};
- if (uiState.configFile && fs.existsSync(uiState.configFile)) {
- try {
- configData = JSON.parse(fs.readFileSync(uiState.configFile, 'utf8'));
- } catch {
- configData = {};
- }
+ if (!hasAnyConfig && !dropsRuntimeAnalyzer) {
+ return false;
}
- if (!configData.stack_analyzer) {
- configData.stack_analyzer = {};
+ if (uiState.configFile) { preserveConfigPaths(configData, targetPath(path.resolve(uiState.configFile))); }
+ if (hasAnyConfig && !configData.stack_analyzer) {
+ configData.stack_analyzer = configData['stack-analyzer'] ?? configData.tools?.ctrace_stack_analyzer ?? configData.tools?.stack_analyzer ?? {};
}
if (includeDirs.length > 0) {
diff --git a/src/extension.ts b/src/extension.ts
index a498c0d..20b1f72 100755
--- a/src/extension.ts
+++ b/src/extension.ts
@@ -4,11 +4,11 @@ import * as path from 'path';
import { SidebarProvider } from './SidebarProvider';
import { locateBinary } from './ctrace/BinaryLocator';
-import { buildCommand, isWslAvailable } from './ctrace/CommandBuilder';
+import { buildCommand, executionTarget, ExecutionTarget, isWslAvailable, pathInExecutionTarget, wslDistroOf } from './ctrace/CommandBuilder';
import { runCommand, DEFAULT_TIMEOUT_MS } from './ctrace/AnalysisRunner';
import { parseSarifOutput } from './ctrace/SarifParser';
import { updateDiagnostics, clearDiagnostics, getFindingForDiagnostic, FindingRef } from './ctrace/DiagnosticsManager';
-import { buildCtraceArgs, buildStackAnalyzerArgs, createReportPath, createConfigPath, generateConfigFileIfNeeded, prepareScanDirectory, shellQuoteArgs, CtraceUIState, sourceLanguage, analysesLanguage, workspaceSourceExtensions, PYTHON_EXCLUDED_DIRS, SourceLanguage } from './ctraceRunner';
+import { buildCtraceArgs, buildStackAnalyzerArgs, createReportPath, createConfigPath, generateConfigFileIfNeeded, effectiveAnalyzers, readCtraceConfig, prepareScanDirectory, shellQuoteArgs, CtraceUIState, sourceLanguage, analysesLanguage, workspaceSourceExtensions, PYTHON_EXCLUDED_DIRS, SourceLanguage } from './ctraceRunner';
import { getFunctionSymbols, cleanFunctionName } from './utils/symbolExtractor';
import { CtraceCodeLensProvider } from './codelens/CtraceCodeLensProvider';
import { ensureBinary, isUpdatingBinary, setBinaryUpdateListener } from './ctrace/BinaryUpdater';
@@ -27,6 +27,7 @@ import { FindingIgnoreList, relativeFindingPath, IGNORE_FILE_NAME } from './ctra
import { IgnoreFindingCodeActionProvider } from './codelens/IgnoreFindingCodeActionProvider';
import { checkDependencies, installDependencies } from './ctrace/DependencyInstaller';
import { StackManager } from './ctrace/StackManager';
+import { isRuntimeAnalyzerAvailable } from './ctrace/RuntimeAnalyzer';
import { parseStackReport, mergeStackReports } from './ctrace/StackParser';
import { FindingsStore } from './ctrace/FindingsStore';
@@ -38,7 +39,7 @@ export function activate(context: vscode.ExtensionContext) {
// ── Sidebar ──────────────────────────────────────────────────────────────
const findingsStore = new FindingsStore(context.workspaceState);
- const sidebarProvider = new SidebarProvider(context.extensionUri, findingsStore);
+ const sidebarProvider = new SidebarProvider(context.extensionUri, findingsStore, context.workspaceState);
// Register the provider itself as a Disposable so its view-scoped
// subscriptions are guaranteed to be released on extension deactivation,
// even if `onDidDispose` is never fired by VS Code.
@@ -81,6 +82,7 @@ export function activate(context: vscode.ExtensionContext) {
// SARIF of the latest analysis, per analysed file, so that ignoring a
// finding can refresh the Problems panel and the sidebar without a rerun.
let lastSarifByFile = new Map();
+ let lastCoverageNote: string | undefined;
let republishPending = false;
async function republishFindings(): Promise {
@@ -94,8 +96,8 @@ export function activate(context: vscode.ExtensionContext) {
updateDiagnostics(sarif, diagnosticCollection, fp, false, { isIgnored });
}
const merged = mergeSarifDocs([...lastSarifByFile.values()]);
- await findingsStore.save(merged).catch(() => { /* best effort */ });
- sidebarProvider.postMessage({ type: 'analysis-result', data: merged, refresh: true });
+ await findingsStore.save(merged, undefined, lastCoverageNote).catch(() => { /* best effort */ });
+ sidebarProvider.postMessage({ type: 'analysis-result', data: merged, coverageNote: lastCoverageNote, refresh: true });
return;
}
// Results restored from a previous session: only the sidebar shows them.
@@ -105,8 +107,8 @@ export function activate(context: vscode.ExtensionContext) {
const fingerprint = result.properties?.ctraceFingerprint;
if (fingerprint) { result.properties = { ...result.properties, ctraceIgnored: ignoreList.has(fingerprint) }; }
}
- await findingsStore.save(snapshot.report, snapshot.savedAt).catch(() => { /* best effort */ });
- sidebarProvider.postMessage({ type: 'analysis-result', data: snapshot.report, restored: true, savedAt: snapshot.savedAt, refresh: true });
+ await findingsStore.save(snapshot.report, snapshot.savedAt, snapshot.coverageNote).catch(() => { /* best effort */ });
+ sidebarProvider.postMessage({ type: 'analysis-result', data: snapshot.report, coverageNote: snapshot.coverageNote, restored: true, savedAt: snapshot.savedAt, refresh: true });
}
context.subscriptions.push(ignoreList.onDidChange(() => { void republishFindings(); }));
@@ -168,24 +170,41 @@ export function activate(context: vscode.ExtensionContext) {
);
// ── Command: ctrace.runAnalysis ──────────────────────────────────────────
- context.subscriptions.push(
- vscode.commands.registerCommand('ctrace.runAnalysis', async (arg?: any) => {
- if (isRunning) {
- vscode.window.showWarningMessage('An analysis is already in progress.');
- sidebarProvider.postMessage({ type: 'analysis-done' });
- return;
+ async function runGuarded(run: (generatedConfigs: string[]) => Promise): Promise {
+ if (isRunning) {
+ vscode.window.showWarningMessage('An analysis is already in progress.');
+ return;
+ }
+ isRunning = true;
+ const generatedConfigs: string[] = [];
+ try {
+ await run(generatedConfigs);
+ } catch (e) {
+ const message = e instanceof Error ? e.message : String(e);
+ output.appendLine(`[ctrace] ${message}`);
+ vscode.window.showErrorMessage(message);
+ sidebarProvider.postMessage({ type: 'analysis-error', message: 'Analysis failed', detail: message });
+ } finally {
+ generatedConfigs.forEach(tryDelete);
+ isRunning = false;
+ sidebarProvider.postMessage({ type: 'analysis-done' });
+ if (republishPending) {
+ republishPending = false;
+ void republishFindings();
}
+ }
+ }
+ context.subscriptions.push(
+ vscode.commands.registerCommand('ctrace.runAnalysis', (arg?: any) => runGuarded(async generatedConfigs => {
if (process.platform === 'win32' && !isWslAvailable()) {
output.appendLine('[ctrace] Windows Subsystem for Linux (WSL) is required to run Ctrace on Windows.');
promptWslInstallation();
- sidebarProvider.postMessage({ type: 'analysis-done' });
return;
}
if (isUpdatingBinary()) {
vscode.window.showWarningMessage('Ctrace is currently updating. Please wait for the download to finish before running an analysis.');
- sidebarProvider.postMessage({ type: 'analysis-done' });
return;
}
@@ -198,13 +217,23 @@ export function activate(context: vscode.ExtensionContext) {
const workspaceRoot = vscode.workspace.workspaceFolders?.[0]?.uri.fsPath;
if (!workspaceRoot) {
vscode.window.showErrorMessage('Please open a workspace folder.');
- sidebarProvider.postMessage({ type: 'analysis-done' });
return;
}
// ── Determine files to analyse ───────────────────────────────────
let filesToAnalyze: string[];
- const pythonEnabled = analysesLanguage(uiState, 'python');
+ const userConfig = readCtraceConfig(uiState.configFile);
+ const analyzers = effectiveAnalyzers(uiState, userConfig);
+ const cEnabled = analyzers.static || analyzers.runtime;
+ const pythonEnabled = analysesLanguage(uiState, 'python', userConfig);
+ const languages: SourceLanguage[] = [];
+ if (cEnabled) { languages.push('c'); }
+ if (pythonEnabled) { languages.push('python'); }
+ if (!languages.length) {
+ vscode.window.showWarningMessage('Select an analyzer before running an analysis.');
+ sidebarProvider.postMessage({ type: 'analysis-error', message: 'No tools selected' });
+ return;
+ }
if (scanWorkspace) {
const userExclude = uiState.excludeDir
@@ -213,7 +242,7 @@ export function activate(context: vscode.ExtensionContext) {
const pythonExclude = pythonEnabled ? PYTHON_EXCLUDED_DIRS.map(dir => `,**/${dir}/**`).join('') : '';
const excludeGlob = `{**/node_modules/**,**/.git/**,**/build/**,**/out/**,**/.cache/**,**/.vscode/**${pythonExclude}${userExclude ? ',' + userExclude : ''}}`;
- const extensions = workspaceSourceExtensions(pythonEnabled ? ['c', 'python'] : ['c']);
+ const extensions = workspaceSourceExtensions(languages);
let includeGlob = `**/*.${extensions}`;
if (uiState.onlyDir) {
const dirs = uiState.onlyDir.split(',').map((s: string) => s.trim()).filter(Boolean);
@@ -226,8 +255,7 @@ export function activate(context: vscode.ExtensionContext) {
const uris = await vscode.workspace.findFiles(includeGlob, excludeGlob);
if (uris.length === 0) {
- vscode.window.showWarningMessage(`No ${pythonEnabled ? 'C/C++ or Python' : 'C/C++'} files found in the current workspace matching the filters.`);
- sidebarProvider._view?.webview.postMessage({ type: 'analysis-done' });
+ vscode.window.showWarningMessage(`No ${languages.map(language => language === 'c' ? 'C/C++' : 'Python').join(' or ')} files found in the current workspace matching the filters.`);
return;
}
filesToAnalyze = uris.map(u => u.fsPath);
@@ -237,18 +265,17 @@ export function activate(context: vscode.ExtensionContext) {
: vscode.window.activeTextEditor?.document.uri;
if (!targetUri) {
vscode.window.showErrorMessage('No active file to analyse.');
- sidebarProvider._view?.webview.postMessage({ type: 'analysis-done' });
return;
}
const language = sourceLanguage(targetUri.fsPath);
if (targetUri.scheme !== 'file' || !language) {
vscode.window.showWarningMessage('Please open or focus a C/C++ (.c, .cpp, .cc, .cxx) or Python (.py) source file to analyse.');
- sidebarProvider._view?.webview.postMessage({ type: 'analysis-done' });
return;
}
- if (!analysesLanguage(uiState, language)) {
- vscode.window.showWarningMessage('The Python analyzer is turned off: select coretrace-python-analyzer in the Static tools menu to analyse Python files.');
- sidebarProvider._view?.webview.postMessage({ type: 'analysis-done' });
+ if (!languages.includes(language)) {
+ const message = language === 'python' ? 'Select the Python analyzer to analyse this file.' : 'Select a C/C++ analyzer to analyse this file.';
+ vscode.window.showWarningMessage(message);
+ sidebarProvider.postMessage({ type: 'analysis-error', message: 'No tools selected for this file', detail: message });
return;
}
filesToAnalyze = [targetUri.fsPath];
@@ -268,7 +295,6 @@ export function activate(context: vscode.ExtensionContext) {
'Run Anyway'
);
if (action === 'Install Analyzers') {
- sidebarProvider.postMessage({ type: 'analysis-done' });
vscode.commands.executeCommand('ctrace.installDependencies');
return;
}
@@ -278,11 +304,9 @@ export function activate(context: vscode.ExtensionContext) {
// ── Locate binary ────────────────────────────────────────────────
const ctracePath = await locateOrError();
if (!ctracePath) {
- sidebarProvider.postMessage({ type: 'analysis-done' });
return;
}
- isRunning = true;
sidebarProvider.postMessage({ type: 'analysis-start' });
const extensionPath = context.extensionUri.fsPath;
@@ -321,6 +345,66 @@ export function activate(context: vscode.ExtensionContext) {
? timeoutSeconds * 1000
: DEFAULT_TIMEOUT_MS;
+ // Dynamic analysis needs the runtime analyzer, which macOS releases
+ // do not include and each WSL distribution may lack: files that run
+ // where it is missing are analysed without it.
+ interface ScanGroup {
+ files: string[];
+ language: SourceLanguage;
+ target: ExecutionTarget;
+ skipRuntime: boolean;
+ generatedConfig?: string;
+ cacheKey?: string;
+ }
+ const groups = new Map();
+ const groupFor = new Map();
+ let skippedCount = 0;
+ for (const file of filesToAnalyze) {
+ const language = sourceLanguage(file) ?? 'c';
+ const distro = process.platform === 'win32' ? wslDistroOf(file) ?? '' : '';
+ const key = JSON.stringify([language, distro.toLowerCase()]);
+ let group = groups.get(key);
+ if (!group) {
+ const target = executionTarget(ctracePath, file);
+ const skipRuntime = language === 'c' && analyzers.runtime
+ && !await isRuntimeAnalyzerAvailable(target, analyzers.runtimePath, extensionPath);
+ group = { files: [], language, target, skipRuntime };
+ groups.set(key, group);
+ }
+ if (group.skipRuntime) { skippedCount++; }
+ if (!group.skipRuntime || analyzers.static) {
+ group.files.push(file);
+ groupFor.set(file, group);
+ }
+ }
+ let coverageNote: string | undefined;
+ let dynamicNotice: string | undefined;
+ if (skippedCount > 0) {
+ const count = `${skippedCount} C/C++ file${skippedCount > 1 ? 's' : ''}`;
+ const reason = 'coretrace-runtime-analyzer cannot be found where ctrace runs (macOS releases do not include it)';
+ coverageNote = analyzers.static
+ ? `Dynamic analysis was skipped for ${count}.`
+ : `${count} skipped because no C/C++ analyzer was available.`;
+ if (analyzers.static) {
+ dynamicNotice = `Dynamic analysis will be skipped for ${count}: ${reason}. The selected static tools will still run.`;
+ } else {
+ // No tool left for them: ctrace would report a clean result without checking anything.
+ filesToAnalyze = filesToAnalyze.filter(file => groupFor.has(file));
+ dynamicNotice = `${count} will not be analysed: ${reason}, and no static C/C++ tool is selected.`;
+ if (filesToAnalyze.length === 0) {
+ output.appendLine(`[ctrace] ${dynamicNotice}`);
+ vscode.window.showWarningMessage(dynamicNotice);
+ sidebarProvider.postMessage({ type: 'analysis-error', message: 'No tools selected', detail: dynamicNotice });
+ return;
+ }
+ }
+ // The action changes the sidebar's settings, so it only helps runs started from there.
+ const actions = arg?.fromSidebar === true && !analyzers.configDynamic ? ['Turn Off Dynamic Analysis'] : [];
+ void vscode.window.showWarningMessage(dynamicNotice, ...actions).then(action => {
+ if (action) { return sidebarProvider.disableDynamicAnalysis(); }
+ });
+ }
+
const autoEntryPoints = uiState.autoEntryPoints === true
|| ctraceConfig.get('analysis.autoEntryPoints', false);
@@ -331,27 +415,26 @@ export function activate(context: vscode.ExtensionContext) {
effectiveUiState = { ...effectiveUiState, scanMode, entryPoints: symbols };
}
+ const noDynamicState: CtraceUIState = { ...effectiveUiState, dynamicEnabled: false, skipRuntimeAnalyzer: true };
+ const stateFor = (group: ScanGroup) => group.skipRuntime ? noDynamicState : effectiveUiState;
+
output.show(true);
output.clear();
+ if (dynamicNotice) { output.appendLine(`[ctrace] ${dynamicNotice}`); }
// ── Scan files ───────────────────────────────────────────────────
// Written before anything runs: without the config, ctrace would
// run without the requested macros, include paths or filters.
- let scanDir: string;
- let configPath: string;
- let hasConfig: boolean;
- try {
- scanDir = prepareScanDirectory(context.globalStorageUri.fsPath);
- configPath = createConfigPath(scanDir);
- hasConfig = generateConfigFileIfNeeded(configPath, effectiveUiState, workspaceRoot, ctraceConfig);
- } catch (e) {
- const message = e instanceof Error ? e.message : String(e);
- output.appendLine(`[ctrace] ${message}`);
- vscode.window.showErrorMessage(message);
- isRunning = false;
- sidebarProvider.postMessage({ type: 'analysis-error', message: 'Analysis not started', detail: message });
- sidebarProvider.postMessage({ type: 'analysis-done' });
- return;
+ const scanDir = prepareScanDirectory(context.globalStorageUri.fsPath);
+ const configPath = createConfigPath(scanDir);
+ for (const group of groups.values()) {
+ if (!group.files.length) { continue; }
+ const candidate = configPath.replace(/\.json$/, `-${generatedConfigs.length}.json`);
+ if (generateConfigFileIfNeeded(candidate, stateFor(group), workspaceRoot, ctraceConfig, userConfig,
+ file => pathInExecutionTarget(file, group.target))) {
+ group.generatedConfig = candidate;
+ generatedConfigs.push(candidate);
+ }
}
// ── Run with progress ────────────────────────────────────────────
@@ -366,7 +449,7 @@ export function activate(context: vscode.ExtensionContext) {
async (progress, token) => {
const allSarif: any[] = [];
const allStackReports: any[] = [];
- lastSarifByFile = new Map();
+ const sarifByFile = new Map();
// Clear once before the loop so workspace-mode doesn't wipe
// previously collected diagnostics on every file.
@@ -391,40 +474,34 @@ export function activate(context: vscode.ExtensionContext) {
// Reuse the results of files whose content, headers and
// ctrace invocation are unchanged since they were analysed.
const incremental = scanWorkspace && ctraceConfig.get('workspace.incremental', true);
- // One key per language: a header edit must not re-analyse Python
- // files, nor a requirements.txt edit C files.
- const contextKeys: Partial> = {};
+ // Cache the effective config and execution target for each language.
let queue: WorkspaceFile[] = filesToAnalyze.map(fsPath => ({ fsPath, hash: '' }));
let cachedCount = 0;
if (incremental) {
await analysisCacheReady;
- const placeholderState = {
- ...effectiveUiState,
- reportFile: '',
- configFile: hasConfig ? '' : effectiveUiState.configFile,
- };
- let configContent = '';
- try { configContent = hasConfig ? fs.readFileSync(configPath, 'utf8') : ''; } catch { /* ignore */ }
- const languages = [...new Set(filesToAnalyze.map(file => sourceLanguage(file) ?? 'c'))];
const cachedByFile = new Map();
queue = [];
- for (const language of languages) {
- const key = language === 'python'
- ? await analysisContextKey(
- [language, buildCtraceArgs(placeholderState, ctraceConfig, language), timeoutMs],
- [ctracePath], PYTHON_MANIFEST_GLOB)
- : await analysisContextKey(
- [buildCtraceArgs(placeholderState, ctraceConfig), buildStackAnalyzerArgs(placeholderState, ctraceConfig), configContent, timeoutMs],
- [ctracePath, effectiveUiState.compileCommandsPath, effectiveUiState.configFile]);
- contextKeys[language] = key;
- const partition = await partitionFiles(filesToAnalyze.filter(file => (sourceLanguage(file) ?? 'c') === language), key);
+ for (const group of groups.values()) {
+ if (!group.files.length) { continue; }
+ const { language, generatedConfig, target } = group;
+ const placeholderState = { ...stateFor(group), reportFile: '',
+ configFile: generatedConfig ? '' : effectiveUiState.configFile };
+ const values: unknown[] = [language, target, buildCtraceArgs(placeholderState, ctraceConfig, language),
+ generatedConfig ? fs.readFileSync(generatedConfig, 'utf8') : '', timeoutMs];
+ const dependencies = [ctracePath, effectiveUiState.configFile];
+ if (language === 'c') {
+ values.push(buildStackAnalyzerArgs(placeholderState, ctraceConfig));
+ dependencies.push(effectiveUiState.compileCommandsPath);
+ }
+ group.cacheKey = await analysisContextKey(values, dependencies, language === 'python' ? PYTHON_MANIFEST_GLOB : undefined);
+ const partition = await partitionFiles(group.files, group.cacheKey);
queue.push(...partition.changed);
partition.cached.forEach((cached, fp) => cachedByFile.set(fp, cached));
}
cachedCount = cachedByFile.size;
for (const [fp, cached] of cachedByFile) {
allSarif.push(cached.sarif);
- lastSarifByFile.set(fp, cached.sarif);
+ sarifByFile.set(fp, cached.sarif);
updateDiagnostics(cached.sarif, diagnosticCollection, fp, false, { isIgnored });
if (cached.stack && cached.stack.functions.length > 0) { publishStack(cached.stack); }
}
@@ -448,7 +525,9 @@ export function activate(context: vscode.ExtensionContext) {
}
const fp = queue[i].fsPath;
- const language = sourceLanguage(fp) ?? 'c';
+ const group = groupFor.get(fp)!;
+ const language = group.language;
+ const configFile = group.generatedConfig ?? effectiveUiState.configFile;
const fileName = path.basename(fp);
const cachedSuffix = cachedCount > 0 ? ` (${cachedCount} unchanged)` : '';
@@ -468,19 +547,20 @@ export function activate(context: vscode.ExtensionContext) {
// Build & run command for this file.
const reportPath = createReportPath(scanDir);
const args = buildCtraceArgs({
- ...effectiveUiState,
+ ...stateFor(group),
reportFile: reportPath,
- configFile: hasConfig ? configPath : effectiveUiState.configFile,
+ configFile,
}, ctraceConfig, language);
- const { command, tempFiles } = await buildCommand(ctracePath, fp, shellQuoteArgs(args));
+ const { command, tempFiles } = await buildCommand(ctracePath, fp, shellQuoteArgs(args), false, group.target);
tryDelete(reportPath);
output.appendLine(`\n${'─'.repeat(60)}`);
output.appendLine(`[${i + 1}/${queue.length}] ${fileName}`);
output.appendLine(`$ ${command}`);
- if (hasConfig) {
+ const runConfig = group.generatedConfig;
+ if (runConfig) {
try {
- output.appendLine(`[ctrace config] ${fs.readFileSync(configPath, 'utf8').trim()}`);
+ output.appendLine(`[ctrace config] ${fs.readFileSync(runConfig, 'utf8').trim()}`);
} catch {}
}
@@ -532,19 +612,14 @@ export function activate(context: vscode.ExtensionContext) {
// In that case, run a fast dedicated stack pass (~20ms) to retrieve the call-graph & stack metrics.
// The stack analyzer only reads C and C++.
if (language === 'c' && (!stackReport || stackReport.functions.length === 0)) {
- const isStackRequested = (
- (effectiveUiState.staticEnabled !== false &&
- (effectiveUiState.staticTools === undefined || effectiveUiState.staticTools.includes('ctrace_stack_analyzer'))) ||
- (effectiveUiState.dynamicEnabled !== false &&
- effectiveUiState.dynamicTools?.includes('ctrace_stack_analyzer'))
- );
- if (isStackRequested) {
+ const fileState = stateFor(group);
+ if (analyzers.stack) {
try {
const stackArgs = buildStackAnalyzerArgs({
- ...effectiveUiState,
- configFile: hasConfig ? configPath : effectiveUiState.configFile,
+ ...fileState,
+ configFile,
}, ctraceConfig);
- const { command: stackCmd, tempFiles: stackTemp } = await buildCommand(ctracePath, fp, shellQuoteArgs(stackArgs));
+ const { command: stackCmd, tempFiles: stackTemp } = await buildCommand(ctracePath, fp, shellQuoteArgs(stackArgs), false, group.target);
try {
const stackRes = await runCommand(stackCmd, extensionPath, token, timeoutMs);
const stackOut = (stackRes.stdout || '') + (stackRes.stderr || '');
@@ -568,10 +643,10 @@ export function activate(context: vscode.ExtensionContext) {
if (sarif) {
normalizeSarifArtifactUris(sarif, fp);
allSarif.push(sarif);
- lastSarifByFile.set(fp, sarif);
+ sarifByFile.set(fp, sarif);
updateDiagnostics(sarif, diagnosticCollection, fp, !scanWorkspace, { isIgnored });
if (incremental && !killed && queue[i].hash) {
- cacheFileAnalysis(queue[i], contextKeys[language] ?? '', { sarif, stack: fileStack });
+ cacheFileAnalysis(queue[i], group.cacheKey ?? '', { sarif, stack: fileStack });
}
} else if (!scanWorkspace) {
// Single-file mode: report parse failure immediately
@@ -605,24 +680,29 @@ export function activate(context: vscode.ExtensionContext) {
return;
}
+ lastSarifByFile = sarifByFile;
+ lastCoverageNote = coverageNote;
const merged = mergeSarifDocs(allSarif);
const total = countVisibleResults(merged);
try {
- await findingsStore.save(merged);
+ await findingsStore.save(merged, undefined, coverageNote);
} catch (error) {
output.appendLine(`[ctrace] Could not save the latest findings: ${error}`);
}
sidebarProvider.postMessage({
type: 'analysis-result',
- data: merged,
+ data: merged, coverageNote,
});
const filesSuffix = (scanWorkspace && filesToAnalyze.length > 1
? ` across ${filesToAnalyze.length} files`
: '') + (cachedCount > 0 ? ` (${cachedCount} unchanged, reused from cache)` : '');
- if (total > 0) {
+ if (coverageNote) {
+ const issues = total ? `${total} issue${total === 1 ? '' : 's'} found` : 'no issues found by active tools';
+ vscode.window.showWarningMessage(`Partial analysis — ${issues}${filesSuffix}. ${coverageNote}`);
+ } else if (total > 0) {
vscode.window.showInformationMessage(
`Analysis complete — ${total} issue${total > 1 ? 's' : ''} found${filesSuffix}.`
);
@@ -650,22 +730,13 @@ export function activate(context: vscode.ExtensionContext) {
detail: String(e),
});
} finally {
- if (hasConfig) {
- tryDelete(configPath);
- }
if (incremental) {
void persistAnalysisCache();
}
- isRunning = false;
- sidebarProvider.postMessage({ type: 'analysis-done' });
- if (republishPending) {
- republishPending = false;
- void republishFindings();
- }
}
}
);
- })
+ }))
);
context.subscriptions.push(
@@ -681,6 +752,8 @@ export function activate(context: vscode.ExtensionContext) {
vscode.commands.registerCommand('ctrace.clearAnalysisCache', async () => {
await clearCache();
StackManager.instance.clear();
+ lastSarifByFile.clear();
+ lastCoverageNote = undefined;
await findingsStore.clear();
sidebarProvider.postMessage({ type: 'clear-results' });
vscode.window.showInformationMessage('Ctrace analysis cache and saved results cleared.');
diff --git a/src/test-workspace/configWrite.test.ts b/src/test-workspace/configWrite.test.ts
index 70a47f0..edfc7da 100644
--- a/src/test-workspace/configWrite.test.ts
+++ b/src/test-workspace/configWrite.test.ts
@@ -54,7 +54,7 @@ suite('Run Analysis with requested settings', function () {
await vscode.commands.executeCommand('ctrace.runAnalysis', {
filePath: sample,
// No static tool: the dependency check would wait for an answer.
- uiState: { staticEnabled: false, staticTools: [], dynamicEnabled: false, dynamicTools: [], macros: 'FEATURE=1' },
+ uiState: { staticEnabled: false, staticTools: [], dynamicEnabled: false, dynamicTools: [], invokedTools: ['ctrace_stack_analyzer'], macros: 'FEATURE=1' },
});
}
diff --git a/src/test-workspace/python.test.ts b/src/test-workspace/python.test.ts
index e044f9c..3142f0d 100644
--- a/src/test-workspace/python.test.ts
+++ b/src/test-workspace/python.test.ts
@@ -78,8 +78,7 @@ suite('Run Analysis on Python files', function () {
test('a workspace scan covers C and Python files and skips virtual environments', async () => {
await vscode.commands.executeCommand('ctrace.clearAnalysisCache');
await 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 },
+ uiState: { staticTools: ['coretrace-python-analyzer', 'ctrace_stack_analyzer'], dynamicEnabled: false },
});
if (!posix) {
assert.ok(launched.length >= 2);
diff --git a/src/test-workspace/runtimeAnalyzer.test.ts b/src/test-workspace/runtimeAnalyzer.test.ts
new file mode 100644
index 0000000..6eea0c2
--- /dev/null
+++ b/src/test-workspace/runtimeAnalyzer.test.ts
@@ -0,0 +1,197 @@
+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 { FindingsStore } from '../ctrace/FindingsStore';
+import * as BinaryUpdater from '../ctrace/BinaryUpdater';
+import { setMockWslAvailableForTesting } from '../ctrace/CommandBuilder';
+import { BUNDLED_RUNTIME_ANALYZER } from '../ctrace/RuntimeAnalyzer';
+import { setScanDirectoryForTesting } from '../ctraceRunner';
+
+/** Run Analysis with dynamic analysis requested, with and without the runtime analyzer. */
+suite('Run Analysis and the runtime analyzer', 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 fakeBinary = '';
+ let launched: string[] = [];
+ const configs = new Map();
+ const originalPath = process.env.PATH;
+
+ const posix = process.platform !== 'win32';
+ const run = (uiState: object) => vscode.commands.executeCommand('ctrace.runAnalysis', {
+ filePath: path.join(vscode.workspace.workspaceFolders![0].uri.fsPath, 'sample.c'),
+ uiState,
+ });
+ // Static tools off: the C dependency check would wait for an answer.
+ const dynamicOnly = { staticEnabled: false, staticTools: [], dynamicEnabled: true, dynamicTools: ['coretrace-runtime-analyzer'] };
+ const sarifRun = () => launched.find(command => command.includes('--sarif-format')) ?? '';
+
+ suiteSetup(async function () {
+ // The fixture needs a POSIX shell and symlinks.
+ if (!posix) { this.skip(); }
+ work = fs.mkdtempSync(path.join(os.tmpdir(), 'ctrace-dyn-'));
+ fakeBinary = path.join(work, 'release', 'bin', 'ctrace');
+ fs.mkdirSync(path.dirname(fakeBinary), { recursive: true });
+ fs.writeFileSync(fakeBinary, '#!/bin/sh\n', { mode: 0o755 });
+ updater.ensureBinary = async () => fakeBinary;
+ runner.runCommand = async (command: string) => {
+ launched.push(command);
+ // The run's config is deleted once ctrace ends: keep what it said.
+ const config = command.match(/'--config=([^']+)'/)?.[1];
+ if (config && fs.existsSync(config)) { configs.set(command, fs.readFileSync(config, 'utf8')); }
+ return { stdout: '', stderr: '', exitCode: 0 };
+ };
+ // Only sh on PATH: a runtime analyzer installed on this machine must not count.
+ const pathDir = path.join(work, 'path');
+ fs.mkdirSync(pathDir);
+ fs.symlinkSync('/bin/sh', path.join(pathDir, 'sh'));
+ process.env.PATH = pathDir;
+ setMockWslAvailableForTesting(true);
+ setScanDirectoryForTesting(path.join(work, 'scan'));
+ await vscode.extensions.getExtension('CoreTrace.coretrace')!.activate();
+ });
+
+ suiteTeardown(() => {
+ if (!work) { return; }
+ process.env.PATH = originalPath;
+ runner.runCommand = originalRunCommand;
+ updater.ensureBinary = originalEnsureBinary;
+ setMockWslAvailableForTesting(null);
+ setScanDirectoryForTesting(undefined);
+ fs.rmSync(work, { recursive: true, force: true });
+ });
+
+ setup(() => { launched = []; configs.clear(); });
+
+ test('without the runtime analyzer, the run goes on without --dyn', async () => {
+ await run({ ...dynamicOnly, staticEnabled: true, staticTools: ['ctrace_stack_analyzer'] });
+ assert.ok(sarifRun(), 'the analysis must still run');
+ assert.ok(!sarifRun().includes("'--dyn'"), sarifRun());
+ });
+
+ test('without the runtime analyzer and with the static tools off, nothing runs', async () => {
+ await run(dynamicOnly);
+ assert.strictEqual(sarifRun(), '', 'a run with no tool would report a clean result');
+ });
+
+ test('with the runtime analyzer of the release, --dyn is passed', async () => {
+ const bundled = path.join(path.dirname(fakeBinary), BUNDLED_RUNTIME_ANALYZER);
+ fs.mkdirSync(path.dirname(bundled), { recursive: true });
+ fs.writeFileSync(bundled, '#!/bin/sh\n', { mode: 0o755 });
+ try {
+ await run(dynamicOnly);
+ assert.ok(sarifRun().includes("'--dyn'"), sarifRun());
+ } finally {
+ fs.rmSync(path.join(work, 'release', 'libexec'), { recursive: true, force: true });
+ }
+ });
+
+ test('with dynamic analysis turned off, static-only runs are unchanged', async () => {
+ await run({ ...dynamicOnly, dynamicEnabled: false, staticEnabled: true, staticTools: ['ctrace_stack_analyzer'] });
+ assert.ok(sarifRun(), 'the analysis must run');
+ assert.ok(!sarifRun().includes("'--dyn'"));
+ });
+
+ test('a config file asking for dynamic analysis does not bring the missing analyzer back', async () => {
+ const userConfig = path.join(work, 'user-config.json');
+ fs.writeFileSync(userConfig, JSON.stringify({ analysis: { dynamic: true, invoke: ['coretrace-runtime-analyzer', 'cppcheck'] } }));
+ await run({ ...dynamicOnly, staticEnabled: true, staticTools: ['ctrace_stack_analyzer'], configFile: userConfig });
+ const config = JSON.parse(configs.get(sarifRun()) ?? '{}');
+ assert.strictEqual(config.analysis?.dynamic, false, sarifRun());
+ assert.deepStrictEqual(config.analysis?.invoke, ['cppcheck']);
+ assert.ok(fs.readFileSync(userConfig, 'utf8').includes('"dynamic":true'), "the user's file is left as it was");
+ });
+
+ test('BOM-prefixed config-only selection keeps the static scan and its config-relative paths', async () => {
+ const userConfig = path.join(work, 'config.json');
+ const userData = {
+ analysis: { dynamic_analysis: true, invoke: 'ctrace_stack_analyzer' },
+ files: { compile_commands: 'db.json' },
+ stack_analyzer: { 'buffer-model': 'models/buffers.json' },
+ };
+ const original = '\uFEFF' + JSON.stringify(userData);
+ fs.writeFileSync(userConfig, original);
+ await run({ staticEnabled: false, dynamicEnabled: false, configFile: userConfig });
+ assert.ok(sarifRun(), 'the config selects a runnable C analyzer');
+ const config = JSON.parse(configs.get(sarifRun())!);
+ assert.deepStrictEqual(config.analysis, { dynamic: false, invoke: 'ctrace_stack_analyzer' });
+ assert.strictEqual(config.files.compile_commands, path.join(work, 'db.json'));
+ assert.strictEqual(config.stack_analyzer['buffer-model'], path.join(work, 'models/buffers.json'));
+ assert.strictEqual(fs.readFileSync(userConfig, 'utf8'), original);
+ });
+
+ test('the static fallback keeps automatically detected entry points', async () => {
+ const point = new vscode.Position(0, 0);
+ const symbol = new vscode.DocumentSymbol('review_entry', '', vscode.SymbolKind.Function,
+ new vscode.Range(point, point), new vscode.Range(point, point));
+ const provider = vscode.languages.registerDocumentSymbolProvider({ scheme: 'file', pattern: '**/sample.c' }, {
+ provideDocumentSymbols: () => [symbol],
+ });
+ try {
+ await run({ ...dynamicOnly, staticEnabled: true, staticTools: ['ctrace_stack_analyzer'], autoEntryPoints: true });
+ assert.match(sarifRun(), /--entry-points=[^']*review_entry/);
+ } finally {
+ provider.dispose();
+ }
+ });
+
+ test('in a mixed workspace, Python files still run when no C tool remains', async () => {
+ await vscode.commands.executeCommand('ctrace.clearAnalysisCache');
+ const launch = runner.runCommand;
+ const save = FindingsStore.prototype.save;
+ const notes: (string | undefined)[] = [];
+ FindingsStore.prototype.save = function (report, savedAt, coverageNote) {
+ notes.push(coverageNote);
+ return save.call(this, report, savedAt, coverageNote);
+ };
+ runner.runCommand = async (...args) => {
+ const result = await launch(...args);
+ return { ...result, stdout: '{"$schema":"sarif","version":"2.1.0","runs":[]}' };
+ };
+ const options = { uiState: { ...dynamicOnly, staticEnabled: true, staticTools: ['coretrace-python-analyzer'] } };
+ try {
+ await vscode.commands.executeCommand('ctrace.runWorkspaceAnalysis', options);
+ const calls = launched.length;
+ await vscode.commands.executeCommand('ctrace.runWorkspaceAnalysis', options);
+ assert.strictEqual(launched.length, calls, 'unchanged Python results should come from the cache');
+ assert.strictEqual(notes.length, 2);
+ assert.match(notes[0] ?? '', /C\/C\+\+ files? skipped/);
+ assert.strictEqual(notes[1], notes[0]);
+ } finally {
+ runner.runCommand = launch;
+ FindingsStore.prototype.save = save;
+ }
+ const inputs = launched.map(command => path.basename(command.match(/--input '([^']+)'/)?.[1] ?? ''));
+ assert.ok(inputs.includes('app.py'), inputs.join(', '));
+ assert.ok(!inputs.includes('sample.c'), inputs.join(', '));
+ });
+
+ test('turning dynamic off afterwards scans only the selected language', async () => {
+ await vscode.commands.executeCommand('ctrace.clearAnalysisCache');
+ await vscode.commands.executeCommand('ctrace.runWorkspaceAnalysis', {
+ uiState: { dynamicEnabled: false, staticTools: ['coretrace-python-analyzer'] },
+ });
+ assert.ok(launched.some(command => command.includes('app.py')));
+ assert.ok(launched.every(command => !command.includes('sample.c')));
+ });
+
+ test('an unreadable config stops the scan and the next run can start', async () => {
+ await run({ ...dynamicOnly, configFile: path.join(work, 'missing-config.json') });
+ assert.strictEqual(launched.length, 0);
+ await run({ dynamicEnabled: false, staticTools: ['ctrace_stack_analyzer'] });
+ assert.ok(sarifRun());
+ });
+
+ test('a malformed tool list does not leave the extension stuck', async () => {
+ await run({ ...dynamicOnly, staticEnabled: true, staticTools: ['ctrace_stack_analyzer'], dynamicTools: null });
+ await run({ ...dynamicOnly, staticEnabled: true, staticTools: ['ctrace_stack_analyzer'] });
+ assert.strictEqual(launched.filter(command => command.includes('--sarif-format')).length, 2);
+ });
+});
diff --git a/src/test/command.test.ts b/src/test/command.test.ts
index 395fcd2..1a5348d 100755
--- a/src/test/command.test.ts
+++ b/src/test/command.test.ts
@@ -1,7 +1,9 @@
import * as assert from 'assert';
import * as fs from 'fs';
+import * as cp from 'child_process';
+import * as os from 'os';
import * as path from 'path';
-import { parseAndValidateParams, isWslAvailable, buildCommand, setMockWslAvailableForTesting } from '../ctrace/CommandBuilder';
+import { parseAndValidateParams, isWslAvailable, buildCommand, executionTarget, pathInExecutionTarget, setMockWslAvailableForTesting } from '../ctrace/CommandBuilder';
import { buildCtraceArgs, buildStackAnalyzerArgs, generateConfigFileIfNeeded, shellQuoteArgs } from '../ctraceRunner';
import { cleanFunctionName } from '../utils/functionCleaner';
@@ -79,6 +81,45 @@ suite('CommandBuilder Test Suite', () => {
}
});
+ test('a copied config and its command use the mount root of each WSL target', async function () {
+ if (process.platform !== 'win32') { this.skip(); }
+ const work = fs.mkdtempSync(path.join(os.tmpdir(), 'ctrace-wsl-config-'));
+ const user = path.join(work, 'user.json');
+ fs.writeFileSync(user, JSON.stringify({ analysis: { dynamic: true }, files: { compile_commands: 'db.json' } }));
+ const child = cp as { execFileSync: typeof cp.execFileSync };
+ const exec = child.execFileSync;
+ child.execFileSync = ((file: string, args: string[]) => {
+ assert.strictEqual(file, 'wsl');
+ if (args.includes('-l')) { return '* Ubuntu Running 2\n Debian Running 2'; }
+ if (args.includes('true')) { return ''; }
+ assert.ok(args.includes('--exec') && args.includes('wslpath'));
+ const root = args.includes('Debian') ? '/drives' : '/volumes';
+ return Buffer.from(root + '/' + path.win32.basename(args[args.length - 1]));
+ }) as typeof cp.execFileSync;
+ setMockWslAvailableForTesting(true);
+ try {
+ for (const [name, mount] of [['Debian', '/drives'], ['Ubuntu', '/volumes']]) {
+ const input = `\\\\wsl$\\${name}\\home\\main.c`;
+ const target = executionTarget('C:\\tools\\ctrace', input);
+ assert.strictEqual(target.distro, name === 'Ubuntu' ? null : name);
+ const generated = path.join(work, name + '.json');
+ assert.ok(generateConfigFileIfNeeded(generated, { configFile: user, skipRuntimeAnalyzer: true },
+ undefined, undefined, undefined, file => pathInExecutionTarget(file, target)));
+ assert.strictEqual(JSON.parse(fs.readFileSync(generated, 'utf8')).files.compile_commands, mount + '/db.json');
+ const built = await buildCommand('C:\\tools\\ctrace', input, shellQuoteArgs(['--config=' + generated]), false, target);
+ try {
+ const script = fs.readFileSync(built.tempFiles[0], 'utf8');
+ assert.ok(script.includes(`'--config=${mount}/${name}.json'`), script);
+ assert.ok(script.includes("--input '/home/main.c'"), script);
+ } finally { for (const file of built.tempFiles) { fs.unlinkSync(file); } }
+ }
+ } finally {
+ child.execFileSync = exec;
+ setMockWslAvailableForTesting(null);
+ fs.rmSync(work, { recursive: true, force: true });
+ }
+ });
+
test('buildCommand does not create temporary copies of source files', async () => {
setMockWslAvailableForTesting(true);
const dummyBin = path.join(__dirname, 'dummy_bin');
diff --git a/src/test/findingsStore.test.ts b/src/test/findingsStore.test.ts
index 9451593..d21fbda 100644
--- a/src/test/findingsStore.test.ts
+++ b/src/test/findingsStore.test.ts
@@ -1,5 +1,6 @@
import * as assert from 'assert';
-import type * as vscode from 'vscode';
+import * as vscode from 'vscode';
+import { SidebarProvider } from '../SidebarProvider';
import { FindingsStore } from '../ctrace/FindingsStore';
import type { SarifLog } from '../types/sarif';
@@ -46,4 +47,40 @@ suite('FindingsStore Test Suite', () => {
assert.ok(restored);
assert.deepStrictEqual(restored.report.runs[0].results, []);
});
+
+ test('the recreated sidebar restores partial coverage and retries the setting until saved', async () => {
+ const state = memoryState();
+ const store = new FindingsStore(state);
+ const note = '1 C/C++ file skipped because no C/C++ analyzer was available.';
+ await store.save({ version: '2.1.0', runs: [] }, 123, note);
+ const provider = new SidebarProvider(vscode.Uri.file(__dirname), store, state);
+ let receive!: (message: any) => Promise;
+ const delivered: any[] = [];
+ let hidden = false;
+ const view = { visible: true, onDidChangeVisibility: () => {}, onDidDispose: () => {}, webview: {
+ asWebviewUri: (uri: vscode.Uri) => uri, cspSource: 'test',
+ onDidReceiveMessage: (listener: typeof receive) => { receive = listener; },
+ postMessage: async (message: any) => {
+ if (!hidden) { delivered.push(message); }
+ return !hidden;
+ },
+ } } as unknown as vscode.WebviewView;
+ try {
+ provider.resolveWebviewView(view, {} as vscode.WebviewViewResolveContext, {} as vscode.CancellationToken);
+ const ready = () => receive({ type: 'webview-ready' });
+ await ready();
+ hidden = true;
+ await provider.disableDynamicAnalysis();
+ hidden = false;
+ await ready();
+ const replayed = delivered.filter(m => m.type === 'set-dynamic-analysis');
+ assert.strictEqual(replayed.length, 1);
+ assert.ok(replayed[0].id);
+ assert.strictEqual(replayed[0].enabled, false);
+ assert.strictEqual(delivered.find(m => m.type === 'analysis-result').coverageNote, note);
+ await receive({ type: 'dynamic-setting-saved', id: replayed[0].id });
+ await ready();
+ assert.strictEqual(delivered.filter(m => m.type === 'set-dynamic-analysis').length, 1);
+ } finally { provider.dispose(); }
+ });
});
diff --git a/src/test/python.test.ts b/src/test/python.test.ts
index c84ee42..7ff7db7 100644
--- a/src/test/python.test.ts
+++ b/src/test/python.test.ts
@@ -22,12 +22,14 @@ suite('Python analysis Test Suite', () => {
assert.strictEqual(workspaceSourceExtensions(['c', 'python']), '{c,cpp,cc,cxx,py}');
});
- test('Python files need the Python analyzer, C files are always analysed', () => {
+ test('each input language needs a selected analyzer', () => {
assert.strictEqual(analysesLanguage({}, 'python'), true);
assert.strictEqual(analysesLanguage({ staticTools: ALL_STATIC }, 'python'), true);
assert.strictEqual(analysesLanguage({ staticTools: ['cppcheck'] }, 'python'), false);
assert.strictEqual(analysesLanguage({ staticEnabled: false }, 'python'), false);
assert.strictEqual(analysesLanguage({ staticTools: [] }, 'c'), true);
+ assert.strictEqual(analysesLanguage({ staticTools: [], dynamicEnabled: false }, 'c'), false);
+ assert.strictEqual(workspaceSourceExtensions(['python']), 'py');
});
test('every tool selected: --static for both languages, --dyn only for C', () => {
diff --git a/src/test/runtimeAnalyzer.test.ts b/src/test/runtimeAnalyzer.test.ts
new file mode 100644
index 0000000..d8d3a82
--- /dev/null
+++ b/src/test/runtimeAnalyzer.test.ts
@@ -0,0 +1,124 @@
+import * as assert from 'assert';
+import * as cp from 'child_process';
+import * as fs from 'fs';
+import * as os from 'os';
+import * as path from 'path';
+import { effectiveAnalyzers, generateConfigFileIfNeeded, readCtraceConfig } from '../ctraceRunner';
+import { BUNDLED_RUNTIME_ANALYZER, isRuntimeAnalyzerAvailable, RUNTIME_ANALYZER } from '../ctrace/RuntimeAnalyzer';
+
+suite('Runtime analyzer detection Test Suite', () => {
+ let work = '';
+ setup(() => { work = fs.mkdtempSync(path.join(os.tmpdir(), 'ctrace-runtime-')); });
+ teardown(() => fs.rmSync(work, { recursive: true, force: true }));
+
+ const ctrace = () => path.join(work, 'bin', 'ctrace');
+ const pathDir = () => path.join(work, 'path');
+ // Runs the probe with only pathDir() on PATH, so the host's tools do not count.
+ const shell = async (command: string) => ({
+ code: cp.spawnSync('/bin/sh', ['-c', command], { env: { PATH: pathDir() } }).status ?? 1,
+ });
+ const available = (configured?: string) =>
+ isRuntimeAnalyzerAvailable({ binary: ctrace(), distro: null }, configured, work, shell);
+ const tool = (file: string, mode = 0o755) => {
+ fs.mkdirSync(path.dirname(file), { recursive: true });
+ fs.writeFileSync(file, '#!/bin/sh\n', { mode });
+ return file;
+ };
+ setup(() => { tool(ctrace()); });
+ const posixOnly = function (this: Mocha.Context) { if (process.platform === 'win32') { this.skip(); } };
+
+ test('the runtime analyzer of the release is found next to ctrace', async function () {
+ posixOnly.call(this);
+ tool(path.join(work, 'bin', BUNDLED_RUNTIME_ANALYZER));
+ assert.strictEqual(await available(), true);
+ });
+
+ test('a build tree keeps it in libexec next to ctrace', async function () {
+ posixOnly.call(this);
+ tool(path.join(work, 'bin', BUNDLED_RUNTIME_ANALYZER.replace('../', '')));
+ assert.strictEqual(await available(), true);
+ });
+
+ test('a bundled file that is not executable, or a directory, does not count', async function () {
+ posixOnly.call(this);
+ tool(path.join(work, 'bin', BUNDLED_RUNTIME_ANALYZER), 0o644);
+ fs.mkdirSync(path.join(work, 'bin', BUNDLED_RUNTIME_ANALYZER.replace('../', '')), { recursive: true });
+ assert.strictEqual(await available(), false);
+ });
+
+ test('without it, one on PATH is used', async function () {
+ posixOnly.call(this);
+ assert.strictEqual(await available(), false);
+ tool(path.join(pathDir(), 'coretrace-runtime-analyzer'));
+ assert.strictEqual(await available(), true);
+ });
+
+ test('a configured path replaces the default lookup', async function () {
+ posixOnly.call(this);
+ tool(path.join(work, 'bin', BUNDLED_RUNTIME_ANALYZER));
+ assert.strictEqual(await available(path.join(work, 'missing')), false);
+ assert.strictEqual(await available(tool(path.join(work, 'custom', 'analyzer'))), true);
+ assert.strictEqual(await available('my-analyzer'), false);
+ tool(path.join(pathDir(), 'my-analyzer'));
+ assert.strictEqual(await available('my-analyzer'), true);
+ tool(path.join(pathDir(), 'test'));
+ assert.strictEqual(await available('test'), true, 'ctrace resolves a configured executable even if sh has a builtin of that name');
+ });
+
+ test('relative paths use the tools directory and fall back to the analysis cwd', async function () {
+ posixOnly.call(this);
+ const previousHome = process.env.HOME;
+ process.env.HOME = work;
+ try {
+ const target = { binary: ctrace(), distro: null };
+ tool(path.join(work, 'fallback-tool'));
+ assert.ok(await isRuntimeAnalyzerAvailable(target, './fallback-tool', work));
+ tool(path.join(work, '.coretrace', 'tools', 'bin', 'relative-tool'));
+ assert.ok(await isRuntimeAnalyzerAvailable(target, './bin/relative-tool', work));
+ assert.strictEqual(await isRuntimeAnalyzerAvailable(target, './fallback-tool', work), false);
+ } finally {
+ if (previousHome === undefined) { delete process.env.HOME; } else { process.env.HOME = previousHome; }
+ }
+ });
+
+ test('a shell that cannot start means no dynamic analysis', async () => {
+ const failing = async () => { throw new Error('no shell'); };
+ assert.strictEqual(await isRuntimeAnalyzerAvailable({ binary: ctrace(), distro: null }, undefined, work, failing), false);
+ });
+
+ test('the configured path is read from the ctrace configuration file', () => {
+ const config = path.join(work, 'config.json');
+ const configuredRuntimeAnalyzer = (file?: string) => effectiveAnalyzers({}, readCtraceConfig(file)).runtimePath;
+ assert.strictEqual(configuredRuntimeAnalyzer(undefined), undefined);
+ assert.throws(() => configuredRuntimeAnalyzer(config), /Could not read ctrace configuration/);
+ fs.writeFileSync(config, JSON.stringify({ tools: { 'coretrace-runtime-analyzer': { path: '/opt/rt/bin/runtime-analyzer' } } }));
+ assert.strictEqual(configuredRuntimeAnalyzer(config), '/opt/rt/bin/runtime-analyzer');
+ fs.writeFileSync(config, '{ not json');
+ assert.throws(() => configuredRuntimeAnalyzer(config), /Could not read ctrace configuration/);
+ });
+
+ test('preflight uses the tool flags and config precedence that ctrace uses', () => {
+ const off = { staticEnabled: false, dynamicEnabled: false };
+ assert.strictEqual(effectiveAnalyzers({}, {}).runtime, true);
+ assert.strictEqual(effectiveAnalyzers({ dynamicTools: [] }, {}).runtime, false);
+ assert.strictEqual(effectiveAnalyzers(off, { analysis: { dynamic_analysis: true } }).runtime, true);
+ assert.strictEqual(effectiveAnalyzers(off, { analysis: { static_analysis: true } }).static, true);
+ const config = { invoke: RUNTIME_ANALYZER };
+ assert.strictEqual(effectiveAnalyzers(off, config).runtime, true);
+ assert.strictEqual(effectiveAnalyzers({ ...off, invokedTools: ['cppcheck'] }, config).runtime, false);
+ assert.strictEqual(effectiveAnalyzers(off, { ...config, analysis: { invoke: [] } }).runtime, false);
+ assert.strictEqual(effectiveAnalyzers(off, { analysis: { invoke: 'coretrace-python-analyzer' } }).static, false);
+ });
+
+ test('a run without the runtime analyzer turns it off in a copy of the user config', () => {
+ const user = path.join(work, 'user.json');
+ const run = path.join(work, 'run.json');
+ assert.strictEqual(generateConfigFileIfNeeded(run, { skipRuntimeAnalyzer: true }), false, 'no config, nothing to write');
+ fs.writeFileSync(user, JSON.stringify({ analysis: { dynamic: false, invoke: 'cppcheck' } }));
+ assert.strictEqual(generateConfigFileIfNeeded(run, { skipRuntimeAnalyzer: true, configFile: user }), false, 'already off');
+ fs.writeFileSync(user, JSON.stringify({ analysis: { invoke: 'coretrace-runtime-analyzer' } }));
+ assert.strictEqual(generateConfigFileIfNeeded(run, { configFile: user }), false, 'only when asked');
+ assert.strictEqual(generateConfigFileIfNeeded(run, { skipRuntimeAnalyzer: true, configFile: user }), true);
+ assert.deepStrictEqual(JSON.parse(fs.readFileSync(run, 'utf8')).analysis, { invoke: [] });
+ });
+});