Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
89 changes: 76 additions & 13 deletions src/ctrace/CommandBuilder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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. */
Expand Down Expand Up @@ -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<BuiltCommand> {
return buildWindowsCommand(ctracePath, inputFilePath, params);
}

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

Expand All @@ -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 };
Expand Down Expand Up @@ -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 = '';
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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) {
Expand All @@ -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<BuiltCommand> {
const wBin = toWslPath(tempBin);
const wInput = toWslPath(inputFilePath);
const extraArgs = compileCommands ? ` --compile-commands ${shellEscapeArg(wInput)}` : '';

const libDir = getLibDirForBinary(ctracePath);
const libEnv = libDir ? `export LD_LIBRARY_PATH=${shellEscapeArg(toWslPath(libDir))}:"$LD_LIBRARY_PATH" && ` : '';

const script = `${wslToolEnvironment()}${libEnv}cp ${shellEscapeArg(wBin)} ${shellEscapeArg(lBin)} && chmod +x ${shellEscapeArg(lBin)} && ${shellEscapeArg(lBin)} --input ${shellEscapeArg(wInput)}${extraArgs} ${validatedParams}; rm -f ${shellEscapeArg(lBin)}`;
const script = `${wslToolEnvironment()}${libEnv}cp ${shellEscapeArg(wBin)} ${shellEscapeArg(lBin)} && chmod +x ${shellEscapeArg(lBin)} && ${shellEscapeArg(lBin)} --input ${shellEscapeArg(wInput)}${extraArgs} ${validatedParams}; status=$?; rm -f ${shellEscapeArg(lBin)}; exit "$status"`;
return await writeWslScript(script, null, tempFiles);
}

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<BuiltCommand> {
Expand Down
118 changes: 63 additions & 55 deletions src/ctrace/DependencyInstaller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -131,30 +132,11 @@ export async function checkDependencies(distro?: string | null): Promise<Depende
IKOS_OK=0
TSCANCODE_OK=0

check_cppcheck_sarif() {
local bin="$1"
[ -n "$bin" ] && [ -x "$bin" ] || return 1
if "$bin" --output-format=sarif /dev/null >/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
Expand Down Expand Up @@ -185,7 +167,8 @@ export async function checkDependencies(distro?: string | null): Promise<Depende
};

const missing: string[] = [];
if (!details.cppcheckHomebrew || !details.cppcheckSarif) {
// Any SARIF-capable Cppcheck will do, wherever it is installed.
if (!details.cppcheckSarif) {
missing.push('cppcheck');
}
if (!details.flawfinder) {
Expand Down Expand Up @@ -236,11 +219,7 @@ elif command -v apk >/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
Expand Down Expand Up @@ -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, {
Expand Down Expand Up @@ -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<string> {
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<void>(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 */ });
}
}
23 changes: 23 additions & 0 deletions src/ctrace/RunOutcome.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
/** ctrace exit codes (--fail-on): 2 = completed with findings, 3 = a tool could not run. */
export const EXIT_FINDINGS = 2;
export const EXIT_INCOMPLETE = 3;

/**
* The tools ctrace names as not run, from lines like
* "[ERROR] Analysis incomplete: tscancode could not run (exit code 3)" and
* "Error: Command not found in PATH: ikos".
*/
export function failedTools(output: string): string[] {
const tools: string[] = [];
const add = (name: string) => {
const tool = name.trim();
if (tool && !tools.includes(tool)) { tools.push(tool); }
};
for (const match of output.matchAll(/Analysis incomplete:\s*(.+?)\s+could not run/gi)) {
match[1].split(/\s*,\s*|\s+and\s+/).forEach(add);
}
for (const match of output.matchAll(/Command not found in PATH:\s*([\w.+-]+)/gi)) {
add(match[1]);
}
return tools;
}
Loading
Loading