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
54 changes: 44 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 @@ -152,7 +169,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 +220,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 +299,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 +332,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 +345,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
78 changes: 78 additions & 0 deletions src/test/wslCommand.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
import * as assert from 'assert';
import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
import { buildWindowsCommandForTesting, 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('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