diff --git a/.vscode-test.js b/.vscode-test.js index 6856bb1..7650f9e 100755 --- a/.vscode-test.js +++ b/.vscode-test.js @@ -11,4 +11,18 @@ module.exports = defineConfig([{ mocha: { timeout: 20000, }, +}, { + // Tests that run commands needing an open folder, like Run Analysis. + label: 'workspace', + files: 'out/test-workspace/**/*.test.js', + version: '1.140.0', + workspaceFolder: './src/test-workspace/fixture', + launchArgs: [ + '--disable-gpu', + '--disable-gpu-sandbox', + '--disable-dev-shm-usage', + ], + mocha: { + timeout: 60000, + }, }]); diff --git a/README.md b/README.md index ee6ab67..8dac798 100755 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # CoreTrace VS Code Extension -CoreTrace VS Code brings the power of the `ctrace` security and quality analysis framework directly into Visual Studio Code. It provides seamless static and dynamic analysis for C and C++ projects, surfacing vulnerabilities, code defects, and stack diagnostics directly in your editor. +CoreTrace VS Code brings the power of the `ctrace` security and quality analysis framework directly into Visual Studio Code. It provides seamless static and dynamic analysis for C, C++ and Python projects, surfacing vulnerabilities, code defects, and stack diagnostics directly in your editor. --- @@ -50,7 +50,7 @@ Precise C/C++ static analysis requires knowledge of compiler flags, include dire > ``` ### 6. Incremental Workspace Scans -Save time on repetitive scans. CoreTrace computes file content hashes and only re-analyzes C/C++ files that have changed since their last analysis; the results of the other files are reused, even after restarting VS Code. +Save time on repetitive scans. CoreTrace computes file content hashes and only re-analyzes C/C++ and Python files that have changed since their last analysis; the results of the other files are reused, even after restarting VS Code. Python files are re-analyzed when a dependency manifest changes (`requirements*.txt`, `pyproject.toml`, `setup.py`, lock files…). - The cache is invalidated for every file when a header, `compile_commands.json`, the `ctrace` binary or the analysis options change, since any of these can change the result of an unmodified source file. - Run **Clear Analysis Cache** to force a full scan, or set `ctrace.workspace.incremental` to `false` to disable the cache. @@ -80,6 +80,13 @@ The gear icon opens the analysis settings, grouped by purpose: - Options that do not apply to the current scan mode say so on a single line. - **Reset to defaults** restores everything in two clicks. Settings stored in `settings.json` (timeout, incremental scans, analysis models…) are one click away. + +### 11. Python Analysis +With `ctrace` 0.85 or newer, Python files (`.py`) are analyzed by `coretrace-python-analyzer`, which ships with `ctrace`: there is nothing to install. +- It reports, among others, dangerous `eval`, hardcoded credentials, weak cryptography, insecure TLS or temporary files, and taint flows from web frameworks (Flask, Django, FastAPI…) into command, SQL or NoSQL injection, path traversal, SSRF and XSS. +- Run it on the active `.py` file, or with **Scan Workspace**, which then covers C/C++ and Python files and skips virtual environments and caches (`.venv`, `venv`, `site-packages`, `__pycache__`…). +- Turn it on or off with `coretrace-python-analyzer` in the **Static** tools menu. C/C++ files never receive it, so older `ctrace` binaries keep working for them. +- Findings get the same diagnostics, CWE links and ignore actions as C/C++ findings. The CodeLens, the Stack Tree and dynamic analysis stay C/C++ only. --- ## ⚙️ Requirements & Prerequisites @@ -111,8 +118,8 @@ Access these commands from the Command Palette (`Ctrl+Shift+P` / `Cmd+Shift+P`): | Command | Title | Description | |---|---|---| -| `ctrace.runAnalysis` | **Run Analysis** | Runs analysis on the currently active C/C++ file. | -| `ctrace.runWorkspaceAnalysis` | **Run Workspace Analysis** | Analyzes all modified C/C++ files in the workspace. | +| `ctrace.runAnalysis` | **Run Analysis** | Runs analysis on the currently active C/C++ or Python file. | +| `ctrace.runWorkspaceAnalysis` | **Run Workspace Analysis** | Analyzes all modified C/C++ and Python files in the workspace. | | `ctrace.installDependencies` | **CoreTrace: Install Analyzers & Dependencies** | Installs or repairs external static analyzers (`cppcheck`, `flawfinder`, `ikos`, `tscancode`). | | `ctrace.clearAnalysisCache` | **Clear Analysis Cache** | Clears cached analysis results to force a full re-scan. | | `ctrace.focusStackFunction` | **CoreTrace: View Function in Stack Visualizer** | Opens the Stack Visualizer on a function. | @@ -174,7 +181,7 @@ npm run compile npm test ``` -The test suite runs inside a downloaded VS Code instance (`@vscode/test-cli`). Press `F5` in VS Code to start an Extension Development Host with the extension loaded. +The test suite runs inside a downloaded VS Code instance (`@vscode/test-cli`), in two configurations: `unit` without a folder, and `workspace` with `src/test-workspace/fixture` open, for commands like Run Analysis that need one. Press `F5` in VS Code to start an Extension Development Host with the extension loaded. `src/test/params.integration.test.ts` runs every analysis parameter through a real `ctrace`. It uses the binary named by `CTRACE_BIN`, or a `ctrace` file at the repository root, and is skipped when there is none, as on CI. diff --git a/media/main.js b/media/main.js index f522b29..1ca549a 100755 --- a/media/main.js +++ b/media/main.js @@ -83,6 +83,8 @@ const smtSecondaryGroup = document.getElementById('smt-secondary-group'); const smtModeSelect = document.getElementById('smt-mode'); const persistedState = vscode.getState() || {}; + // Static tools of the versions that did not save knownStaticTools. + const LEGACY_STATIC_TOOLS = ['cppcheck', 'flawfinder', 'ikos', 'tscancode', 'ctrace_stack_analyzer']; // While a search forces sections open: the ones to reopen afterwards. let settingsSearchRestore = null; let analysisProfile = 'full'; @@ -211,7 +213,7 @@ if (fileLabel) { fileLabel.textContent = workspace ? 'All C/C++ files in workspace' - : (lastFileName || 'Open a C/C++ file to analyse'); + : (lastFileName || 'Open a C/C++ or Python file to analyse'); } [onlyDirGroup, excludeDirGroup].forEach(group => { if (!group) { return; } @@ -363,7 +365,8 @@ setScanMode(persistedState.scanWorkspace === true); setAnalysisProfile(saved.analysisProfile || 'full'); - restoreToolSelection('.static-tool', saved.staticTools, saved.staticEnabled !== false, saved.dynamicTools); + restoreToolSelection('.static-tool', saved.staticTools, saved.staticEnabled !== false, saved.dynamicTools, + persistedState.knownStaticTools || LEGACY_STATIC_TOOLS); restoreToolSelection('.dynamic-tool', saved.dynamicTools, saved.dynamicEnabled !== false); const isWs = persistedState.scanWorkspace === true; setValue('only-function', saved.onlyFunction || ''); @@ -401,6 +404,7 @@ vscode.setState({ uiState: readCtraceUiState(), scanWorkspace, + knownStaticTools: [...document.querySelectorAll('.static-tool')].map(tool => tool.value), openSections: openSectionKeys(), }); refreshSettingsIndicators(); @@ -605,10 +609,14 @@ return Array.from(document.querySelectorAll(`${selector}:checked`)).map(element => element.value); } - function restoreToolSelection(selector, savedTools, enabled, fallbackSavedTools) { + function restoreToolSelection(selector, savedTools, enabled, fallbackSavedTools, knownTools) { const selected = Array.isArray(savedTools) ? savedTools : null; document.querySelectorAll(selector).forEach(tool => { - if (selected) { + if (selected && Array.isArray(knownTools) && !knownTools.includes(tool.value)) { + // A tool added since this state was saved: the user never + // turned it off, so it starts on like in a fresh install. + tool.checked = enabled; + } else if (selected) { const inSaved = selected.includes(tool.value); const inFallback = Array.isArray(fallbackSavedTools) && fallbackSavedTools.includes(tool.value); tool.checked = inSaved || inFallback; diff --git a/package.json b/package.json index d043588..aed4c06 100755 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "coretrace", "displayName": "CoreTrace", - "description": "Integration for CoreTrace CLI", + "description": "Security and quality analysis of C, C++ and Python code with the CoreTrace CLI", "version": "0.3.6", "publisher": "CoreTrace", "icon": "icon.png", @@ -12,6 +12,7 @@ "keywords": [ "c", "cpp", + "python", "security", "static analysis", "audit", diff --git a/src/SidebarProvider.ts b/src/SidebarProvider.ts index e2db4d0..1bb6610 100755 --- a/src/SidebarProvider.ts +++ b/src/SidebarProvider.ts @@ -228,7 +228,7 @@ export class SidebarProvider implements vscode.WebviewViewProvider, vscode.Dispo
- Open a C/C++ file to analyse + Open a C/C++ or Python file to analyse
@@ -261,6 +261,7 @@ export class SidebarProvider implements vscode.WebviewViewProvider, vscode.Dispo +
diff --git a/src/ctrace/CommandBuilder.ts b/src/ctrace/CommandBuilder.ts index 3d6f2fe..7e5047a 100755 --- a/src/ctrace/CommandBuilder.ts +++ b/src/ctrace/CommandBuilder.ts @@ -24,9 +24,19 @@ export function parseAndValidateParams(raw: string): string[] { tokens.push(m[1].replace(/^["']|["']$/g, '')); } - const safe = /^--?[a-zA-Z0-9][a-zA-Z0-9._\-:/\\=,@]*$/; + // The name is strict. The value only has to stay free of what a shell + // interprets: every token is single-quoted again before use, and real + // paths contain spaces, parentheses, ~ (C:\Users\RUNNER~1) or accents. + const safeName = /^--?[a-zA-Z0-9][a-zA-Z0-9._\-]*$/; + const unsafeValue = /[$`;&|<>'"\r\n\0]/; + // Entry points are function names, never paths. + const functionList = /^[a-zA-Z0-9_:~,]*$/; for (const token of tokens) { - if (!safe.test(token)) { + const eq = token.indexOf('='); + const name = eq < 0 ? token : token.slice(0, eq); + const value = eq < 0 ? '' : token.slice(eq + 1); + if (!safeName.test(name) || unsafeValue.test(value) + || (name === '--entry-points' && !functionList.test(value))) { throw new Error(`Unsafe CLI parameter rejected: "${token}"`); } } diff --git a/src/ctrace/WorkspaceScanner.ts b/src/ctrace/WorkspaceScanner.ts index 93f4d5c..bf58c8f 100755 --- a/src/ctrace/WorkspaceScanner.ts +++ b/src/ctrace/WorkspaceScanner.ts @@ -129,11 +129,15 @@ export async function partitionFiles(files: string[], contextKey: string): Promi * header in the workspace. Header edits therefore invalidate the whole cache, * since an unchanged .c file may include a changed header. */ -export async function analysisContextKey(values: unknown[], dependencyFiles: (string | undefined)[]): Promise { +export async function analysisContextKey( + values: unknown[], + dependencyFiles: (string | undefined)[], + dependencyGlob: string = HEADER_GLOB +): Promise { const hash = crypto.createHash('sha1'); hash.update(JSON.stringify(values)); - const headers = await vscode.workspace.findFiles(HEADER_GLOB, EXCLUDE_GLOB); - const statFiles = [...dependencyFiles.filter((f): f is string => Boolean(f)), ...headers.map(u => u.fsPath).sort()]; + const dependencies = await vscode.workspace.findFiles(dependencyGlob, EXCLUDE_GLOB); + const statFiles = [...dependencyFiles.filter((f): f is string => Boolean(f)), ...dependencies.map(u => u.fsPath).sort()]; for (const file of statFiles) { try { const stat = await fs.promises.stat(file); @@ -146,6 +150,11 @@ export async function analysisContextKey(values: unknown[], dependencyFiles: (st } const HEADER_GLOB = '**/*.{h,hh,hpp,hxx,h++,inl,inc,ipp,tpp}'; +/** + * What a Python result depends on besides the file itself: the dependency + * rules of the Python analyzer read the project's requirement manifests. + */ +export const PYTHON_MANIFEST_GLOB = '**/{requirements*.txt,pyproject.toml,setup.py,setup.cfg,Pipfile,Pipfile.lock,poetry.lock,uv.lock,advisories.json}'; /** Directories that should never be scanned (build artifacts, vendored code…) */ const EXCLUDE_GLOB = '{**/node_modules/**,**/build/**,**/out/**,**/dist/**,**/.git/**,**/CMakeFiles/**,**/cmake-build-*/**}'; diff --git a/src/ctraceRunner.ts b/src/ctraceRunner.ts index 296d038..89408c1 100755 --- a/src/ctraceRunner.ts +++ b/src/ctraceRunner.ts @@ -1,4 +1,5 @@ import * as fs from 'fs'; +import * as os from 'os'; import * as path from 'path'; import * as vscode from 'vscode'; import { cleanFunctionName } from './utils/symbolExtractor'; @@ -52,10 +53,59 @@ const ALLOWED_INVOKE_TOOLS = new Set([ 'flawfinder', 'ikos', 'tscancode', + 'coretrace-python-analyzer', ]); -const STATIC_TOOLS = ['cppcheck', 'flawfinder', 'ikos', 'tscancode', 'ctrace_stack_analyzer']; +const STATIC_TOOLS = ['cppcheck', 'flawfinder', 'ikos', 'tscancode', 'ctrace_stack_analyzer', 'coretrace-python-analyzer']; const DYNAMIC_TOOLS = ['coretrace-runtime-analyzer']; +export type SourceLanguage = 'c' | 'python'; + +export const PYTHON_ANALYZER = 'coretrace-python-analyzer'; + +/** + * The tools that analyse each language. Only these are passed to ctrace for a + * file: a ctrace older than 0.85 rejects the whole run when --invoke names the + * Python analyzer, so C and C++ runs must never name it. + */ +const TOOLS_BY_LANGUAGE: Record = { + c: { static: ['cppcheck', 'flawfinder', 'ikos', 'tscancode', 'ctrace_stack_analyzer'], dynamic: DYNAMIC_TOOLS }, + // The runtime analyzer builds and runs C and C++ programs only. + python: { static: [PYTHON_ANALYZER], dynamic: [] }, +}; + +const SOURCE_EXTENSIONS: Record = { + c: ['.c', '.cpp', '.cc', '.cxx'], + python: ['.py'], +}; +/** Headers can be analysed on their own when opened, but are not scanned in a workspace. */ +const C_HEADER_EXTENSIONS = ['.h', '.hpp', '.hh']; + +/** The language ctrace analyses a file as, or undefined when it cannot analyse it. */ +export function sourceLanguage(filePath: string): SourceLanguage | undefined { + const ext = path.extname(filePath).toLowerCase(); + if (SOURCE_EXTENSIONS.c.includes(ext) || C_HEADER_EXTENSIONS.includes(ext)) { return 'c'; } + if (SOURCE_EXTENSIONS.python.includes(ext)) { return 'python'; } + return 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(',')}}`; +} + +/** 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. + */ +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)); +} + /** * Converts Webview state and VS Code settings into safe ctrace CLI arguments. * The input file is added by CommandBuilder because it is different for each @@ -63,7 +113,8 @@ const DYNAMIC_TOOLS = ['coretrace-runtime-analyzer']; */ export function buildCtraceArgs( uiState: CtraceUIState, - vscodeConfig: vscode.WorkspaceConfiguration + vscodeConfig: vscode.WorkspaceConfiguration, + language: SourceLanguage = 'c' ): string[] { const args: string[] = []; @@ -78,17 +129,20 @@ export function buildCtraceArgs( args.push(`--entry-points=${entryPoints.join(',')}`); } - const staticTools = normalizeTools(uiState.staticTools, STATIC_TOOLS); - const dynamicTools = normalizeTools(uiState.dynamicTools, DYNAMIC_TOOLS); + // 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 && staticTools.length === STATIC_TOOLS.length) { + 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 && dynamicTools.length === DYNAMIC_TOOLS.length) { + if (uiState.dynamicEnabled !== false && languageTools.dynamic.length > 0 && dynamicTools.length === languageTools.dynamic.length) { args.push('--dyn'); } else if (uiState.dynamicEnabled !== false) { partialTools.push(...dynamicTools); @@ -115,6 +169,7 @@ export function buildCtraceArgs( .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) { @@ -233,12 +288,61 @@ function validPositiveInteger(value: unknown): number | undefined { return Number.isInteger(number) && number > 0 ? number : undefined; } -export function createReportPath(extensionPath: string): string { - return path.join(extensionPath, `.ctrace-report-${Date.now()}-${process.pid}.txt`); +export function createReportPath(scanDir: string): string { + return path.join(scanDir, `.ctrace-report-${Date.now()}-${process.pid}.txt`); } -export function createConfigPath(extensionPath: string): string { - return path.join(extensionPath, `.ctrace-config-${Date.now()}-${process.pid}.json`); +export function createConfigPath(scanDir: string): string { + return path.join(scanDir, `.ctrace-config-${Date.now()}-${process.pid}.json`); +} + +/** The scan files could not be created: the analysis must not start without them. */ +export class ScanSetupError extends Error {} + +let scanDirOverride: string | undefined; +let tempScanDir: string | undefined; + +export function setScanDirectoryForTesting(dir: string | undefined): void { + scanDirOverride = dir; +} + +/** + * Returns a writable folder for the report and config files of a run. + * The extension's install folder can be read-only, so they go to the + * extension's storage, or to a private temporary folder as a fallback. + * Both are host paths that CommandBuilder converts for WSL. + */ +export function prepareScanDirectory(storageDir: string | undefined): string { + const tried: string[] = []; + const usable = (dir: string): boolean => { + tried.push(dir); + try { + fs.mkdirSync(dir, { recursive: true }); + fs.accessSync(dir, fs.constants.W_OK); + return true; + } catch { + return false; + } + }; + + if (scanDirOverride !== undefined) { + if (usable(scanDirOverride)) { return scanDirOverride; } + } else { + const preferred = storageDir ? path.join(storageDir, 'scan') : undefined; + if (preferred && usable(preferred)) { return preferred; } + if (tempScanDir && usable(tempScanDir)) { return tempScanDir; } + try { + // mkdtemp: a fixed name in a shared /tmp could be planted by another user. + tempScanDir = fs.mkdtempSync(path.join(os.tmpdir(), 'coretrace-scan-')); + return tempScanDir; + } catch { + tried.push(path.join(os.tmpdir(), 'coretrace-scan-*')); + } + } + throw new ScanSetupError( + `CoreTrace found no writable folder for its scan files (tried: ${tried.join(', ')}). ` + + 'The analysis was not started. Check the permissions of these folders.' + ); } function toInternalPath(p: string): string { @@ -255,6 +359,14 @@ function toInternalPath(p: string): string { return normalized.replace(/^([a-zA-Z]):(?=\/|$)/, (_match, drive: string) => `/mnt/${drive.toLowerCase()}`); } +/** + * Writes the JSON config that carries the settings ctrace has no CLI flag + * for (include directories, macros, filters…). + * + * @returns false when no setting needs a config file, true once it is written. + * @throws ScanSetupError when it cannot be written: running without it would + * silently drop the requested settings. + */ export function generateConfigFileIfNeeded( configPath: string, uiState: CtraceUIState, @@ -395,8 +507,21 @@ export function generateConfigFileIfNeeded( try { fs.writeFileSync(configPath, JSON.stringify(configData, null, 2), 'utf8'); return true; - } catch { - return false; + } catch (e) { + const requested = [ + [includeDirs.length > 0, 'include directories'], + [defines.length > 0, 'macros'], + [compileArgs.length > 0, 'compiler arguments'], + [onlyFunctions.length > 0, 'function filter'], + [onlyDirs.length > 0 || excludeDirs.length > 0, 'directory filters'], + [includeStl || compdbFast || dumpFilter || warningsOnly, 'analysis options'], + [Boolean(compileIrCacheDir || resourceSummaryDir || resourceSummaryMemoryOnly) || resourceCrossTu !== undefined, 'cache and cross-file settings'], + ].filter(([wanted]) => wanted).map(([, label]) => label); + throw new ScanSetupError( + `CoreTrace could not write its analysis configuration to ${configPath} (${(e as Error).message}). ` + + `The analysis was not started, because it would have ignored these settings: ${requested.join(', ')}. ` + + 'Check that this folder is writable.' + ); } } diff --git a/src/extension.ts b/src/extension.ts index d09e9cb..a498c0d 100755 --- a/src/extension.ts +++ b/src/extension.ts @@ -8,7 +8,7 @@ import { buildCommand, 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'; -import { buildCtraceArgs, buildStackAnalyzerArgs, createReportPath, createConfigPath, generateConfigFileIfNeeded, shellQuoteArgs, CtraceUIState } from './ctraceRunner'; +import { buildCtraceArgs, buildStackAnalyzerArgs, createReportPath, createConfigPath, generateConfigFileIfNeeded, 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'; @@ -21,6 +21,7 @@ import { analysisContextKey, cacheFileAnalysis, WorkspaceFile, + PYTHON_MANIFEST_GLOB, } from './ctrace/WorkspaceScanner'; import { FindingIgnoreList, relativeFindingPath, IGNORE_FILE_NAME } from './ctrace/FindingIgnoreList'; import { IgnoreFindingCodeActionProvider } from './codelens/IgnoreFindingCodeActionProvider'; @@ -69,7 +70,7 @@ export function activate(context: vscode.ExtensionContext) { const ignoreList = new FindingIgnoreList(vscode.workspace.workspaceFolders?.[0]?.uri.fsPath); context.subscriptions.push(ignoreList); const isIgnored = (fingerprint: string) => ignoreList.has(fingerprint); - for (const language of ['c', 'cpp', 'objective-c', 'objective-cpp']) { + for (const language of ['c', 'cpp', 'objective-c', 'objective-cpp', 'python']) { context.subscriptions.push(vscode.languages.registerCodeActionsProvider( { language }, new IgnoreFindingCodeActionProvider(), @@ -201,46 +202,31 @@ export function activate(context: vscode.ExtensionContext) { return; } - const requestedStaticTools: string[] = uiState.staticTools ?? ['cppcheck', 'flawfinder', 'ikos', 'tscancode', 'ctrace_stack_analyzer']; - if (uiState.staticEnabled !== false && requestedStaticTools.length > 0) { - const depStatus = await checkDependencies(); - const missingRequested = requestedStaticTools.filter((t) => depStatus.missing.includes(t)); - if (missingRequested.length > 0) { - const action = await vscode.window.showWarningMessage( - `CoreTrace: The following analyzer(s) are not configured: ${missingRequested.join(', ')}. Would you like to install them now?`, - 'Install Analyzers', - 'Run Anyway' - ); - if (action === 'Install Analyzers') { - sidebarProvider.postMessage({ type: 'analysis-done' }); - vscode.commands.executeCommand('ctrace.installDependencies'); - return; - } - } - } - // ── Determine files to analyse ─────────────────────────────────── let filesToAnalyze: string[]; + const pythonEnabled = analysesLanguage(uiState, 'python'); if (scanWorkspace) { const userExclude = uiState.excludeDir ? uiState.excludeDir.split(',').map((s: string) => `**/${s.trim()}/**`).filter(Boolean).join(',') : ''; - const excludeGlob = `{**/node_modules/**,**/.git/**,**/build/**,**/out/**,**/.cache/**,**/.vscode/**${userExclude ? ',' + userExclude : ''}}`; + const pythonExclude = pythonEnabled ? PYTHON_EXCLUDED_DIRS.map(dir => `,**/${dir}/**`).join('') : ''; + const excludeGlob = `{**/node_modules/**,**/.git/**,**/build/**,**/out/**,**/.cache/**,**/.vscode/**${pythonExclude}${userExclude ? ',' + userExclude : ''}}`; - let includeGlob = '**/*.{c,cpp,cc,cxx}'; + const extensions = workspaceSourceExtensions(pythonEnabled ? ['c', 'python'] : ['c']); + let includeGlob = `**/*.${extensions}`; if (uiState.onlyDir) { const dirs = uiState.onlyDir.split(',').map((s: string) => s.trim()).filter(Boolean); if (dirs.length === 1) { - includeGlob = `${dirs[0]}/**/*.{c,cpp,cc,cxx}`; + includeGlob = `${dirs[0]}/**/*.${extensions}`; } else if (dirs.length > 1) { - includeGlob = `{${dirs.map((d: string) => `${d}/**/*.{c,cpp,cc,cxx}`).join(',')}}`; + includeGlob = `{${dirs.map((d: string) => `${d}/**/*.${extensions}`).join(',')}}`; } } const uris = await vscode.workspace.findFiles(includeGlob, excludeGlob); if (uris.length === 0) { - vscode.window.showWarningMessage('No C/C++ files found in the current workspace matching the filters.'); + 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' }); return; } @@ -254,16 +240,41 @@ export function activate(context: vscode.ExtensionContext) { sidebarProvider._view?.webview.postMessage({ type: 'analysis-done' }); return; } - const ext = path.extname(targetUri.fsPath).toLowerCase(); - const C_EXTENSIONS = new Set(['.c', '.cpp', '.cc', '.cxx', '.h', '.hpp', '.hh']); - if (targetUri.scheme !== 'file' || !C_EXTENSIONS.has(ext)) { - vscode.window.showWarningMessage('Please open or focus a C/C++ source file (.c, .cpp, .cc, .cxx) to analyse.'); + 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' }); return; } filesToAnalyze = [targetUri.fsPath]; } + // Only the C and C++ tools have to be installed; the Python analyzer ships with ctrace. + const hasCFiles = filesToAnalyze.some(file => sourceLanguage(file) === 'c'); + 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(); + const missingRequested = requestedStaticTools.filter((t) => depStatus.missing.includes(t)); + if (missingRequested.length > 0) { + const action = await vscode.window.showWarningMessage( + `CoreTrace: The following analyzer(s) are not configured: ${missingRequested.join(', ')}. Would you like to install them now?`, + 'Install Analyzers', + 'Run Anyway' + ); + if (action === 'Install Analyzers') { + sidebarProvider.postMessage({ type: 'analysis-done' }); + vscode.commands.executeCommand('ctrace.installDependencies'); + return; + } + } + } + // ── Locate binary ──────────────────────────────────────────────── const ctracePath = await locateOrError(); if (!ctracePath) { @@ -313,7 +324,8 @@ export function activate(context: vscode.ExtensionContext) { const autoEntryPoints = uiState.autoEntryPoints === true || ctraceConfig.get('analysis.autoEntryPoints', false); - if (scanMode === 'file' && autoEntryPoints && !uiState.entryPoints?.length) { + // Entry points are C and C++ function names. + if (scanMode === 'file' && autoEntryPoints && !uiState.entryPoints?.length && sourceLanguage(filesToAnalyze[0]) === 'c') { const document = await vscode.workspace.openTextDocument(vscode.Uri.file(filesToAnalyze[0])); const symbols = await getFunctionSymbols(document); effectiveUiState = { ...effectiveUiState, scanMode, entryPoints: symbols }; @@ -322,6 +334,26 @@ export function activate(context: vscode.ExtensionContext) { output.show(true); output.clear(); + // ── 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; + } + // ── Run with progress ──────────────────────────────────────────── await vscode.window.withProgress( { @@ -343,9 +375,6 @@ export function activate(context: vscode.ExtensionContext) { StackManager.instance.clear(); } - const configPath = createConfigPath(extensionPath); - const hasConfig = generateConfigFileIfNeeded(configPath, effectiveUiState, workspaceRoot, ctraceConfig); - const publishStack = (stackReport: any) => { allStackReports.push(stackReport); const unifiedStack = mergeStackReports(allStackReports); @@ -362,7 +391,9 @@ 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); - let contextKey = ''; + // One key per language: a header edit must not re-analyse Python + // files, nor a requirements.txt edit C files. + const contextKeys: Partial> = {}; let queue: WorkspaceFile[] = filesToAnalyze.map(fsPath => ({ fsPath, hash: '' })); let cachedCount = 0; if (incremental) { @@ -374,14 +405,24 @@ export function activate(context: vscode.ExtensionContext) { }; let configContent = ''; try { configContent = hasConfig ? fs.readFileSync(configPath, 'utf8') : ''; } catch { /* ignore */ } - contextKey = await analysisContextKey( - [buildCtraceArgs(placeholderState, ctraceConfig), buildStackAnalyzerArgs(placeholderState, ctraceConfig), configContent, timeoutMs], - [ctracePath, effectiveUiState.compileCommandsPath, effectiveUiState.configFile] - ); - const partition = await partitionFiles(filesToAnalyze, contextKey); - queue = partition.changed; - cachedCount = partition.cached.size; - for (const [fp, cached] of partition.cached) { + 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); + 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); updateDiagnostics(cached.sarif, diagnosticCollection, fp, false, { isIgnored }); @@ -407,6 +448,7 @@ export function activate(context: vscode.ExtensionContext) { } const fp = queue[i].fsPath; + const language = sourceLanguage(fp) ?? 'c'; const fileName = path.basename(fp); const cachedSuffix = cachedCount > 0 ? ` (${cachedCount} unchanged)` : ''; @@ -424,12 +466,12 @@ export function activate(context: vscode.ExtensionContext) { }); // Build & run command for this file. - const reportPath = createReportPath(extensionPath); + const reportPath = createReportPath(scanDir); const args = buildCtraceArgs({ ...effectiveUiState, reportFile: reportPath, configFile: hasConfig ? configPath : effectiveUiState.configFile, - }, ctraceConfig); + }, ctraceConfig, language); const { command, tempFiles } = await buildCommand(ctracePath, fp, shellQuoteArgs(args)); tryDelete(reportPath); @@ -488,7 +530,8 @@ export function activate(context: vscode.ExtensionContext) { // If ctrace was run with --sarif-format, ctrace >= 0.80 suppresses the stack analyzer // rendering from stdout/report-file into SARIF-only results (no function/stack metrics). // In that case, run a fast dedicated stack pass (~20ms) to retrieve the call-graph & stack metrics. - if (!stackReport || stackReport.functions.length === 0) { + // 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'))) || @@ -528,7 +571,7 @@ export function activate(context: vscode.ExtensionContext) { lastSarifByFile.set(fp, sarif); updateDiagnostics(sarif, diagnosticCollection, fp, !scanWorkspace, { isIgnored }); if (incremental && !killed && queue[i].hash) { - cacheFileAnalysis(queue[i], contextKey, { sarif, stack: fileStack }); + cacheFileAnalysis(queue[i], contextKeys[language] ?? '', { sarif, stack: fileStack }); } } else if (!scanWorkspace) { // Single-file mode: report parse failure immediately diff --git a/src/test-workspace/configWrite.test.ts b/src/test-workspace/configWrite.test.ts new file mode 100644 index 0000000..70a47f0 --- /dev/null +++ b/src/test-workspace/configWrite.test.ts @@ -0,0 +1,88 @@ +import * as assert from 'assert'; +import * as fs from 'fs'; +import * as os from 'os'; +import * as path from 'path'; +import * as vscode from 'vscode'; +import * as AnalysisRunner from '../ctrace/AnalysisRunner'; +import * as BinaryUpdater from '../ctrace/BinaryUpdater'; +import { setMockWslAvailableForTesting } from '../ctrace/CommandBuilder'; +import { setScanDirectoryForTesting } from '../ctraceRunner'; + +/** + * Runs the real "Run Analysis" command in a window with a workspace, with the + * binary lookup and the process launcher replaced, to see what would be run. + */ +suite('Run Analysis with requested settings', 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 launched: { command: string; config: any }[] = []; + let work = ''; + + suiteSetup(async () => { + work = fs.mkdtempSync(path.join(os.tmpdir(), 'ctrace-run-')); + const fakeBinary = path.join(work, 'ctrace'); + fs.writeFileSync(fakeBinary, '#!/bin/sh\n', { mode: 0o755 }); + updater.ensureBinary = async () => fakeBinary; + runner.runCommand = async (command: string) => { + // Read the config now: the run deletes it once finished. + const configPath = command.match(/--config=([^'"\s]+)/)?.[1]; + const config = configPath && fs.existsSync(configPath) ? JSON.parse(fs.readFileSync(configPath, 'utf8')) : null; + launched.push({ command, config }); + return { stdout: '', stderr: '', exitCode: 0 }; + }; + // Windows runs ctrace through WSL; the command is built but never run here. + setMockWslAvailableForTesting(true); + await vscode.extensions.getExtension('CoreTrace.coretrace')!.activate(); + }); + + suiteTeardown(() => { + runner.runCommand = originalRunCommand; + updater.ensureBinary = originalEnsureBinary; + setMockWslAvailableForTesting(null); + setScanDirectoryForTesting(undefined); + fs.rmSync(work, { recursive: true, force: true }); + }); + + setup(() => { launched = []; }); + + async function runWithMacro(): Promise { + const sample = path.join(vscode.workspace.workspaceFolders![0].uri.fsPath, 'sample.c'); + 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' }, + }); + } + + test('the test window has a workspace, which Run Analysis requires', () => { + assert.ok(vscode.workspace.workspaceFolders?.length); + }); + + test('no analysis is launched when the scan files cannot be written', async () => { + // A folder below a regular file can never be created, even as root. + const blocker = path.join(work, 'not-a-folder'); + fs.writeFileSync(blocker, ''); + setScanDirectoryForTesting(path.join(blocker, 'scan')); + await runWithMacro(); + assert.deepStrictEqual(launched, []); + }); + + test('the requested macro reaches ctrace through the config when it can be written', async () => { + setScanDirectoryForTesting(path.join(work, 'scan')); + await runWithMacro(); + assert.ok(launched.length > 0, 'ctrace was not launched'); + // On Windows the arguments live in a WSL script, not in the command. + if (process.platform === 'win32') { return; } + const withConfig = launched.filter(run => run.config); + assert.ok(withConfig.length > 0, `no --config in: ${launched.map(run => run.command).join('\n')}`); + for (const run of withConfig) { + assert.deepStrictEqual(run.config.stack_analyzer.defines, ['FEATURE=1']); + } + assert.ok(!launched[0].command.includes(vscode.extensions.getExtension('CoreTrace.coretrace')!.extensionPath + path.sep + '.ctrace-'), + 'scan files must not be written to the extension folder'); + }); +}); diff --git a/src/test-workspace/fixture/.venv/lib/vendored.py b/src/test-workspace/fixture/.venv/lib/vendored.py new file mode 100644 index 0000000..92895d7 --- /dev/null +++ b/src/test-workspace/fixture/.venv/lib/vendored.py @@ -0,0 +1,2 @@ +def vendored(x): + return eval(x) diff --git a/src/test-workspace/fixture/app.py b/src/test-workspace/fixture/app.py new file mode 100644 index 0000000..c1f48ca --- /dev/null +++ b/src/test-workspace/fixture/app.py @@ -0,0 +1,2 @@ +def calc(expr): + return eval(expr) diff --git a/src/test-workspace/fixture/sample.c b/src/test-workspace/fixture/sample.c new file mode 100644 index 0000000..a971d8b --- /dev/null +++ b/src/test-workspace/fixture/sample.c @@ -0,0 +1,7 @@ +int main(void) { +#ifdef FEATURE + return FEATURE; +#else + return 0; +#endif +} diff --git a/src/test-workspace/python.test.ts b/src/test-workspace/python.test.ts new file mode 100644 index 0000000..e044f9c --- /dev/null +++ b/src/test-workspace/python.test.ts @@ -0,0 +1,121 @@ +import * as assert from 'assert'; +import * as fs from 'fs'; +import * as os from 'os'; +import * as path from 'path'; +import * as vscode from 'vscode'; +import * as AnalysisRunner from '../ctrace/AnalysisRunner'; +import * as BinaryUpdater from '../ctrace/BinaryUpdater'; +import { setMockWslAvailableForTesting } from '../ctrace/CommandBuilder'; +import { setScanDirectoryForTesting } from '../ctraceRunner'; + +const ALL_STATIC = ['cppcheck', 'flawfinder', 'ikos', 'tscancode', 'ctrace_stack_analyzer', 'coretrace-python-analyzer']; + +/** + * Runs the real Run Analysis command on the fixture, which holds C, Python + * and a .venv, with the binary lookup and the process launcher replaced. + */ +suite('Run Analysis on Python files', 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 launched: string[] = []; + let work = ''; + let root = ''; + + suiteSetup(async () => { + root = vscode.workspace.workspaceFolders![0].uri.fsPath; + work = fs.mkdtempSync(path.join(os.tmpdir(), 'ctrace-py-')); + const fakeBinary = path.join(work, 'ctrace'); + fs.writeFileSync(fakeBinary, '#!/bin/sh\n', { mode: 0o755 }); + updater.ensureBinary = async () => fakeBinary; + runner.runCommand = async (command: string) => { + launched.push(command); + return { stdout: '', stderr: '', exitCode: 0 }; + }; + setMockWslAvailableForTesting(true); + setScanDirectoryForTesting(path.join(work, 'scan')); + await vscode.extensions.getExtension('CoreTrace.coretrace')!.activate(); + }); + + suiteTeardown(() => { + runner.runCommand = originalRunCommand; + updater.ensureBinary = originalEnsureBinary; + setMockWslAvailableForTesting(null); + setScanDirectoryForTesting(undefined); + fs.rmSync(work, { recursive: true, force: true }); + }); + + setup(() => { launched = []; }); + + const inputOf = (command: string) => command.match(/--input '([^']+)'/)?.[1] ?? command; + const posix = process.platform !== 'win32'; + + test('a Python file is analysed once, with --static and without the C-only passes', async () => { + await vscode.commands.executeCommand('ctrace.runAnalysis', { + filePath: path.join(root, 'app.py'), + uiState: { staticTools: ALL_STATIC, dynamicTools: ['coretrace-runtime-analyzer'] }, + }); + assert.strictEqual(launched.length, 1, `expected one run, got:\n${launched.join('\n')}`); + if (posix) { + assert.strictEqual(inputOf(launched[0]), path.join(root, 'app.py')); + assert.ok(launched[0].includes("'--static'")); + assert.ok(!launched[0].includes("'--dyn'"), 'no runtime analysis for Python'); + assert.ok(!launched[0].includes('ctrace_stack_analyzer'), 'no stack pass for Python'); + } + }); + + test('nothing is launched for a Python file when the Python analyzer is off', async () => { + await vscode.commands.executeCommand('ctrace.runAnalysis', { + filePath: path.join(root, 'app.py'), + uiState: { staticTools: ALL_STATIC.filter(tool => tool !== 'coretrace-python-analyzer'), dynamicEnabled: false }, + }); + assert.deepStrictEqual(launched, []); + }); + + 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 }, + }); + if (!posix) { + assert.ok(launched.length >= 2); + return; + } + const inputs = launched.map(inputOf).map(file => path.relative(root, file)).sort(); + assert.ok(inputs.includes('app.py'), inputs.join(', ')); + assert.ok(inputs.includes('sample.c'), inputs.join(', ')); + assert.ok(!inputs.some(file => file.includes('.venv')), `virtual environment scanned: ${inputs.join(', ')}`); + const cRun = launched.find(command => inputOf(command).endsWith('sample.c'))!; + assert.ok(!cRun.includes('coretrace-python-analyzer'), 'a C run must never name the Python analyzer'); + }); + + test('with a real ctrace 0.85 or newer, Python findings reach the Problems panel', async function () { + // CTRACE_BIN: a ctrace with the Python analyzer, e.g. the one the extension downloads. + const binary = process.env.CTRACE_BIN; + if (!binary || !posix) { this.skip(); } + runner.runCommand = originalRunCommand; + updater.ensureBinary = async () => binary!; + try { + const file = path.join(root, 'app.py'); + await vscode.commands.executeCommand('ctrace.runAnalysis', { + filePath: file, + uiState: { staticTools: ['coretrace-python-analyzer'], dynamicEnabled: false }, + }); + const diagnostics = vscode.languages.getDiagnostics(vscode.Uri.file(file)); + const evalFinding = diagnostics.find(d => String((d.code as any)?.value ?? d.code).startsWith('dangerous-eval')); + assert.ok(evalFinding, `no dangerous-eval finding, got: ${diagnostics.map(d => `${d.source} ${d.message}`).join(' | ') || 'none'}`); + assert.strictEqual(evalFinding.source, 'CoreTrace (coretrace-python-analyzer)'); + assert.strictEqual(evalFinding.range.start.line, 1); + } finally { + runner.runCommand = async (command: string) => { + launched.push(command); + return { stdout: '', stderr: '', exitCode: 0 }; + }; + updater.ensureBinary = originalEnsureBinary; + } + }); +}); diff --git a/src/test/command.test.ts b/src/test/command.test.ts index 1b0edc5..395fcd2 100755 --- a/src/test/command.test.ts +++ b/src/test/command.test.ts @@ -2,7 +2,7 @@ import * as assert from 'assert'; import * as fs from 'fs'; import * as path from 'path'; import { parseAndValidateParams, isWslAvailable, buildCommand, setMockWslAvailableForTesting } from '../ctrace/CommandBuilder'; -import { buildCtraceArgs, buildStackAnalyzerArgs, generateConfigFileIfNeeded } from '../ctraceRunner'; +import { buildCtraceArgs, buildStackAnalyzerArgs, generateConfigFileIfNeeded, shellQuoteArgs } from '../ctraceRunner'; import { cleanFunctionName } from '../utils/functionCleaner'; suite('CommandBuilder Test Suite', () => { @@ -38,6 +38,22 @@ suite('CommandBuilder Test Suite', () => { } }); + test('Keeps real Windows paths: 8.3 names, spaces, parentheses, accents', () => { + const args = [ + '--report-file=C:\\Users\\RUNNER~1\\AppData\\Local\\Temp\\scan\\.ctrace-report-1.txt', + '--config=C:\\Users\\Jean Dupont\\Program Files (x86)\\réglages.json', + '--entry-points=main,ns::run', + '--static', + ]; + assert.deepStrictEqual(parseAndValidateParams(shellQuoteArgs(args)), args); + }); + + test('Rejects shell syntax hidden in a value or a name', () => { + for (const args of [['--config=a;b'], ['--config=a`id`'], ['--config=a|b'], ['--config=a>b'], ['--x$(id)=1'], ['--config=a&b']]) { + assert.throws(() => parseAndValidateParams(shellQuoteArgs(args)), /Unsafe CLI/, args[0]); + } + }); + test('Handles empty or whitespace-only params', () => { assert.deepStrictEqual(parseAndValidateParams(''), []); assert.deepStrictEqual(parseAndValidateParams(' '), []); diff --git a/src/test/params.test.ts b/src/test/params.test.ts index 2d54b97..57b1254 100644 --- a/src/test/params.test.ts +++ b/src/test/params.test.ts @@ -2,7 +2,7 @@ import * as assert from 'assert'; import * as fs from 'fs'; import * as os from 'os'; import * as path from 'path'; -import { buildCtraceArgs, buildStackAnalyzerArgs, generateConfigFileIfNeeded, CtraceUIState } from '../ctraceRunner'; +import { buildCtraceArgs, buildStackAnalyzerArgs, generateConfigFileIfNeeded, prepareScanDirectory, ScanSetupError, setScanDirectoryForTesting, CtraceUIState } from '../ctraceRunner'; const REPO_ROOT = path.resolve(__dirname, '..', '..'); const REPORT = '/tmp/report.json'; @@ -264,3 +264,50 @@ suite('Analysis parameters: wiring between the sidebar, the runner and package.j } }); }); + +suite('Analysis parameters: scan files', () => { + let work = ''; + setup(() => { work = fs.mkdtempSync(path.join(os.tmpdir(), 'ctrace-scan-')); }); + teardown(() => { + setScanDirectoryForTesting(undefined); + fs.rmSync(work, { recursive: true, force: true }); + }); + + /** A path below a regular file: creating it always fails, even as root. */ + function unwritable(): string { + const blocker = path.join(work, 'not-a-folder'); + fs.writeFileSync(blocker, ''); + return path.join(blocker, 'sub'); + } + + test('a config that cannot be written stops the run and names the lost settings', () => { + assert.throws( + () => generateConfigFileIfNeeded(path.join(unwritable(), 'c.json'), { macros: 'FEATURE=1', extraIncludes: 'include' }, '/work', settings()), + (error: Error) => error instanceof ScanSetupError + && /not started/.test(error.message) + && /macros/.test(error.message) + && /include directories/.test(error.message) + ); + }); + + test('no config needed is not an error, even where nothing can be written', () => { + assert.strictEqual(generateConfigFileIfNeeded(path.join(unwritable(), 'c.json'), {}, '/work', settings()), false); + }); + + test('scan files go to the extension storage', () => { + const storage = path.join(work, 'storage'); + assert.strictEqual(prepareScanDirectory(storage), path.join(storage, 'scan')); + assert.ok(fs.statSync(path.join(storage, 'scan')).isDirectory()); + }); + + test('a private temporary folder is used when the storage is not writable', () => { + const dir = prepareScanDirectory(unwritable()); + assert.ok(dir.startsWith(path.join(os.tmpdir(), 'coretrace-scan-')), dir); + fs.accessSync(dir, fs.constants.W_OK); + }); + + test('no writable folder at all is an error', () => { + setScanDirectoryForTesting(unwritable()); + assert.throws(() => prepareScanDirectory(path.join(work, 'storage')), ScanSetupError); + }); +}); diff --git a/src/test/python.test.ts b/src/test/python.test.ts new file mode 100644 index 0000000..c84ee42 --- /dev/null +++ b/src/test/python.test.ts @@ -0,0 +1,66 @@ +import * as assert from 'assert'; +import { analysesLanguage, buildCtraceArgs, sourceLanguage, workspaceSourceExtensions, CtraceUIState } from '../ctraceRunner'; + +const ALL_STATIC = ['cppcheck', 'flawfinder', 'ikos', 'tscancode', 'ctrace_stack_analyzer', 'coretrace-python-analyzer']; +const settings: any = { get: (_key: string, fallback?: unknown) => fallback }; +const args = (state: CtraceUIState, language: 'c' | 'python') => + buildCtraceArgs({ reportFile: '/tmp/r.json', ...state }, settings, language); +const invoked = (built: string[]) => built.find(arg => arg.startsWith('--invoke='))?.slice('--invoke='.length).split(',') ?? []; + +suite('Python analysis Test Suite', () => { + test('files are recognised by their extension', () => { + assert.strictEqual(sourceLanguage('/w/app.py'), 'python'); + assert.strictEqual(sourceLanguage('/w/APP.PY'), 'python'); + assert.strictEqual(sourceLanguage('/w/main.cpp'), 'c'); + assert.strictEqual(sourceLanguage('/w/main.h'), 'c'); + assert.strictEqual(sourceLanguage('/w/notes.txt'), undefined); + assert.strictEqual(sourceLanguage('/w/setup.pyc'), undefined); + }); + + test('a workspace scan looks for Python files only when they are analysed', () => { + assert.strictEqual(workspaceSourceExtensions(['c']), '{c,cpp,cc,cxx}'); + assert.strictEqual(workspaceSourceExtensions(['c', 'python']), '{c,cpp,cc,cxx,py}'); + }); + + test('Python files need the Python analyzer, C files are always analysed', () => { + 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); + }); + + test('every tool selected: --static for both languages, --dyn only for C', () => { + const state: CtraceUIState = { staticTools: ALL_STATIC, dynamicTools: ['coretrace-runtime-analyzer'] }; + const c = args(state, 'c'); + const python = args(state, 'python'); + assert.ok(c.includes('--static') && c.includes('--dyn')); + assert.ok(python.includes('--static')); + assert.ok(!python.includes('--dyn'), 'the runtime analyzer builds C programs only'); + }); + + test('turning the Python analyzer off keeps C runs on --static', () => { + const state: CtraceUIState = { staticTools: ALL_STATIC.filter(tool => tool !== 'coretrace-python-analyzer'), dynamicEnabled: false }; + assert.ok(args(state, 'c').includes('--static')); + assert.deepStrictEqual(invoked(args(state, 'c')), []); + }); + + test('a C run never names the Python analyzer, which ctrace before 0.85 rejects', () => { + const state: CtraceUIState = { staticTools: ['cppcheck', 'coretrace-python-analyzer'], invokedTools: ['coretrace-python-analyzer'], dynamicEnabled: false }; + assert.deepStrictEqual(invoked(args(state, 'c')), ['cppcheck']); + assert.ok(!args(state, 'c').includes('--static')); + }); + + test('a Python run never names C tools', () => { + const state: CtraceUIState = { staticTools: ['cppcheck', 'ikos', 'coretrace-python-analyzer'], invokedTools: ['flawfinder'], dynamicEnabled: false }; + const python = args(state, 'python'); + assert.ok(python.includes('--static')); + assert.deepStrictEqual(invoked(python), []); + }); + + test('a Python run with the analyzer off has no tool to run', () => { + const python = args({ staticTools: ['cppcheck'], dynamicEnabled: false }, 'python'); + assert.ok(!python.includes('--static')); + assert.deepStrictEqual(invoked(python), []); + }); +});