Skip to content
Merged
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
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ The **Stack Tree** tab shows how much stack your functions use, in a layout made
- **Call tree**: an expandable tree of who calls what, heaviest callees first. A bar behind each value shows its share of the highest peak, and the heaviest call path is highlighted in red. The flame button jumps straight to it.
- **Ranking**: every function sorted by peak stack.
- **Filter** by function or file name: matches stay in place in the tree with the calls leading to them.
- **Jump to source**: clicking a function opens its file at its definition.
- **Details**: selecting a function shows its local and peak stack, its callers and callees (click one to jump to it), and a link to the source.
- **Keyboard**: arrow keys navigate and open rows, `Enter` opens the source (double-click works too).
- Recursive calls end on a row marked `↻` instead of expanding forever.
Expand All @@ -87,7 +88,7 @@ The gear icon opens the analysis settings, grouped by purpose:
- **Operating Systems**:
- **Linux / macOS**: Supported natively.
- **Windows**: Requires **WSL** (Windows Subsystem for Linux, e.g. Ubuntu). If you do not have WSL installed, run `wsl --install` in PowerShell.
- **CoreTrace CLI**: The extension automatically downloads and updates the latest `ctrace` binaries from GitHub Releases upon first launch.
- **CoreTrace CLI**: The extension automatically downloads and updates the latest `ctrace` binaries from GitHub Releases upon first launch. Prebuilt binaries exist for Linux (x64, arm64) and Apple Silicon Macs; on an Intel Mac, build `ctrace` from source and put it on your `PATH`.
- **Analyzers (Optional but Recommended)**: To enable all static analysis engines (`cppcheck`, `flawfinder`, `ikos`, `tscancode`), run the built-in installer via the sidebar or command palette.

---
Expand Down
5 changes: 3 additions & 2 deletions media/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -1061,6 +1061,7 @@
return;
}
selectStackRow(row);
openStackFunction(row.dataset.id, true);
// A click opens but never closes: selecting a parent to read its
// details must not hide its callees.
if (row.getAttribute('aria-expanded') === 'false') { toggleStackRow(key); }
Expand Down Expand Up @@ -1259,10 +1260,10 @@
}
}

function openStackFunction(id) {
function openStackFunction(id, preserveFocus = false) {
const node = stackModel?.nodes.get(id);
if (node?.file) {
vscode.postMessage({ type: 'open-file', path: node.file, line: node.line ? node.line - 1 : 0 });
vscode.postMessage({ type: 'open-file', path: node.file, line: node.line ? node.line - 1 : 0, preserveFocus });
}
}

Expand Down
32 changes: 31 additions & 1 deletion media/style.css
Original file line number Diff line number Diff line change
Expand Up @@ -475,7 +475,8 @@ body {
justify-content: center;
gap: 8px;
flex: 1;
padding: 11px 16px;
min-width: 0;
padding: 11px 12px;
background: linear-gradient(135deg, #b51425, var(--coretrace-red));
color: #fff;
border: 1px solid var(--coretrace-red-bright);
Expand Down Expand Up @@ -518,6 +519,16 @@ body {
flex-shrink: 0;
}

/* The label gives way before the icon: a long "Analysing…" or "Downloading (42%)"
is shortened instead of pushing the spinner out of the button. */
.btn-run span {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
}

.btn-run.running span { white-space: nowrap; }

/* Icon swap via CSS — no JS icon recreation needed */
.btn-run .icon-running { display: none; }
.btn-run .icon-idle { display: block; }
Expand Down Expand Up @@ -1117,6 +1128,9 @@ body {
}

.vuln-sev {
display: inline-flex;
align-items: center;
gap: 3px;
font-size: 0.68em;
font-weight: 600;
padding: 1px 6px;
Expand All @@ -1126,6 +1140,12 @@ body {
letter-spacing: 0.04em;
}

.vuln-sev svg {
width: 10px;
height: 10px;
flex-shrink: 0;
}

.sev-error { background: rgba(227, 38, 54, 0.2); color: #ff6b78; border: 1px solid rgba(255, 70, 86, 0.5); }
.sev-warning { background: rgba(245, 158, 11, 0.18); color: #fbbf24; border: 1px solid rgba(245, 158, 11, 0.45); }
.sev-note { background: rgba(96, 165, 250, 0.14); color: #93c5fd; border: 1px solid rgba(96, 165, 250, 0.35); }
Expand Down Expand Up @@ -1957,6 +1977,16 @@ select:focus-visible {

.stack-details-open:hover { text-decoration: underline; }

/* Beside the two tool menus the run button is too narrow for its running
label: give it its own row on a sidebar of usual width. */
@media (max-width: 380px) {
.run-controls { flex-wrap: wrap; }
.btn-run { flex: 1 1 100%; }
.analysis-mode-row { flex: 1 1 100%; }
.analysis-mode-menu { flex: 1; }
.analysis-mode-toggle { width: 100%; justify-content: center; }
}

@media (max-width: 260px) {
.sidebar { padding: 10px 8px; gap: 8px; }
.run-controls { flex-direction: column; }
Expand Down
3 changes: 2 additions & 1 deletion src/SidebarProvider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,8 @@ export class SidebarProvider implements vscode.WebviewViewProvider, vscode.Dispo
break;
}
const doc = await vscode.workspace.openTextDocument(openUri);
const editor = await vscode.window.showTextDocument(doc);
// The Stack Tree keeps the focus so arrow keys still walk the tree.
const editor = await vscode.window.showTextDocument(doc, { preserveFocus: data.preserveFocus === true });
const safeLine = Number.isFinite(data.line) ? Math.max(0, Math.floor(data.line)) : 0;
const line = Math.min(safeLine, Math.max(0, doc.lineCount - 1));
const range = new vscode.Range(line, 0, line, 0);
Expand Down
109 changes: 84 additions & 25 deletions src/ctrace/BinaryUpdater.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,14 @@ import * as vscode from 'vscode';
import * as fs from 'fs';
import * as path from 'path';
import * as tar from 'tar';
import * as cp from 'child_process';
import { promisify } from 'util';
import { pipeline } from 'stream/promises';
import { Readable, Transform } from 'stream';
import { locateBinary, locateBinaryOnPath } from './BinaryLocator';

const execFileAsync = promisify(cp.execFile);

const REPO_LATEST_RELEASE_URL = 'https://api.github.com/repos/CoreTrace/coretrace/releases/latest';

let updatePromise: Promise<string | null> | null = null;
Expand Down Expand Up @@ -91,7 +95,7 @@ async function doEnsureBinary(context: vscode.ExtensionContext, output: vscode.O
cancellable: false
}, async (progress) => {
output.appendLine(`Downloading CoreTrace release ${latestVersion} from GitHub...`);
await downloadAndExtract(assetInfo.url, binDir, progress);
await downloadAndExtract(assetInfo.url, assetInfo.name, binDir, progress);
await Promise.all([
context.globalState.update('coretrace-version', latestVersion),
context.globalState.update('coretrace-last-failed-update-check', undefined)
Expand Down Expand Up @@ -127,40 +131,84 @@ async function doEnsureBinary(context: vscode.ExtensionContext, output: vscode.O
return await locateBinaryOnPath();
}

function getAssetForPlatform(assets: any[]): { name: string; url: string } | null {
const ARCHIVE_EXTENSIONS: Record<string, string[]> = {
// macOS releases ship a disk image; hdiutil is always available there.
'darwin': ['.dmg', '.tar.gz'],
};
const KNOWN_ARCHS = ['amd64', 'x86_64', 'x64', 'arm64', 'aarch64'];

/**
* Picks the release file for a platform. A file built for another CPU is
* never returned: it would download fine and then fail to run.
*/
export function getAssetForPlatform(
assets: any[],
platform: string = process.platform,
nodeArch: string = process.arch
): { name: string; url: string } | null {
const osMap: Record<string, string[]> = {
'win32': ['windows', 'linux'], // Windows executes via WSL, so fall back to linux if no native windows binary exists
'linux': ['linux'],
'darwin': ['darwin', 'macos']
};
const archMap: Record<string, string> = {
'x64': 'amd64',
'arm64': 'arm64'
const archMap: Record<string, string[]> = {
'x64': ['amd64', 'x86_64', 'x64'],
'arm64': ['arm64', 'aarch64']
};

const osList = osMap[process.platform] || [process.platform];
const arch = archMap[process.arch] || process.arch;


const osList = osMap[platform] || [platform];
const archs = archMap[nodeArch] || [nodeArch];
const extensions = ARCHIVE_EXTENSIONS[platform] || ['.tar.gz'];
const isArchive = (name: string) => extensions.some(ext => name.endsWith(ext));

for (const os of osList) {
// First try exact matches (os + arch + .tar.gz)
// First try exact matches (os + arch + archive)
for (const asset of assets) {
const name = asset.name.toLowerCase();
if (name.includes(os) && name.includes(arch) && name.endsWith('.tar.gz')) {
const name = String(asset.name).toLowerCase();
if (name.includes(os) && archs.some(arch => name.includes(arch)) && isArchive(name)) {
return { name: asset.name, url: asset.browser_download_url };
}
}
// Fallback for older formats (os + .tar.gz)
// Fallback for older formats that do not name a CPU (os + archive)
for (const asset of assets) {
const name = asset.name.toLowerCase();
if (name.includes(os) && name.endsWith('.tar.gz')) {
const name = String(asset.name).toLowerCase();
if (name.includes(os) && isArchive(name) && !KNOWN_ARCHS.some(arch => name.includes(arch))) {
return { name: asset.name, url: asset.browser_download_url };
}
}
}
return null;
}

async function downloadAndExtract(url: string, destDir: string, progress: vscode.Progress<{ message?: string; increment?: number }>): Promise<void> {
/** Folders of the release layout. `libexec` holds helper analyzers on macOS. */
export const INSTALL_FOLDERS = ['bin', 'lib', 'config', 'libexec'];

/**
* Copies the content of a macOS disk image into `targetDir`, without the
* single top-level folder the release wraps everything in (like tar's strip: 1).
*/
async function extractDmg(dmgPath: string, targetDir: string): Promise<void> {
const mountPoint = path.join(path.dirname(dmgPath), 'mnt');
await fs.promises.mkdir(mountPoint, { recursive: true });
await execFileAsync('hdiutil', ['attach', '-nobrowse', '-readonly', '-noautoopen', '-mountpoint', mountPoint, dmgPath]);
try {
const source = await dmgContentRoot(mountPoint);
// ditto keeps symlinks and permissions, which the dylibs rely on.
await execFileAsync('ditto', [source, targetDir]);
} finally {
await execFileAsync('hdiutil', ['detach', mountPoint, '-force']).catch(() => { /* already unmounted */ });
}
}

/** The folder holding bin/, lib/…: the volume itself, or its single top-level folder. */
export async function dmgContentRoot(mountPoint: string): Promise<string> {
const entries = await fs.promises.readdir(mountPoint, { withFileTypes: true });
if (entries.some(entry => entry.isDirectory() && entry.name === 'bin')) { return mountPoint; }
const folders = entries.filter(entry => entry.isDirectory() && !entry.name.startsWith('.'));
return folders.length === 1 ? path.join(mountPoint, folders[0].name) : mountPoint;
}

async function downloadAndExtract(url: string, assetName: string, destDir: string, progress: vscode.Progress<{ message?: string; increment?: number }>): Promise<void> {
const timestamp = Date.now();

const token = process.env.GITHUB_TOKEN || '';
Expand Down Expand Up @@ -212,19 +260,30 @@ async function downloadAndExtract(url: string, destDir: string, progress: vscode
const candidates = ['ctrace', 'coretrace', 'ctrace.exe', 'coretrace.exe'];

try {
const extractStream = tar.x({
C: tmpDir,
strip: 1
});

await pipeline(Readable.fromWeb(response.body as any), progressStream, extractStream);
if (assetName.toLowerCase().endsWith('.dmg')) {
// hdiutil cannot read from a stream: save the image, then mount it.
const dmgDir = path.join(tmpDir, 'dmg');
await fs.promises.mkdir(dmgDir, { recursive: true });
const dmgPath = path.join(dmgDir, 'coretrace.dmg');
await pipeline(Readable.fromWeb(response.body as any), progressStream, fs.createWriteStream(dmgPath));
clearTimeout(timeoutId);
if (progressListener) { progressListener("Extracting..."); }
await extractDmg(dmgPath, tmpDir);
} else {
const extractStream = tar.x({
C: tmpDir,
strip: 1
});

await pipeline(Readable.fromWeb(response.body as any), progressStream, extractStream);
}
clearTimeout(timeoutId);

if (progressListener) { progressListener("Finishing..."); }

// Move the extracted layout (bin, lib, config) into destDir so ctrace can resolve its shared libraries
// via INSTALL_RPATH "$ORIGIN/../lib"
for (const folder of ['bin', 'lib', 'config']) {
// Move the extracted layout (bin, lib, config, libexec) into destDir so ctrace can resolve its shared
// libraries via INSTALL_RPATH "$ORIGIN/../lib" (Linux) or "@loader_path/../lib" (macOS)
for (const folder of INSTALL_FOLDERS) {
const src = path.join(tmpDir, folder);
const dst = path.join(destDir, folder);
if (fs.existsSync(src)) {
Expand Down
12 changes: 9 additions & 3 deletions src/ctrace/StackParser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,12 @@ import { cleanFunctionName } from '../utils/functionCleaner';
/**
* Parses ctrace-stack-analyzer outputs from either JSON report content or plaintext IR mode.
*/
export function parseStackReport(reportContent: string, sourceCode?: string): StackReport | null {
/**
* @param sourceFile Path of the analysed file. Functions defined in
* `sourceCode` that the report gives no file for get it,
* so the Stack Tree can jump to them.
*/
export function parseStackReport(reportContent: string, sourceCode?: string, sourceFile?: string): StackReport | null {
if (!reportContent || !reportContent.trim()) {
return null;
}
Expand Down Expand Up @@ -63,7 +68,7 @@ export function parseStackReport(reportContent: string, sourceCode?: string): St

// Locate function lines in source code if available
if (sourceCode) {
attachSourceLines(functions, sourceCode);
attachSourceLines(functions, sourceCode, sourceFile);
}

// Infer call graph and call chains
Expand Down Expand Up @@ -124,11 +129,12 @@ function parseIrReportText(text: string): StackFunction[] {
/**
* Searches the source file for function definition line numbers.
*/
function attachSourceLines(functions: StackFunction[], sourceCode: string): void {
function attachSourceLines(functions: StackFunction[], sourceCode: string, sourceFile?: string): void {
for (const fn of functions) {
const definition = findFunctionDefinition(sourceCode, fn.name);
if (definition) {
fn.line = sourceCode.slice(0, definition.index).split('\n').length;
if (!fn.file && sourceFile) { fn.file = sourceFile; }
}
}
}
Expand Down
9 changes: 5 additions & 4 deletions src/extension.ts
Original file line number Diff line number Diff line change
Expand Up @@ -130,8 +130,9 @@ export function activate(context: vscode.ExtensionContext) {
if (!p) {
const extPath = context.extensionUri.fsPath;
const globalStorage = context.globalStorageUri.fsPath;
const hint = process.platform === 'darwin'
? '\nCoreTrace publishes no prebuilt macOS binary: build it from https://github.com/CoreTrace/coretrace and put `ctrace` on your PATH.'
// Releases include an Apple Silicon build only.
const hint = process.platform === 'darwin' && process.arch !== 'arm64'
? '\nCoreTrace publishes no prebuilt binary for Intel Macs: build it from https://github.com/CoreTrace/coretrace and put `ctrace` on your PATH.'
: '';
vscode.window.showErrorMessage(
`Ctrace binary could not be found or downloaded. Checked: \n- ${globalStorage}/bin\n- ${extPath}\n- PATH${hint}\nSee the "Ctrace" Output channel for details.`
Expand Down Expand Up @@ -482,7 +483,7 @@ export function activate(context: vscode.ExtensionContext) {
sourceCode = await fs.promises.readFile(fp, 'utf8');
} catch { /* ignore */ }

let stackReport = parseStackReport(reportContent, sourceCode) ?? parseStackReport(stdout, sourceCode);
let stackReport = parseStackReport(reportContent, sourceCode, fp) ?? parseStackReport(stdout, sourceCode, fp);

// 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).
Expand All @@ -504,7 +505,7 @@ export function activate(context: vscode.ExtensionContext) {
try {
const stackRes = await runCommand(stackCmd, extensionPath, token, timeoutMs);
const stackOut = (stackRes.stdout || '') + (stackRes.stderr || '');
stackReport = parseStackReport(stackOut, sourceCode);
stackReport = parseStackReport(stackOut, sourceCode, fp);
} finally {
stackTemp.forEach(tryDelete);
}
Expand Down
Loading
Loading