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
81 changes: 71 additions & 10 deletions src/ctrace/CommandBuilder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,23 @@ function shellEscapeArg(arg: string): string {
return "'" + arg.replace(/'/g, "'\\''") + "'";
}

type WslExec = (args: string[], options: { encoding?: BufferEncoding; timeout: number }) => string | Buffer;

let wslExec: WslExec = (args, options) => cp.execFileSync('wsl', args, options);

/**
* Replaces the calls to wsl.exe, so the Windows command builders can be
* tested on any platform.
*/
export function setWslExecForTesting(fake: WslExec | null): void {
wslExec = fake ?? ((args, options) => cp.execFileSync('wsl', args, options));
}

/** The Windows builder, for tests on other platforms (with setMockWslAvailableForTesting). */
export function buildWindowsCommandForTesting(ctracePath: string, inputFilePath: string, params: string): Promise<BuiltCommand> {
return buildWindowsCommand(ctracePath, inputFilePath, params);
}

/**
* Converts a Windows-style path to its WSL POSIX equivalent using `wslpath`.
* Falls back to a simple `/mnt/<drive>/` prefix substitution if the command fails.
Expand All @@ -63,7 +80,7 @@ function toWslPath(winPath: string, distroName: string | null = null): string {
...(distroName ? ['-d', distroName] : []),
'wslpath', '-u', normalized,
];
return cp.execFileSync('wsl', args, { timeout: 5000 }).toString().trim();
return wslExec(args, { timeout: 5000 }).toString().trim();
} catch {
return normalized.replace(/^([a-zA-Z]):/, (_, d) => `/mnt/${d.toLowerCase()}`);
}
Expand Down Expand Up @@ -129,6 +146,33 @@ function parseWslUNC(p: string): { distro: string; internalPath: string } | null
return null;
}

/**
* The WSL distribution a scan of these paths runs in: the one named by a
* WSL path (\\wsl$\Debian\...) when it is not the default one, else null
* for the default distribution. Same rule as trySmartDistroExecution(), so
* the analyzers are checked and installed where they will run.
*/
export function executionDistro(...paths: (string | undefined)[]): string | null {
const detected = paths.map(p => p ? parseWslUNC(p) : null).find(Boolean)?.distro;
if (!detected) { return null; }
try {
const clean = (s: string) => s.replace(/[\u0000-\u001F\u007F-\u009F\uFEFF\uFFFD]/g, '').trim();
const lines = wslExec(['-l', '-v'], { encoding: 'utf16le', timeout: 5000 }).toString().split(/[\r\n]+/).filter(l => l.trim());
let defaultDistro = '';
let matched = '';
for (const line of lines) {
if (line.includes('NAME') && line.includes('STATE')) { continue; }
const name = clean(line.replace('*', '').trim().split(/\s+/)[0] ?? '');
if (line.trim().startsWith('*')) { defaultDistro = name; }
if (name.toLowerCase() === detected.toLowerCase()) { matched = name; }
}
if (!matched || matched === defaultDistro) { return null; }
return resolveDistroName(matched);
} catch {
return null;
}
}

let cachedWslAvailable: { result: boolean; timestamp: number } | null = null;
let mockWslAvailable: boolean | null = null;

Expand All @@ -152,7 +196,7 @@ export function isWslAvailable(): boolean {
return cachedWslAvailable.result;
}
try {
const stdout = cp.execFileSync('wsl', ['-l', '-q'], { encoding: 'utf16le', timeout: 5000 });
const stdout = wslExec(['-l', '-q'], { encoding: 'utf16le', timeout: 5000 }).toString();
const clean = stdout.replace(/[\u0000-\u001F\u007F-\u009F\uFEFF\uFFFD]/g, '').trim();
const available = Boolean(clean) && !/no installed distributions|no distribution/i.test(clean);
cachedWslAvailable = { result: available, timestamp: now };
Expand Down Expand Up @@ -203,7 +247,7 @@ function trySmartDistroExecution(
const clean = (s: string) => s.replace(/[\u0000-\u001F\u007F-\u009F\uFEFF\uFFFD]/g, '').trim();
// execFileSync avoids spawning a shell (cmd.exe); encoding:'utf16le' is
// supported by Node's execFileSync just as it is by execSync.
const stdout = cp.execFileSync('wsl', ['-l', '-v'], { encoding: 'utf16le', timeout: 5000 });
const stdout = wslExec(['-l', '-v'], { encoding: 'utf16le', timeout: 5000 }).toString();
const lines = stdout.split(/[\r\n]+/).filter(l => l.trim());

let defaultDistro = '';
Expand Down Expand Up @@ -282,7 +326,7 @@ function resolveDistroName(distro: string): string | null {
const safeDistro = distro.replace(/["'`\\]/g, '');
if (!safeDistro) { return null; }
try {
cp.execFileSync('wsl', ['-d', safeDistro, 'true'], { timeout: 5000 });
wslExec(['-d', safeDistro, 'true'], { timeout: 5000 });
return safeDistro;
} catch {
// fall through
Expand Down Expand Up @@ -315,12 +359,7 @@ async function buildFallbackCommand(
const tempBin = path.join(os.tmpdir(), `ctrace-bin-${stamp}`);
const lBin = `/tmp/ctrace-${stamp}`;

await fs.promises.copyFile(ctracePath, tempBin);
tempFiles.push(tempBin);

const wBin = toWslPath(tempBin);
const wInput = toWslPath(inputFilePath);

// Validated before the CLI is copied: a rejected argument leaves nothing behind.
const validatedParamsTokens = parseAndValidateParams(params).map(token => {
const eqIndex = token.indexOf('=');
if (eqIndex > 0) {
Expand All @@ -333,6 +372,28 @@ 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);
Expand Down
21 changes: 16 additions & 5 deletions src/extension.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import * as path from 'path';

import { SidebarProvider } from './SidebarProvider';
import { locateBinary } from './ctrace/BinaryLocator';
import { buildCommand, isWslAvailable } from './ctrace/CommandBuilder';
import { buildCommand, executionDistro, isWslAvailable } from './ctrace/CommandBuilder';
import { runCommand, DEFAULT_TIMEOUT_MS } from './ctrace/AnalysisRunner';
import { parseSarifOutput } from './ctrace/SarifParser';
import { updateDiagnostics, clearDiagnostics, getFindingForDiagnostic, FindingRef } from './ctrace/DiagnosticsManager';
Expand Down Expand Up @@ -147,7 +147,7 @@ export function activate(context: vscode.ExtensionContext) {

// ── Command: ctrace.installDependencies ──────────────────────────────────
context.subscriptions.push(
vscode.commands.registerCommand('ctrace.installDependencies', async () => {
vscode.commands.registerCommand('ctrace.installDependencies', async (arg?: { distro?: string | null }) => {
if (process.platform === 'win32' && !isWslAvailable()) {
output.appendLine('[ctrace] Windows Subsystem for Linux (WSL) is required to install dependencies on Windows.');
promptWslInstallation();
Expand All @@ -161,7 +161,14 @@ export function activate(context: vscode.ExtensionContext) {
cancellable: false,
},
async (progress) => {
await installDependencies(output, progress);
// Install where the scan runs: the distribution a preflight
// asked for, else the one of the active file (WSL paths).
const activeFile = vscode.window.activeTextEditor?.document.uri.fsPath;
const distro = arg && 'distro' in arg
? arg.distro ?? null
: process.platform === 'win32' ? executionDistro(activeFile) : null;
if (distro) { output.appendLine(`[ctrace] Installing the analyzers in the WSL distribution ${distro}.`); }
await installDependencies(output, progress, distro);
}
);
})
Expand Down Expand Up @@ -259,7 +266,11 @@ export function activate(context: vscode.ExtensionContext) {
const requestedStaticTools: string[] = (uiState.staticTools ?? ['cppcheck', 'flawfinder', 'ikos', 'tscancode', 'ctrace_stack_analyzer'])
.filter(tool => tool !== 'coretrace-python-analyzer');
if (hasCFiles && uiState.staticEnabled !== false && requestedStaticTools.length > 0) {
const depStatus = await checkDependencies();
// The analyzers are checked in the distribution that will run the scan.
const toolsDistro = process.platform === 'win32'
? executionDistro(scanWorkspace ? workspaceRoot : filesToAnalyze[0])
: null;
const depStatus = await checkDependencies(toolsDistro);
const missingRequested = requestedStaticTools.filter((t) => depStatus.missing.includes(t));
if (missingRequested.length > 0) {
const action = await vscode.window.showWarningMessage(
Expand All @@ -269,7 +280,7 @@ export function activate(context: vscode.ExtensionContext) {
);
if (action === 'Install Analyzers') {
sidebarProvider.postMessage({ type: 'analysis-done' });
vscode.commands.executeCommand('ctrace.installDependencies');
vscode.commands.executeCommand('ctrace.installDependencies', { distro: toolsDistro });
return;
}
}
Expand Down
94 changes: 94 additions & 0 deletions src/test/wslCommand.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
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 "/);
});

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