diff --git a/README.md b/README.md index dd4b06b..ee6ab67 100755 --- a/README.md +++ b/README.md @@ -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. @@ -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. --- diff --git a/media/main.js b/media/main.js index 078b8eb..f522b29 100755 --- a/media/main.js +++ b/media/main.js @@ -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); } @@ -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 }); } } diff --git a/media/style.css b/media/style.css index 42ffba0..a871db8 100755 --- a/media/style.css +++ b/media/style.css @@ -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); @@ -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; } @@ -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; @@ -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); } @@ -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; } diff --git a/src/SidebarProvider.ts b/src/SidebarProvider.ts index f00e2a4..e2db4d0 100755 --- a/src/SidebarProvider.ts +++ b/src/SidebarProvider.ts @@ -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); diff --git a/src/ctrace/BinaryUpdater.ts b/src/ctrace/BinaryUpdater.ts index d504665..ea1e96e 100755 --- a/src/ctrace/BinaryUpdater.ts +++ b/src/ctrace/BinaryUpdater.ts @@ -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 | null = null; @@ -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) @@ -127,32 +131,48 @@ 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 = { + // 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 = { '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 = { - 'x64': 'amd64', - 'arm64': 'arm64' + const archMap: Record = { + '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 }; } } @@ -160,7 +180,35 @@ function getAssetForPlatform(assets: any[]): { name: string; url: string } | nul return null; } -async function downloadAndExtract(url: string, destDir: string, progress: vscode.Progress<{ message?: string; increment?: number }>): Promise { +/** 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 { + 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 { + 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 { const timestamp = Date.now(); const token = process.env.GITHUB_TOKEN || ''; @@ -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)) { diff --git a/src/ctrace/StackParser.ts b/src/ctrace/StackParser.ts index e9b3056..cbfafb3 100644 --- a/src/ctrace/StackParser.ts +++ b/src/ctrace/StackParser.ts @@ -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; } @@ -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 @@ -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; } } } } diff --git a/src/extension.ts b/src/extension.ts index b43eaff..d09e9cb 100755 --- a/src/extension.ts +++ b/src/extension.ts @@ -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.` @@ -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). @@ -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); } diff --git a/src/test/binaryUpdater.test.ts b/src/test/binaryUpdater.test.ts new file mode 100644 index 0000000..0b5de4b --- /dev/null +++ b/src/test/binaryUpdater.test.ts @@ -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 { dmgContentRoot, getAssetForPlatform, INSTALL_FOLDERS } from '../ctrace/BinaryUpdater'; + +// File names of the v0.85.0 release. +const RELEASE = [ + 'coretrace-v0.85.0-linux-amd64.tar.gz', + 'coretrace-v0.85.0-linux-amd64.tar.gz.sha256', + 'coretrace-v0.85.0-linux-arm64.tar.gz', + 'coretrace-v0.85.0-linux-arm64.tar.gz.sha256', + 'coretrace-v0.85.0-macos-arm64.dmg', + 'coretrace-v0.85.0-macos-arm64.dmg.sha256', +].map(name => ({ name, browser_download_url: `https://example.test/${name}` })); + +const pick = (platform: string, arch: string, assets = RELEASE) => getAssetForPlatform(assets, platform, arch)?.name ?? null; + +suite('BinaryUpdater release asset Test Suite', () => { + test('Apple Silicon Macs get the disk image', () => { + assert.strictEqual(pick('darwin', 'arm64'), 'coretrace-v0.85.0-macos-arm64.dmg'); + }); + + test('Intel Macs get nothing rather than a binary they cannot run', () => { + assert.strictEqual(pick('darwin', 'x64'), null); + }); + + test('Linux gets the tarball of its CPU', () => { + assert.strictEqual(pick('linux', 'x64'), 'coretrace-v0.85.0-linux-amd64.tar.gz'); + assert.strictEqual(pick('linux', 'arm64'), 'coretrace-v0.85.0-linux-arm64.tar.gz'); + }); + + test('Windows falls back to the Linux tarball for WSL', () => { + assert.strictEqual(pick('win32', 'x64'), 'coretrace-v0.85.0-linux-amd64.tar.gz'); + }); + + test('checksum files and disk images are never picked on Linux', () => { + const assets = [{ name: 'coretrace-linux-amd64.dmg', browser_download_url: 'u' }, { name: 'coretrace-linux-amd64.tar.gz.sha256', browser_download_url: 'u' }]; + assert.strictEqual(pick('linux', 'x64', assets), null); + }); + + test('a macOS tarball is still accepted', () => { + const assets = [{ name: 'coretrace-darwin-arm64.tar.gz', browser_download_url: 'u' }]; + assert.strictEqual(pick('darwin', 'arm64', assets), 'coretrace-darwin-arm64.tar.gz'); + }); + + test('older releases that name no CPU are still found', () => { + const assets = [{ name: 'coretrace-linux.tar.gz', browser_download_url: 'u' }]; + assert.strictEqual(pick('linux', 'x64', assets), 'coretrace-linux.tar.gz'); + }); + + test('libexec is installed with the other folders', () => { + assert.deepStrictEqual(INSTALL_FOLDERS, ['bin', 'lib', 'config', 'libexec']); + }); + + test('the single top-level folder of a disk image is skipped', async () => { + const mount = fs.mkdtempSync(path.join(os.tmpdir(), 'ctrace-dmg-')); + try { + fs.mkdirSync(path.join(mount, 'coretrace-v0.85.0-macos-arm64', 'bin'), { recursive: true }); + fs.mkdirSync(path.join(mount, '.Trashes')); + fs.writeFileSync(path.join(mount, '.DS_Store'), ''); + assert.strictEqual(await dmgContentRoot(mount), path.join(mount, 'coretrace-v0.85.0-macos-arm64')); + } finally { + fs.rmSync(mount, { recursive: true, force: true }); + } + }); + + test('a disk image with bin/ at its root is used as is', async () => { + const mount = fs.mkdtempSync(path.join(os.tmpdir(), 'ctrace-dmg-')); + try { + fs.mkdirSync(path.join(mount, 'bin')); + fs.mkdirSync(path.join(mount, 'lib')); + assert.strictEqual(await dmgContentRoot(mount), mount); + } finally { + fs.rmSync(mount, { recursive: true, force: true }); + } + }); +}); diff --git a/src/test/stackParser.test.ts b/src/test/stackParser.test.ts index bb2c4c5..6b87c67 100644 --- a/src/test/stackParser.test.ts +++ b/src/test/stackParser.test.ts @@ -2,6 +2,19 @@ import * as assert from 'assert'; import { parseStackReport, mergeStackReports } from '../ctrace/StackParser'; suite('StackParser Test Suite', () => { + test('functions defined in the analysed file get its path, so the Stack Tree can jump to them', () => { + const report = [ + 'Function: helper ', '\tlocal stack: 16 bytes', '\tmax stack (including callees): 16 bytes', '', + 'Function: from_header ', '\tlocal stack: 8 bytes', '\tmax stack (including callees): 8 bytes', '', + ].join('\n'); + const source = '#include "h.h"\n\nint helper(int n) {\n return from_header(n);\n}\n'; + const parsed = parseStackReport(report, source, '/w/src/app.c'); + assert.deepStrictEqual(parsed?.functions.map(fn => [fn.name, fn.file, fn.line]), [ + ['helper', '/w/src/app.c', 3], + ['from_header', undefined, undefined], + ]); + }); + test('flags only the recursive functions in a plaintext report', () => { const report = [ 'Function: loop ', '\tlocal stack: 16 bytes', '\tmax stack (including callees): 32 bytes',