diff --git a/src/ctrace/CommandBuilder.ts b/src/ctrace/CommandBuilder.ts index 7e5047a..6e46b27 100755 --- a/src/ctrace/CommandBuilder.ts +++ b/src/ctrace/CommandBuilder.ts @@ -2,6 +2,7 @@ import * as cp from 'child_process'; import * as fs from 'fs'; import * as os from 'os'; import * as path from 'path'; +import { cppcheckEnvironment } from './ToolPaths'; export interface BuiltCommand { /** Shell command string to execute via cp.exec. */ @@ -52,6 +53,23 @@ function shellEscapeArg(arg: string): string { return "'" + arg.replace(/'/g, "'\\''") + "'"; } +type WslExec = (args: string[], options: { encoding?: BufferEncoding; timeout: number }) => string | Buffer; + +let wslExec: WslExec = (args, options) => cp.execFileSync('wsl', args, options); + +/** + * Replaces the calls to wsl.exe, so the Windows command builders can be + * tested on any platform. + */ +export function setWslExecForTesting(fake: WslExec | null): void { + wslExec = fake ?? ((args, options) => cp.execFileSync('wsl', args, options)); +} + +/** The Windows builder, for tests on other platforms (with setMockWslAvailableForTesting). */ +export function buildWindowsCommandForTesting(ctracePath: string, inputFilePath: string, params: string): Promise { + return buildWindowsCommand(ctracePath, inputFilePath, params); +} + /** * Converts a Windows-style path to its WSL POSIX equivalent using `wslpath`. * Falls back to a simple `/mnt//` prefix substitution if the command fails. @@ -63,7 +81,7 @@ function toWslPath(winPath: string, distroName: string | null = null): string { ...(distroName ? ['-d', distroName] : []), 'wslpath', '-u', normalized, ]; - return cp.execFileSync('wsl', args, { timeout: 5000 }).toString().trim(); + return wslExec(args, { timeout: 5000 }).toString().trim(); } catch { return normalized.replace(/^([a-zA-Z]):/, (_, d) => `/mnt/${d.toLowerCase()}`); } @@ -108,7 +126,8 @@ function buildNativeCommand( const extraArgs = compileCommands ? ` --compile-commands ${input}` : ''; 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')} && `; + // Cppcheck is resolved like the dependency check does (ToolPaths.ts). + const envExports = `${cppcheckEnvironment()}export 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}`; return { command, tempFiles: [] }; @@ -129,6 +148,33 @@ function parseWslUNC(p: string): { distro: string; internalPath: string } | null return null; } +/** + * The WSL distribution a scan of these paths runs in: the one named by a + * WSL path (\\wsl$\Debian\...) when it is not the default one, else null + * for the default distribution. Same rule as trySmartDistroExecution(), so + * the analyzers are checked and installed where they will run. + */ +export function executionDistro(...paths: (string | undefined)[]): string | null { + const detected = paths.map(p => p ? parseWslUNC(p) : null).find(Boolean)?.distro; + if (!detected) { return null; } + try { + const clean = (s: string) => s.replace(/[\u0000-\u001F\u007F-\u009F\uFEFF\uFFFD]/g, '').trim(); + const lines = wslExec(['-l', '-v'], { encoding: 'utf16le', timeout: 5000 }).toString().split(/[\r\n]+/).filter(l => l.trim()); + let defaultDistro = ''; + let matched = ''; + for (const line of lines) { + if (line.includes('NAME') && line.includes('STATE')) { continue; } + const name = clean(line.replace('*', '').trim().split(/\s+/)[0] ?? ''); + if (line.trim().startsWith('*')) { defaultDistro = name; } + if (name.toLowerCase() === detected.toLowerCase()) { matched = name; } + } + if (!matched || matched === defaultDistro) { return null; } + return resolveDistroName(matched); + } catch { + return null; + } +} + let cachedWslAvailable: { result: boolean; timestamp: number } | null = null; let mockWslAvailable: boolean | null = null; @@ -152,7 +198,7 @@ export function isWslAvailable(): boolean { return cachedWslAvailable.result; } try { - const stdout = cp.execFileSync('wsl', ['-l', '-q'], { encoding: 'utf16le', timeout: 5000 }); + const stdout = wslExec(['-l', '-q'], { encoding: 'utf16le', timeout: 5000 }).toString(); const clean = stdout.replace(/[\u0000-\u001F\u007F-\u009F\uFEFF\uFFFD]/g, '').trim(); const available = Boolean(clean) && !/no installed distributions|no distribution/i.test(clean); cachedWslAvailable = { result: available, timestamp: now }; @@ -203,7 +249,7 @@ function trySmartDistroExecution( const clean = (s: string) => s.replace(/[\u0000-\u001F\u007F-\u009F\uFEFF\uFFFD]/g, '').trim(); // execFileSync avoids spawning a shell (cmd.exe); encoding:'utf16le' is // supported by Node's execFileSync just as it is by execSync. - const stdout = cp.execFileSync('wsl', ['-l', '-v'], { encoding: 'utf16le', timeout: 5000 }); + const stdout = wslExec(['-l', '-v'], { encoding: 'utf16le', timeout: 5000 }).toString(); const lines = stdout.split(/[\r\n]+/).filter(l => l.trim()); let defaultDistro = ''; @@ -282,7 +328,7 @@ function resolveDistroName(distro: string): string | null { const safeDistro = distro.replace(/["'`\\]/g, ''); if (!safeDistro) { return null; } try { - cp.execFileSync('wsl', ['-d', safeDistro, 'true'], { timeout: 5000 }); + wslExec(['-d', safeDistro, 'true'], { timeout: 5000 }); return safeDistro; } catch { // fall through @@ -315,12 +361,7 @@ async function buildFallbackCommand( const tempBin = path.join(os.tmpdir(), `ctrace-bin-${stamp}`); const lBin = `/tmp/ctrace-${stamp}`; - await fs.promises.copyFile(ctracePath, tempBin); - tempFiles.push(tempBin); - - const wBin = toWslPath(tempBin); - const wInput = toWslPath(inputFilePath); - + // Validated before the CLI is copied: a rejected argument leaves nothing behind. const validatedParamsTokens = parseAndValidateParams(params).map(token => { const eqIndex = token.indexOf('='); if (eqIndex > 0) { @@ -333,18 +374,40 @@ async function buildFallbackCommand( return token; }); const validatedParams = validatedParamsTokens.map(shellEscapeArg).join(' '); + + await fs.promises.copyFile(ctracePath, tempBin); + tempFiles.push(tempBin); + try { + return await finishFallbackCommand(ctracePath, inputFilePath, validatedParams, tempBin, lBin, tempFiles, compileCommands); + } catch (error) { + await Promise.all(tempFiles.map(file => fs.promises.unlink(file).catch(() => { /* already gone */ }))); + throw error; + } +} + +async function finishFallbackCommand( + ctracePath: string, + inputFilePath: string, + validatedParams: string, + tempBin: string, + lBin: string, + tempFiles: string[], + compileCommands: boolean +): Promise { + const wBin = toWslPath(tempBin); + const wInput = toWslPath(inputFilePath); const extraArgs = compileCommands ? ` --compile-commands ${shellEscapeArg(wInput)}` : ''; const libDir = getLibDirForBinary(ctracePath); const libEnv = libDir ? `export LD_LIBRARY_PATH=${shellEscapeArg(toWslPath(libDir))}:"$LD_LIBRARY_PATH" && ` : ''; - const script = `${wslToolEnvironment()}${libEnv}cp ${shellEscapeArg(wBin)} ${shellEscapeArg(lBin)} && chmod +x ${shellEscapeArg(lBin)} && ${shellEscapeArg(lBin)} --input ${shellEscapeArg(wInput)}${extraArgs} ${validatedParams}; rm -f ${shellEscapeArg(lBin)}`; + const script = `${wslToolEnvironment()}${libEnv}cp ${shellEscapeArg(wBin)} ${shellEscapeArg(lBin)} && chmod +x ${shellEscapeArg(lBin)} && ${shellEscapeArg(lBin)} --input ${shellEscapeArg(wInput)}${extraArgs} ${validatedParams}; status=$?; rm -f ${shellEscapeArg(lBin)}; exit "$status"`; return await writeWslScript(script, null, tempFiles); } 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 `cd "${toolsDir}" 2>/dev/null || true; ${cppcheckEnvironment()}export 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..a273edd 100644 --- a/src/ctrace/DependencyInstaller.ts +++ b/src/ctrace/DependencyInstaller.ts @@ -4,6 +4,7 @@ import * as os from 'os'; import * as path from 'path'; import * as vscode from 'vscode'; import { isWslAvailable } from './CommandBuilder'; +import { CPPCHECK_RESOLVER_SH, HOMEBREW_INSTALL_SH, installErrors } from './ToolPaths'; let mockPasswordlessSudo: boolean | null = null; @@ -131,30 +132,11 @@ export async function checkDependencies(distro?: string | null): Promise/dev/null 2>&1; then - return 0 - fi - local ver=$("$bin" --version 2>/dev/null | grep -oE '[0-9]+\.[0-9]+' | head -1) - if [ -n "$ver" ]; then - local major=$(echo "$ver" | cut -d. -f1) - local minor=$(echo "$ver" | cut -d. -f2) - [ "$major" -gt 2 ] || { [ "$major" -eq 2 ] && [ "$minor" -ge 14 ]; } && return 0 - fi - return 1 - } - + ${CPPCHECK_RESOLVER_SH} if has_cmd cppcheck; then CPPCHECK_SYS=1; fi - if has_file /opt/homebrew/bin/cppcheck; then - CPPCHECK_BREW=1 - if check_cppcheck_sarif /opt/homebrew/bin/cppcheck; then - CPPCHECK_SARIF=1 - fi - elif check_cppcheck_sarif "$(command -v cppcheck 2>/dev/null)"; then - CPPCHECK_SARIF=1 - fi + if has_file "\${CORETRACE_HOMEBREW_BIN:-/opt/homebrew/bin}/cppcheck"; then CPPCHECK_BREW=1; fi + # Same choice as the analysis command makes (see ToolPaths.ts). + if [ -n "$(coretrace_resolve_cppcheck)" ]; then CPPCHECK_SARIF=1; fi if has_file "$HOME/.coretrace/tools/flawfinder/src/flawfinder-build/flawfinder.py" || has_cmd flawfinder; then FLAWFINDER_OK=1 @@ -185,7 +167,8 @@ export async function checkDependencies(distro?: string | null): Promise/dev/null 2>&1; then echo "Detected Alpine Linux (apk)." apk add --no-cache cppcheck flawfinder build-base git cmake python3 py3-pip curl || true elif command -v brew >/dev/null 2>&1; then - echo "Detected macOS (Homebrew)." - # Homebrew refuses to run as root, so install as the invoking user. - sudo -u "\${SUDO_USER:-$(id -un)}" brew install cppcheck flawfinder cmake python3 || true - # IKOS is only published through NASA's tap (builds LLVM deps, can take a while). - sudo -u "\${SUDO_USER:-$(id -un)}" brew install nasa-sw-vnv/core/ikos || true +${HOMEBREW_INSTALL_SH} else echo "Warning: Unrecognized package manager. Please ensure git, g++, make, cmake, python3, and curl are installed." fi @@ -393,32 +372,15 @@ export async function installDependencies( progress.report({ message: 'Installing packages & building analyzers in WSL/Linux...', increment: 20 }); if (process.platform !== 'win32' && !(await canRunSudoWithoutPassword())) { - const scriptPath = path.join(os.tmpdir(), `coretrace-install-${Date.now()}-${process.pid}.sh`); - await fs.promises.writeFile(scriptPath, script, { mode: 0o755 }); output.appendLine('[CoreTrace] sudo requires a password on this machine. Launching installer in interactive VS Code terminal...'); vscode.window.showInformationMessage( 'CoreTrace dependency installation requires administrator (sudo) privileges. Please enter your password in the opened terminal to proceed.' ); - const terminal = vscode.window.createTerminal({ name: 'CoreTrace: Install Dependencies' }); - terminal.show(true); - terminal.sendText(`sudo "${scriptPath}" && rm -f "${scriptPath}"`); - - const disposable = vscode.window.onDidCloseTerminal(async (closedTerminal) => { - if (closedTerminal === terminal) { - disposable.dispose(); - try { await fs.promises.unlink(scriptPath).catch(() => {}); } catch {} - const status = await checkDependencies(distro); - if (status.allInstalled) { - output.appendLine('[CoreTrace] All dependencies (cppcheck, flawfinder, ikos, tscancode) are operational!'); - vscode.window.showInformationMessage('CoreTrace analyzers (cppcheck, flawfinder, ikos, tscancode) have been successfully installed and configured!'); - } else { - const missingList = status.missing.join(', '); - output.appendLine(`[CoreTrace] Some dependencies could not be verified: ${missingList}`); - vscode.window.showWarningMessage(`Dependency setup finished, but some tools could not be verified: ${missingList}. Check the Output channel.`); - } - } - }); - return true; + progress.report({ message: 'Waiting for the installer in the terminal...' }); + const log = await runInstallerInTerminal(script); + output.append(log); + progress.report({ message: 'Verifying installed tools...', increment: 5 }); + return reportVerification(await checkDependencies(distro), installErrors(log), output); } const result = await execShellCommand(script, { @@ -448,16 +410,62 @@ export async function installDependencies( // Verify after installation progress.report({ message: 'Verifying installed tools...', increment: 5 }); - const status = await checkDependencies(distro); + return reportVerification(await checkDependencies(distro), installErrors(result.stdout + result.stderr), output); +} +/** + * Tells the user what the installation achieved. A package-manager error + * (e.g. Homebrew refusing an untrusted tap formula for IKOS) is shown as + * is, since it says what to do; returns whether every tool now works. + */ +function reportVerification(status: DependencyStatus, errors: string[], output: vscode.OutputChannel): boolean { if (status.allInstalled) { output.appendLine('[CoreTrace] All dependencies (cppcheck, flawfinder, ikos, tscancode) are operational!'); vscode.window.showInformationMessage('CoreTrace analyzers (cppcheck, flawfinder, ikos, tscancode) have been successfully installed and configured!'); return true; + } + const missingList = status.missing.join(', '); + output.appendLine(`[CoreTrace] Some dependencies could not be verified: ${missingList}`); + errors.forEach(error => output.appendLine(`[CoreTrace] Installer error: ${error}`)); + if (errors.length > 0) { + vscode.window.showErrorMessage( + `Could not install ${missingList}. ${errors.join(' ')} Fix this, then install the analyzers again.`, 'Show Output' + ).then(action => { if (action) { output.show(true); } }); } else { - const missingList = status.missing.join(', '); - output.appendLine(`[CoreTrace] Some dependencies could not be verified: ${missingList}`); vscode.window.showWarningMessage(`Dependency setup finished, but some tools could not be verified: ${missingList}. Check the Output channel.`); - return false; + } + return false; +} + +/** + * Runs the installer with sudo in a terminal, where the user types the + * password, and resolves with its output once the terminal is closed. + * The script and its log live in a private folder: a predictable name in + * the shared temporary directory could be replaced before sudo runs it. + */ +async function runInstallerInTerminal(script: string): Promise { + const dir = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'coretrace-install-')); + const scriptPath = path.join(dir, 'install.sh'); + const logPath = path.join(dir, 'install.log'); + await fs.promises.writeFile(scriptPath, script, { mode: 0o700 }); + const quote = (value: string) => "'" + value.replace(/'/g, "'\\''") + "'"; + try { + await new Promise(resolve => { + const terminal = vscode.window.createTerminal({ + name: 'CoreTrace: Install Dependencies', + shellPath: '/bin/sh', + shellArgs: ['-c', `sudo sh ${quote(scriptPath)} 2>&1 | tee ${quote(logPath)}; echo; echo 'Installer finished: press Enter to close this terminal.'; read _`], + }); + const disposable = vscode.window.onDidCloseTerminal(closed => { + if (closed === terminal) { + disposable.dispose(); + resolve(); + } + }); + terminal.show(true); + }); + return await fs.promises.readFile(logPath, 'utf8').catch(() => ''); + } finally { + await fs.promises.rm(dir, { recursive: true, force: true }).catch(() => { /* best effort */ }); } } diff --git a/src/ctrace/RunOutcome.ts b/src/ctrace/RunOutcome.ts new file mode 100644 index 0000000..756f89c --- /dev/null +++ b/src/ctrace/RunOutcome.ts @@ -0,0 +1,23 @@ +/** ctrace exit codes (--fail-on): 2 = completed with findings, 3 = a tool could not run. */ +export const EXIT_FINDINGS = 2; +export const EXIT_INCOMPLETE = 3; + +/** + * The tools ctrace names as not run, from lines like + * "[ERROR] Analysis incomplete: tscancode could not run (exit code 3)" and + * "Error: Command not found in PATH: ikos". + */ +export function failedTools(output: string): string[] { + const tools: string[] = []; + const add = (name: string) => { + const tool = name.trim(); + if (tool && !tools.includes(tool)) { tools.push(tool); } + }; + for (const match of output.matchAll(/Analysis incomplete:\s*(.+?)\s+could not run/gi)) { + match[1].split(/\s*,\s*|\s+and\s+/).forEach(add); + } + for (const match of output.matchAll(/Command not found in PATH:\s*([\w.+-]+)/gi)) { + add(match[1]); + } + return tools; +} diff --git a/src/ctrace/ToolPaths.ts b/src/ctrace/ToolPaths.ts new file mode 100644 index 0000000..23861aa --- /dev/null +++ b/src/ctrace/ToolPaths.ts @@ -0,0 +1,65 @@ +/** + * Shell code that picks the Cppcheck ctrace runs, shared by the dependency + * check and by the analysis command so that both agree: the first + * SARIF-capable (>= 2.14) executable among Homebrew's, CoreTrace's own + * tools folder, and PATH. Prints nothing when there is none. + * + * CORETRACE_HOMEBREW_BIN replaces /opt/homebrew/bin in tests. + */ +export const CPPCHECK_RESOLVER_SH = ` +coretrace_cppcheck_sarif() { + [ -n "$1" ] && [ -x "$1" ] || return 1 + if "$1" --output-format=sarif /dev/null >/dev/null 2>&1; then return 0; fi + v=$("$1" --version 2>/dev/null | grep -oE '[0-9]+\\.[0-9]+' | head -1) + [ -n "$v" ] || return 1 + major=\${v%%.*}; minor=\${v#*.} + [ "$major" -gt 2 ] || { [ "$major" -eq 2 ] && [ "$minor" -ge 14 ]; } +} +coretrace_resolve_cppcheck() { + for candidate in "\${CORETRACE_HOMEBREW_BIN:-/opt/homebrew/bin}/cppcheck" "$HOME/.coretrace/tools/bin/cppcheck" "$(command -v cppcheck 2>/dev/null)"; do + if coretrace_cppcheck_sarif "$candidate"; then echo "$candidate"; return 0; fi + done + return 0 +} +`; + +/** Exports CORETRACE_CPPCHECK_BIN for ctrace, keeping the former default when none is found. */ +export function cppcheckEnvironment(): string { + return `${CPPCHECK_RESOLVER_SH} +CORETRACE_CPPCHECK_PATH="$(coretrace_resolve_cppcheck)" +export CORETRACE_CPPCHECK_BIN="\${CORETRACE_CPPCHECK_PATH:-/opt/homebrew/bin/cppcheck}" +`; +} + +/** + * The Homebrew part of the installer. Homebrew refuses to run as root, so + * it runs as the user who invoked sudo. A failure is no longer hidden: it is + * printed and summed up on a CORETRACE_INSTALL_ERROR line, which the + * extension shows (e.g. a tap formula that Homebrew asks to trust first). + */ +export const HOMEBREW_INSTALL_SH = ` +coretrace_brew() { + if [ "$(id -u)" = 0 ] && [ -n "$SUDO_USER" ]; then sudo -u "$SUDO_USER" brew "$@"; else brew "$@"; fi +} +coretrace_brew_install() { + tool="$1"; shift + if out=$(coretrace_brew install "$@" 2>&1); then + printf '%s\\n' "$out" + else + printf '%s\\n' "$out" + reason=$(printf '%s\\n' "$out" | grep -iE 'error|refus|trust|untrusted|failed' | tail -3 | tr '\\n' ' ') + echo "CORETRACE_INSTALL_ERROR $tool: \${reason:-brew install $* failed}" + fi +} +echo "Detected macOS (Homebrew)." +coretrace_brew_install cppcheck cppcheck +coretrace_brew_install flawfinder flawfinder +coretrace_brew_install build-tools cmake python3 +# IKOS is only published through NASA's tap (builds LLVM deps, can take a while). +coretrace_brew_install ikos nasa-sw-vnv/core/ikos +`; + +/** The CORETRACE_INSTALL_ERROR lines of an installer run, as "tool: reason". */ +export function installErrors(output: string): string[] { + return [...output.matchAll(/^CORETRACE_INSTALL_ERROR (.+)$/gm)].map(match => match[1].trim()); +} diff --git a/src/ctrace/WorkspaceScanner.ts b/src/ctrace/WorkspaceScanner.ts index bf58c8f..61aa3a8 100755 --- a/src/ctrace/WorkspaceScanner.ts +++ b/src/ctrace/WorkspaceScanner.ts @@ -18,6 +18,11 @@ export interface WorkspaceFile { export interface CachedFileAnalysis { sarif: SarifLog; stack: StackReport | null; + /** + * Every requested tool ran. Only complete analyses are cached; entries + * saved before this flag existed may hold partial results and are redone. + */ + complete?: boolean; } export interface PartitionResult { @@ -113,7 +118,7 @@ export async function partitionFiles(files: string[], contextKey: string): Promi for (const fsPath of files) { const hash = await fileContentHash(fsPath); const entry = _analysisCache.get(fsPath); - if (hash && entry && entry.hash === hash && entry.contextKey === contextKey) { + if (hash && entry && entry.hash === hash && entry.contextKey === contextKey && entry.analysis.complete === true) { cached.set(fsPath, entry.analysis); } else { changed.push({ fsPath, hash: hash ?? '' }); diff --git a/src/extension.ts b/src/extension.ts index a498c0d..87e29df 100755 --- a/src/extension.ts +++ b/src/extension.ts @@ -4,7 +4,7 @@ import * as path from 'path'; import { SidebarProvider } from './SidebarProvider'; import { locateBinary } from './ctrace/BinaryLocator'; -import { buildCommand, isWslAvailable } from './ctrace/CommandBuilder'; +import { buildCommand, executionDistro, isWslAvailable } from './ctrace/CommandBuilder'; import { runCommand, DEFAULT_TIMEOUT_MS } from './ctrace/AnalysisRunner'; import { parseSarifOutput } from './ctrace/SarifParser'; import { updateDiagnostics, clearDiagnostics, getFindingForDiagnostic, FindingRef } from './ctrace/DiagnosticsManager'; @@ -29,6 +29,7 @@ import { checkDependencies, installDependencies } from './ctrace/DependencyInsta import { StackManager } from './ctrace/StackManager'; import { parseStackReport, mergeStackReports } from './ctrace/StackParser'; import { FindingsStore } from './ctrace/FindingsStore'; +import { EXIT_INCOMPLETE, failedTools } from './ctrace/RunOutcome'; export function activate(context: vscode.ExtensionContext) { @@ -147,21 +148,28 @@ export function activate(context: vscode.ExtensionContext) { // ── Command: ctrace.installDependencies ────────────────────────────────── context.subscriptions.push( - vscode.commands.registerCommand('ctrace.installDependencies', async () => { + vscode.commands.registerCommand('ctrace.installDependencies', async (arg?: { distro?: string | null }): Promise => { if (process.platform === 'win32' && !isWslAvailable()) { output.appendLine('[ctrace] Windows Subsystem for Linux (WSL) is required to install dependencies on Windows.'); promptWslInstallation(); - return; + return false; } - await vscode.window.withProgress( + return vscode.window.withProgress( { location: vscode.ProgressLocation.Notification, title: 'CoreTrace: Installing Analyzers & Dependencies', cancellable: false, }, - async (progress) => { - await installDependencies(output, progress); + async (progress): Promise => { + // Install where the scan runs: the distribution a preflight + // asked for, else the one of the active file (WSL paths). + const activeFile = vscode.window.activeTextEditor?.document.uri.fsPath; + const distro = arg && 'distro' in arg + ? arg.distro ?? null + : process.platform === 'win32' ? executionDistro(activeFile) : null; + if (distro) { output.appendLine(`[ctrace] Installing the analyzers in the WSL distribution ${distro}.`); } + return installDependencies(output, progress, distro); } ); }) @@ -259,7 +267,11 @@ export function activate(context: vscode.ExtensionContext) { const requestedStaticTools: string[] = (uiState.staticTools ?? ['cppcheck', 'flawfinder', 'ikos', 'tscancode', 'ctrace_stack_analyzer']) .filter(tool => tool !== 'coretrace-python-analyzer'); if (hasCFiles && uiState.staticEnabled !== false && requestedStaticTools.length > 0) { - const depStatus = await checkDependencies(); + // The analyzers are checked in the distribution that will run the scan. + const toolsDistro = process.platform === 'win32' + ? executionDistro(scanWorkspace ? workspaceRoot : filesToAnalyze[0]) + : null; + const depStatus = await checkDependencies(toolsDistro); const missingRequested = requestedStaticTools.filter((t) => depStatus.missing.includes(t)); if (missingRequested.length > 0) { const action = await vscode.window.showWarningMessage( @@ -268,9 +280,13 @@ export function activate(context: vscode.ExtensionContext) { 'Run Anyway' ); if (action === 'Install Analyzers') { - sidebarProvider.postMessage({ type: 'analysis-done' }); - vscode.commands.executeCommand('ctrace.installDependencies'); - return; + // Waits for the installer and its verification, then the + // scan goes on with the tools just installed. + const installed = await vscode.commands.executeCommand('ctrace.installDependencies', { distro: toolsDistro }); + if (!installed) { + sidebarProvider.postMessage({ type: 'analysis-done' }); + return; + } } } } @@ -433,6 +449,8 @@ export function activate(context: vscode.ExtensionContext) { const step = queue.length > 0 ? 100 / queue.length : 100; let hadToolExecutionWarning = false; + // Files whose run exited 3: their findings are shown, but some tools did not run. + const incompleteRuns: { file: string; tools: string[] }[] = []; try { for (let i = 0; i < queue.length; i++) { if (token.isCancellationRequested) { @@ -492,6 +510,12 @@ export function activate(context: vscode.ExtensionContext) { output.appendLine(`[exit ${exitCode ?? 0}]`); const combined = (stdout || '') + (stderr || ''); + const incomplete = exitCode === EXIT_INCOMPLETE; + if (incomplete) { + const tools = failedTools(combined); + incompleteRuns.push({ file: fileName, tools }); + output.appendLine(`[ctrace] Incomplete analysis of ${fileName}: ${tools.length ? `${tools.join(', ')} could not run` : 'a tool could not run'}.`); + } if (/(?:command not found|unrecognized command line option|cannot execute binary file|execvp: No such file or directory|can't open file '.*(?:flawfinder|ikos|tscancode|cppcheck).*':\s*\[Errno 2\] No such file or directory|\/opt\/homebrew\/bin\/cppcheck:\s*(?:No such file or directory|not found))/i.test(combined)) { hadToolExecutionWarning = true; output.appendLine('[ctrace warning] Note: one or more static analysis tools (e.g. cppcheck/flawfinder/ikos/tscancode) could not be executed by ctrace.'); @@ -570,8 +594,9 @@ export function activate(context: vscode.ExtensionContext) { allSarif.push(sarif); lastSarifByFile.set(fp, sarif); updateDiagnostics(sarif, diagnosticCollection, fp, !scanWorkspace, { isIgnored }); - if (incremental && !killed && queue[i].hash) { - cacheFileAnalysis(queue[i], contextKeys[language] ?? '', { sarif, stack: fileStack }); + // An incomplete result is not cached: the next scan retries the file. + if (incremental && !killed && !incomplete && queue[i].hash) { + cacheFileAnalysis(queue[i], contextKeys[language] ?? '', { sarif, stack: fileStack, complete: true }); } } else if (!scanWorkspace) { // Single-file mode: report parse failure immediately @@ -622,7 +647,20 @@ export function activate(context: vscode.ExtensionContext) { ? ` across ${filesToAnalyze.length} files` : '') + (cachedCount > 0 ? ` (${cachedCount} unchanged, reused from cache)` : ''); - if (total > 0) { + if (incompleteRuns.length > 0) { + const tools = [...new Set(incompleteRuns.flatMap(run => run.tools))]; + const which = tools.length > 0 ? tools.join(', ') : 'some tools'; + const files = incompleteRuns.length === 1 ? incompleteRuns[0].file : `${incompleteRuns.length} files`; + vscode.window.showWarningMessage( + `Analysis incomplete — ${total} issue${total === 1 ? '' : 's'} found${filesSuffix}, but ${which} could not run on ${files}: their findings are missing. See the Ctrace output channel.` + ); + sidebarProvider.postMessage({ + type: 'analysis-status', + status: 'error', + message: 'Analysis incomplete', + detail: `${which} could not run on ${files}`, + }); + } else if (total > 0) { vscode.window.showInformationMessage( `Analysis complete — ${total} issue${total > 1 ? 's' : ''} found${filesSuffix}.` ); diff --git a/src/test-workspace/incomplete.test.ts b/src/test-workspace/incomplete.test.ts new file mode 100644 index 0000000..be1d8de --- /dev/null +++ b/src/test-workspace/incomplete.test.ts @@ -0,0 +1,84 @@ +import * as assert from 'assert'; +import * as fs from 'fs'; +import * as os from 'os'; +import * as path from 'path'; +import * as vscode from 'vscode'; +import * as AnalysisRunner from '../ctrace/AnalysisRunner'; +import * as BinaryUpdater from '../ctrace/BinaryUpdater'; +import { setMockWslAvailableForTesting } from '../ctrace/CommandBuilder'; +import { setScanDirectoryForTesting } from '../ctraceRunner'; + +/** Workspace scans where ctrace exits 3 (a tool could not run) on one file. */ +suite('Incomplete scans', function () { + this.timeout(60000); + + const runner = AnalysisRunner as { runCommand: typeof AnalysisRunner.runCommand }; + const updater = BinaryUpdater as { ensureBinary: typeof BinaryUpdater.ensureBinary }; + const originalRunCommand = runner.runCommand; + const originalEnsureBinary = updater.ensureBinary; + let work = ''; + let root = ''; + let launched: string[] = []; + + const inputOf = (command: string) => command.match(/--input '([^']+)'/)?.[1] ?? ''; + const sarifFor = (file: string) => JSON.stringify({ + $schema: 'https://json.schemastore.org/sarif-2.1.0.json', + version: '2.1.0', + runs: [{ + tool: { driver: { name: 'cppcheck' } }, + results: [{ + ruleId: 'partialRule', level: 'warning', message: { text: `found in ${path.basename(file)}` }, + locations: [{ physicalLocation: { artifactLocation: { uri: file }, region: { startLine: 1 } } }], + }], + }], + }); + const scan = () => vscode.commands.executeCommand('ctrace.runWorkspaceAnalysis', { + // No C tool selected: the C dependency check would wait for an answer. + uiState: { staticTools: ['coretrace-python-analyzer'], dynamicEnabled: false }, + }); + const analysed = () => launched.filter(c => c.includes('--sarif-format')).map(c => path.basename(inputOf(c))).sort(); + + suiteSetup(async () => { + root = vscode.workspace.workspaceFolders![0].uri.fsPath; + work = fs.mkdtempSync(path.join(os.tmpdir(), 'ctrace-incomplete-')); + const fakeBinary = path.join(work, 'ctrace'); + fs.writeFileSync(fakeBinary, '#!/bin/sh\n', { mode: 0o755 }); + updater.ensureBinary = async () => fakeBinary; + runner.runCommand = async (command: string) => { + launched.push(command); + if (!command.includes('--sarif-format')) { return { stdout: '', stderr: '', exitCode: 0 }; } + const file = inputOf(command); + // sample.c: findings, but tscancode could not run. app.py: complete, with findings. + return file.endsWith('sample.c') + ? { stdout: sarifFor(file), stderr: '[ERROR] Analysis incomplete: tscancode could not run (exit code 3)', exitCode: 3 } + : { stdout: sarifFor(file), stderr: '', exitCode: 2 }; + }; + setMockWslAvailableForTesting(true); + setScanDirectoryForTesting(path.join(work, 'scan')); + await vscode.extensions.getExtension('CoreTrace.coretrace')!.activate(); + }); + + suiteTeardown(() => { + runner.runCommand = originalRunCommand; + updater.ensureBinary = originalEnsureBinary; + setMockWslAvailableForTesting(null); + setScanDirectoryForTesting(undefined); + fs.rmSync(work, { recursive: true, force: true }); + }); + + test('the findings of an incomplete file are shown, and the file is retried on the next scan', async function () { + if (process.platform === 'win32') { this.skip(); } + await vscode.commands.executeCommand('ctrace.clearAnalysisCache'); + launched = []; + await scan(); + assert.deepStrictEqual(analysed(), ['app.py', 'sample.c']); + const diagnostics = vscode.languages.getDiagnostics(vscode.Uri.file(path.join(root, 'sample.c'))) + .filter(d => d.source?.startsWith('CoreTrace')); + assert.strictEqual(diagnostics.length, 1, 'the available findings of the incomplete file must be shown'); + + launched = []; + await scan(); + // app.py (exit 2, complete) comes from the cache; sample.c (exit 3) is analysed again. + assert.deepStrictEqual(analysed(), ['sample.c']); + }); +}); diff --git a/src/test-workspace/installResume.test.ts b/src/test-workspace/installResume.test.ts new file mode 100644 index 0000000..7a4f596 --- /dev/null +++ b/src/test-workspace/installResume.test.ts @@ -0,0 +1,114 @@ +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 * as DependencyInstaller from '../ctrace/DependencyInstaller'; +import { setScanDirectoryForTesting } from '../ctraceRunner'; + +/** + * Run Analysis with a missing analyzer and the user choosing Install + * Analyzers: the installer and its check are replaced, the rest is real. + */ +suite('Run Analysis after installing analyzers', function () { + this.timeout(60000); + + const runner = AnalysisRunner as { runCommand: typeof AnalysisRunner.runCommand }; + const updater = BinaryUpdater as { ensureBinary: typeof BinaryUpdater.ensureBinary }; + const installer = DependencyInstaller as { + checkDependencies: typeof DependencyInstaller.checkDependencies; + installDependencies: typeof DependencyInstaller.installDependencies; + }; + const window = vscode.window as { showWarningMessage: typeof vscode.window.showWarningMessage }; + const originals = { + runCommand: runner.runCommand, + ensureBinary: updater.ensureBinary, + checkDependencies: installer.checkDependencies, + installDependencies: installer.installDependencies, + showWarningMessage: window.showWarningMessage, + }; + let work = ''; + let launched: string[] = []; + let prompts = 0; + let installs = 0; + let installWorks = true; + let ikosInstalled = false; + + const status = (): DependencyInstaller.DependencyStatus => ({ + allInstalled: ikosInstalled, + missing: ikosInstalled ? [] : ['ikos'], + details: { cppcheck: true, cppcheckHomebrew: false, cppcheckSarif: true, flawfinder: true, ikos: ikosInstalled, tscancode: true }, + }); + const run = () => vscode.commands.executeCommand('ctrace.runAnalysis', { + filePath: path.join(vscode.workspace.workspaceFolders![0].uri.fsPath, 'sample.c'), + uiState: { staticTools: ['ikos'], dynamicEnabled: false }, + }); + const analysed = () => launched.filter(command => command.includes('--sarif-format')).length; + + suiteSetup(async () => { + work = fs.mkdtempSync(path.join(os.tmpdir(), 'ctrace-resume-')); + 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 }; + }; + installer.checkDependencies = async () => status(); + installer.installDependencies = async () => { + installs++; + ikosInstalled = installWorks; + return installWorks; + }; + window.showWarningMessage = ((message: string, ...items: string[]) => { + if (items.includes('Install Analyzers')) { + prompts++; + return Promise.resolve('Install Analyzers'); + } + return originals.showWarningMessage(message, ...items); + }) as typeof vscode.window.showWarningMessage; + setMockWslAvailableForTesting(true); + setScanDirectoryForTesting(path.join(work, 'scan')); + await vscode.extensions.getExtension('CoreTrace.coretrace')!.activate(); + }); + + suiteTeardown(() => { + runner.runCommand = originals.runCommand; + updater.ensureBinary = originals.ensureBinary; + installer.checkDependencies = originals.checkDependencies; + installer.installDependencies = originals.installDependencies; + window.showWarningMessage = originals.showWarningMessage; + setMockWslAvailableForTesting(null); + setScanDirectoryForTesting(undefined); + fs.rmSync(work, { recursive: true, force: true }); + }); + + setup(() => { launched = []; prompts = 0; installs = 0; }); + + test('a failed repair does not start the scan', async function () { + if (process.platform === 'win32') { this.skip(); } + ikosInstalled = false; + installWorks = false; + await run(); + assert.strictEqual(installs, 1); + assert.strictEqual(analysed(), 0); + }); + + test('after a successful repair the original scan resumes, and the next run asks nothing', async function () { + if (process.platform === 'win32') { this.skip(); } + ikosInstalled = false; + installWorks = true; + await run(); + assert.strictEqual(installs, 1); + assert.strictEqual(analysed(), 1, 'the scan must resume after the verified install'); + + launched = []; prompts = 0; installs = 0; + await run(); + assert.strictEqual(prompts, 0, 'no installer prompt once the tools are verified'); + assert.strictEqual(installs, 0); + assert.strictEqual(analysed(), 1); + }); +}); diff --git a/src/test/findings.test.ts b/src/test/findings.test.ts index 3fda5c6..4e663fc 100644 --- a/src/test/findings.test.ts +++ b/src/test/findings.test.ts @@ -193,7 +193,7 @@ suite('Incremental workspace scan Test Suite', () => { let partition = await partitionFiles([a, b], 'key1'); assert.deepStrictEqual(partition.changed.map(f => f.fsPath), [a, b]); for (const file of partition.changed) { - cacheFileAnalysis(file, 'key1', { sarif: emptySarif(path.basename(file.fsPath)), stack: null }); + cacheFileAnalysis(file, 'key1', { sarif: emptySarif(path.basename(file.fsPath)), stack: null, complete: true }); } partition = await partitionFiles([a, b], 'key1'); @@ -221,7 +221,7 @@ suite('Incremental workspace scan Test Suite', () => { try { await initAnalysisCache(storage); for (const file of (await partitionFiles([a, gone], 'key')).changed) { - cacheFileAnalysis(file, 'key', { sarif: emptySarif('x'), stack: null }); + cacheFileAnalysis(file, 'key', { sarif: emptySarif('x'), stack: null, complete: true }); } fs.unlinkSync(gone); await persistAnalysisCache(); @@ -242,6 +242,27 @@ suite('Incremental workspace scan Test Suite', () => { } }); + test('incomplete analyses, and entries saved before the flag existed, are analysed again', async () => { + const dir = tempDir('ctrace-incr-'); + const done = path.join(dir, 'done.c'); + const partial = path.join(dir, 'partial.c'); + const legacy = path.join(dir, 'legacy.c'); + for (const file of [done, partial, legacy]) { fs.writeFileSync(file, `int ${path.basename(file, '.c')};`); } + try { + const [d, p, l] = (await partitionFiles([done, partial, legacy], 'key')).changed; + cacheFileAnalysis(d, 'key', { sarif: emptySarif('done'), stack: null, complete: true }); + cacheFileAnalysis(p, 'key', { sarif: emptySarif('partial'), stack: null, complete: false }); + // As written by a version without the flag. + cacheFileAnalysis(l, 'key', { sarif: emptySarif('legacy'), stack: null }); + + const partition = await partitionFiles([done, partial, legacy], 'key'); + assert.deepStrictEqual([...partition.cached.keys()], [done]); + assert.deepStrictEqual(partition.changed.map(f => f.fsPath).sort(), [legacy, partial].sort()); + } finally { + fs.rmSync(dir, { recursive: true, force: true }); + } + }); + test('context key changes with the options and the dependency files', async () => { const dir = tempDir('ctrace-incr-'); const compdb = path.join(dir, 'compile_commands.json'); diff --git a/src/test/runOutcome.test.ts b/src/test/runOutcome.test.ts new file mode 100644 index 0000000..d06f85b --- /dev/null +++ b/src/test/runOutcome.test.ts @@ -0,0 +1,24 @@ +import * as assert from 'assert'; +import { failedTools } from '../ctrace/RunOutcome'; + +suite('Run outcome Test Suite', () => { + test('the tools that could not run are read from ctrace output', () => { + // As printed by ctrace 0.85 with tscancode missing. + const output = [ + '|42| == CoreTrace == [INFO] (cppcheck) Diagnostics summary: info=0, warning=0, error=1', + 'Error: Command not found in PATH: tscancode', + '|42| == CoreTrace == [ERROR] Analysis incomplete: tscancode could not run (exit code 3)', + ].join('\n'); + assert.deepStrictEqual(failedTools(output), ['tscancode']); + }); + + test('several tools in one line or several lines are all named once', () => { + const output = 'Analysis incomplete: ikos, tscancode and coretrace-runtime-analyzer could not run (exit code 3)\n' + + 'Error: Command not found in PATH: coretrace-runtime-analyzer'; + assert.deepStrictEqual(failedTools(output), ['ikos', 'tscancode', 'coretrace-runtime-analyzer']); + }); + + test('a complete run names no tool', () => { + assert.deepStrictEqual(failedTools('[INFO] Verdict: info=0, warning=1, error=0, fail-on=error (exit code 0)'), []); + }); +}); diff --git a/src/test/toolPaths.test.ts b/src/test/toolPaths.test.ts new file mode 100644 index 0000000..b63ff9f --- /dev/null +++ b/src/test/toolPaths.test.ts @@ -0,0 +1,114 @@ +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 { runCommand } from '../ctrace/AnalysisRunner'; +import { buildCommand } from '../ctrace/CommandBuilder'; +import { checkDependencies } from '../ctrace/DependencyInstaller'; +import { CPPCHECK_RESOLVER_SH, HOMEBREW_INSTALL_SH, installErrors } from '../ctrace/ToolPaths'; + +const posix = process.platform !== 'win32' ? suite : suite.skip; + +posix('Cppcheck resolution Test Suite', () => { + let work = ''; + let saved: NodeJS.ProcessEnv; + + /** A fake Cppcheck reporting `version`, without --output-format=sarif support. */ + function cppcheck(dir: string, version: string): string { + fs.mkdirSync(dir, { recursive: true }); + const file = path.join(dir, 'cppcheck'); + fs.writeFileSync(file, `#!/bin/sh\n[ "$1" = "--version" ] && echo "Cppcheck ${version}"\nexit 1\n`, { mode: 0o755 }); + return file; + } + + setup(() => { + work = fs.mkdtempSync(path.join(os.tmpdir(), 'ctrace-cppcheck-')); + saved = { ...process.env }; + // No Homebrew prefix, an empty home, and only our fake bin dir plus the system on PATH. + process.env.CORETRACE_HOMEBREW_BIN = path.join(work, 'homebrew', 'bin'); + process.env.HOME = path.join(work, 'home'); + process.env.PATH = `${path.join(work, 'path')}:/usr/bin:/bin`; + fs.mkdirSync(process.env.HOME, { recursive: true }); + }); + + teardown(() => { + process.env = saved; + fs.rmSync(work, { recursive: true, force: true }); + }); + + const resolve = () => cp.execFileSync('/bin/sh', ['-c', `${CPPCHECK_RESOLVER_SH}\ncoretrace_resolve_cppcheck`], { encoding: 'utf8' }).trim(); + + test('a SARIF-capable Cppcheck on PATH is used when Homebrew has none', () => { + const onPath = cppcheck(path.join(work, 'path'), '2.16'); + assert.strictEqual(resolve(), onPath); + }); + + test('a Homebrew Cppcheck too old for SARIF is skipped for a newer one', () => { + cppcheck(process.env.CORETRACE_HOMEBREW_BIN!, '2.10'); + const onPath = cppcheck(path.join(work, 'path'), '2.16'); + assert.strictEqual(resolve(), onPath); + }); + + test('Homebrew comes first when it is recent enough', () => { + const brew = cppcheck(process.env.CORETRACE_HOMEBREW_BIN!, '2.17'); + cppcheck(path.join(work, 'path'), '2.16'); + assert.strictEqual(resolve(), brew); + }); + + test('no SARIF-capable Cppcheck resolves to nothing', () => { + cppcheck(path.join(work, 'path'), '2.10'); + assert.strictEqual(resolve(), ''); + }); + + test('the dependency check and the analysis command pick the same Cppcheck', async () => { + const onPath = cppcheck(path.join(work, 'path'), '2.16'); + const status = await checkDependencies(); + assert.strictEqual(status.details.cppcheckSarif, true); + assert.ok(!status.missing.includes('cppcheck'), 'a Cppcheck outside /opt/homebrew/bin must count as installed'); + + // A ctrace that prints the Cppcheck it was given. + const ctrace = path.join(work, 'ctrace'); + fs.writeFileSync(ctrace, '#!/bin/sh\nprintf "%s" "$CORETRACE_CPPCHECK_BIN"\n', { mode: 0o755 }); + const { command } = await buildCommand(ctrace, path.join(work, 'main.c'), ''); + assert.strictEqual((await runCommand(command, work)).stdout, onPath); + }); +}); + +posix('Homebrew install Test Suite', () => { + let work = ''; + setup(() => { work = fs.mkdtempSync(path.join(os.tmpdir(), 'ctrace-brew-')); }); + teardown(() => fs.rmSync(work, { recursive: true, force: true })); + + /** Runs the installer's Homebrew part with a fake brew that refuses `failing`. */ + function install(failing: string | null): string { + const bin = path.join(work, 'bin'); + fs.mkdirSync(bin, { recursive: true }); + fs.writeFileSync(path.join(bin, 'brew'), `#!/bin/sh +for arg in "$@"; do + if [ "$arg" = "${failing ?? '-'}" ]; then + echo "==> Fetching nasa-sw-vnv/core/apron" + echo "Error: Refusing to load formula nasa-sw-vnv/core/apron: tap nasa-sw-vnv/core is not trusted." >&2 + exit 1 + fi +done +echo "==> Installed $*" +`, { mode: 0o755 }); + return cp.execFileSync('/bin/sh', ['-c', `set -e\n${HOMEBREW_INSTALL_SH}`], { + encoding: 'utf8', + env: { ...process.env, PATH: `${bin}:/usr/bin:/bin`, SUDO_USER: '' }, + }); + } + + test('a refused IKOS dependency is reported with Homebrew\'s own message, and the rest still installs', () => { + const output = install('nasa-sw-vnv/core/ikos'); + const errors = installErrors(output); + assert.strictEqual(errors.length, 1, output); + assert.match(errors[0], /^ikos: .*Refusing to load formula nasa-sw-vnv\/core\/apron.*not trusted/); + assert.match(output, /Installed install cppcheck/, 'a failure must not stop the other packages'); + }); + + test('a successful install reports no error', () => { + assert.deepStrictEqual(installErrors(install(null)), []); + }); +}); diff --git a/src/test/wslCommand.test.ts b/src/test/wslCommand.test.ts new file mode 100644 index 0000000..5253045 --- /dev/null +++ b/src/test/wslCommand.test.ts @@ -0,0 +1,96 @@ +import * as assert from 'assert'; +import * as fs from 'fs'; +import * as os from 'os'; +import * as path from 'path'; +import { buildWindowsCommandForTesting, executionDistro, setMockWslAvailableForTesting, setWslExecForTesting } from '../ctrace/CommandBuilder'; +import { shellQuoteArgs } from '../ctraceRunner'; + +/** + * The two Windows execution branches, on any platform, with a fake wsl.exe: + * a source in a WSL distribution (UNC path), and a Windows source run through + * a temporary copy of the CLI. + */ +suite('WSL command Test Suite', () => { + let work = ''; + let built: { command: string; tempFiles: string[] } | undefined; + + /** wslpath and the distribution list, as wsl.exe answers them. */ + const fakeWsl = (args: string[]) => { + if (args[0] === '-l') { return ' NAME STATE VERSION\n* Ubuntu Running 2\n Debian Stopped 2\n'; } + if (args.includes('wslpath')) { + const target = args[args.length - 1].replace(/\\/g, '/'); + const unc = target.match(/^\/\/wsl(?:\$|\.localhost)\/[^/]+(\/.*)$/i); + if (unc) { return unc[1]; } + return target.replace(/^([a-zA-Z]):/, (_m, drive: string) => `/mnt/${drive.toLowerCase()}`); + } + return ''; + }; + + setup(() => { + work = fs.mkdtempSync(path.join(os.tmpdir(), 'ctrace-wsl-')); + setMockWslAvailableForTesting(true); + setWslExecForTesting(fakeWsl); + built = undefined; + }); + + teardown(() => { + for (const file of built?.tempFiles ?? []) { fs.rmSync(file, { force: true }); } + setMockWslAvailableForTesting(null); + setWslExecForTesting(null); + fs.rmSync(work, { recursive: true, force: true }); + }); + + const script = () => fs.readFileSync(built!.tempFiles.find(file => file.endsWith('.sh'))!, 'utf8'); + const ctrace = () => { + const file = path.join(work, 'ctrace'); + fs.writeFileSync(file, 'binary'); + return file; + }; + + test('a Windows path with spaces stays one argument through the temporary-copy branch', async () => { + const args = ['--report-file=C:\\My Project\\report.json', '--compile-commands=C:\\My Project\\build\\compile_commands.json', '--static']; + built = await buildWindowsCommandForTesting(ctrace(), 'C:\\My Project\\src\\main.c', shellQuoteArgs(args)); + const text = script(); + assert.ok(text.includes("'--report-file=/mnt/c/My Project/report.json'"), text); + assert.ok(text.includes("'--compile-commands=/mnt/c/My Project/build/compile_commands.json'"), text); + assert.ok(text.includes("--input '/mnt/c/My Project/src/main.c'"), text); + assert.match(built.command, /^wsl --exec sh "/); + // The script cleans up its copy after ctrace but exits with ctrace's code. + assert.match(text, /; status=\$\?; rm -f '[^']+'; exit "\$status"\n?$/, text); + }); + + test('a source inside a WSL distribution with spaces runs in that distribution', async () => { + const args = ['--report-file=C:\\My Project\\report.json']; + built = await buildWindowsCommandForTesting(ctrace(), '\\\\wsl$\\Debian\\home\\me\\My Project\\main.c', shellQuoteArgs(args)); + const text = script(); + assert.ok(text.includes("--input '/home/me/My Project/main.c'"), text); + assert.ok(text.includes("'--report-file=/mnt/c/My Project/report.json'"), text); + assert.match(built.command, /^wsl -d "Debian" --exec sh "/, 'the non-default distribution must be used'); + }); + + test('the analyzers are checked in the distribution that runs the scan', () => { + // Debian is not the default: a scan of its files runs, and must be checked, there. + assert.strictEqual(executionDistro('\\\\wsl$\\Debian\\home\\me\\main.c'), 'Debian'); + assert.strictEqual(executionDistro('\\\\wsl.localhost\\debian\\home\\me\\main.c'), 'Debian'); + // The default distribution, an ordinary Windows path, or an unknown distribution keep the default (null). + assert.strictEqual(executionDistro('\\\\wsl$\\Ubuntu\\home\\me\\main.c'), null); + assert.strictEqual(executionDistro('C:\\My Project\\main.c'), null); + assert.strictEqual(executionDistro('\\\\wsl$\\Arch\\home\\me\\main.c'), null); + assert.strictEqual(executionDistro(undefined), null); + }); + + test('without wsl.exe, the default distribution is kept', () => { + setWslExecForTesting(() => { throw new Error('wsl.exe not found'); }); + assert.strictEqual(executionDistro('\\\\wsl$\\Debian\\home\\me\\main.c'), null); + }); + + test('an unsafe argument is still rejected, and leaves no temporary copy behind', async () => { + const before = new Set(fs.readdirSync(os.tmpdir()).filter(name => name.startsWith('ctrace-bin-'))); + await assert.rejects( + buildWindowsCommandForTesting(ctrace(), 'C:\\src\\main.c', shellQuoteArgs(['--report-file=C:\\x;rm -rf ~'])), + /Unsafe CLI parameter rejected/ + ); + const after = fs.readdirSync(os.tmpdir()).filter(name => name.startsWith('ctrace-bin-') && !before.has(name)); + assert.deepStrictEqual(after, [], 'the temporary CLI copy must be removed'); + }); +});