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
8 changes: 4 additions & 4 deletions media/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -701,7 +701,7 @@
case 'focus-stack-tab':
switchResultTab('stack');
if (msg.functionName && stackModel) {
const id = stackTreeLib.resolveName(stackModel, msg.functionName);
const id = stackTreeLib.resolveName(stackModel, msg.functionName, msg.file);
if (id) { revealStackFunction(id); }
}
break;
Expand Down Expand Up @@ -1008,7 +1008,7 @@

const name = document.createElement('span');
name.className = 'stack-row-name';
appendHighlighted(name, node.name, query);
appendHighlighted(name, stackTreeLib.displayName(stackModel, row.id), query);

const badges = document.createElement('span');
badges.className = 'stack-row-badges';
Expand Down Expand Up @@ -1218,8 +1218,8 @@
const link = document.createElement('button');
link.type = 'button';
link.className = 'stack-link';
link.textContent = id;
link.title = `Show ${id} in the tree`;
link.textContent = stackTreeLib.displayName(stackModel, id);
link.title = `Show ${link.textContent} in the tree`;
link.addEventListener('click', () => revealStackFunction(id));
row.appendChild(link);
});
Expand Down
39 changes: 31 additions & 8 deletions media/stackTree.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,9 @@
const nodes = new Map();
for (const node of report?.callGraph?.nodes ?? []) { nodes.set(node.id, { ...node }); }
for (const fn of report?.functions ?? []) {
nodes.set(fn.name, { ...(nodes.get(fn.name) ?? {}), ...fn, id: fn.name, name: fn.name });
// A merged report gives same-named functions of different files their own id.
const id = fn.id ?? fn.name;
nodes.set(id, { ...(nodes.get(id) ?? {}), ...fn, id, name: fn.name });
}

const children = new Map();
Expand Down Expand Up @@ -76,7 +78,11 @@

const standalone = [...nodes.keys()].filter(id => !linked.has(id)).sort(compare);
const peak = Math.max(1, report?.peakStack || 0, ...[...nodes.values()].map(node => node.maxStack || 0));
const model = { nodes, children, parents, roots, standalone, peak, callCount, hotKeys: new Set(), hotPath: [] };
const nameCounts = new Map();
nodes.forEach(node => nameCounts.set(node.name, (nameCounts.get(node.name) ?? 0) + 1));
// Names shared by several functions: the UI adds their file to tell them apart.
const duplicateNames = new Set([...nameCounts].filter(([, count]) => count > 1).map(([name]) => name));
const model = { nodes, children, parents, roots, standalone, peak, callCount, duplicateNames, hotKeys: new Set(), hotPath: [] };
model.hotPath = computeHotPath(model);
// Prefixes of the path are hot too: they are the rows leading to it.
model.hotPath.forEach((_, index) => model.hotKeys.add(keyOf(topLevelPrefix(model, model.hotPath[0]), model.hotPath.slice(0, index + 1))));
Expand Down Expand Up @@ -256,13 +262,30 @@
return null;
}

/** CodeLens passes unqualified names: `run` must find `Worker::run`. */
function resolveName(model, name) {
/**
* CodeLens passes unqualified names: `run` must find `Worker::run`. With
* `file`, the definition in that file wins over same-named ones elsewhere.
*/
function resolveName(model, name, file) {
if (!name) { return null; }
if (model.nodes.has(name)) { return name; }
const suffix = `::${name}`;
const match = [...model.nodes.keys()].filter(id => id.endsWith(suffix)).sort(byPeakThenName(model.nodes));
return match[0] ?? null;
const all = [...model.nodes.values()];
const exact = all.filter(node => node.name === name);
const candidates = (exact.length > 0 ? exact : all.filter(node => node.name.endsWith(suffix)))
.sort((a, b) => byPeakThenName(model.nodes)(a.id, b.id));
if (file) {
const inFile = candidates.find(node => node.file === file);
if (inFile) { return inFile.id; }
}
return candidates[0]?.id ?? null;
}

/** Name to show for a function: with its file when another function shares the name. */
function displayName(model, id) {
const node = model.nodes.get(id);
if (!node) { return id; }
if (!model.duplicateNames.has(node.name) || !node.file) { return node.name; }
return `${node.name} · ${String(node.file).split(/[\\/]/).pop()}`;
}

/** Key of the row a nested row hangs from, or null at the top level. */
Expand All @@ -271,5 +294,5 @@
return index < 0 ? null : key.slice(0, index);
}

return { STANDALONE_KEY, createModel, defaultExpanded, allExpanded, flattenTree, rankedRows, pathTo, resolveName, parentKey };
return { STANDALONE_KEY, createModel, defaultExpanded, allExpanded, flattenTree, rankedRows, pathTo, resolveName, displayName, parentKey };
}));
4 changes: 2 additions & 2 deletions src/codelens/CtraceCodeLensProvider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ function collectFunctionLenses(
));

// 2. Stack Footprint & Recursion Action
const stackInfo = StackManager.instance.getFunction(cleanName);
const stackInfo = StackManager.instance.getFunction(cleanName, documentUri.fsPath);
if (stackInfo) {
const recursionText = (stackInfo.isRecursive || stackInfo.hasInfiniteSelfRecursion)
? '⚠️ Recursion: Cycle detected'
Expand All @@ -68,7 +68,7 @@ function collectFunctionLenses(
{
title: footprintTitle,
command: 'ctrace.focusStackFunction',
arguments: [cleanName],
arguments: [cleanName, documentUri.fsPath],
tooltip: `Peak stack usage: ${stackInfo.maxStack} bytes. Click to view in Stack Visualizer.`,
}
));
Expand Down
28 changes: 23 additions & 5 deletions src/ctrace/StackManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@ import type { StackFunction, StackReport } from '../types/stack';
export class StackManager {
private static _instance: StackManager;
private _latestReport: StackReport | null = null;
private _functionMap = new Map<string, StackFunction>();
// name → every definition with that name: two files can each define one.
private _functionMap = new Map<string, StackFunction[]>();
private _onDidUpdateStackData = new vscode.EventEmitter<void>();

public readonly onDidUpdateStackData = this._onDidUpdateStackData.event;
Expand All @@ -20,20 +21,37 @@ export class StackManager {
this._latestReport = report;
this._functionMap.clear();

const index = (name: string, fn: StackFunction) => {
const list = this._functionMap.get(name) ?? [];
list.push(fn);
this._functionMap.set(name, list);
};
for (const fn of report.functions) {
this._functionMap.set(fn.name, fn);
index(fn.name, fn);
// Also store without namespace or qualifiers if any
const simpleName = fn.name.split('::').pop() ?? fn.name;
if (simpleName !== fn.name) {
this._functionMap.set(simpleName, fn);
index(simpleName, fn);
}
}

this._onDidUpdateStackData.fire();
}

public getFunction(name: string): StackFunction | undefined {
return this._functionMap.get(name);
/**
* The definition of `name` in `file`. Without a match in that file, only
* a definition whose file is unknown is returned: another file's function
* of the same name is a different function.
*/
public getFunction(name: string, file?: string): StackFunction | undefined {
const candidates = this._functionMap.get(name) ?? [];
if (file) {
const inFile = candidates.find(fn => fn.file === file);
if (inFile) { return inFile; }
const unknownFile = candidates.filter(fn => !fn.file);
return unknownFile.length === 1 ? unknownFile[0] : undefined;
}
return candidates.length === 1 ? candidates[0] : undefined;
}

public getLatestReport(): StackReport | null {
Expand Down
61 changes: 46 additions & 15 deletions src/ctrace/StackParser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -152,11 +152,13 @@ function buildCallGraph(
functions: StackFunction[],
sourceCode?: string
): { nodes: CallGraphNode[]; edges: CallGraphEdge[]; chains: CallChainStep[][] } {
// Callees are ids: names in a single-file report, see StackFunction.id.
const idOf = (f: StackFunction) => f.id ?? f.name;
const fnMap = new Map<string, StackFunction>();
functions.forEach(f => fnMap.set(f.name, f));
functions.forEach(f => fnMap.set(idOf(f), f));

const nodes: CallGraphNode[] = functions.map(f => ({
id: f.name,
id: idOf(f),
name: f.name,
file: f.file,
line: f.line,
Expand Down Expand Up @@ -192,7 +194,7 @@ function buildCallGraph(
// Prefer call relationships supplied by the analyzer when available.
for (const fn of functions) {
for (const callee of fn.callees ?? []) {
if (fnMap.has(callee)) { addEdge(fn.name, callee, fn.name === callee); }
if (fnMap.has(callee)) { addEdge(idOf(fn), callee, idOf(fn) === callee); }
}
}

Expand Down Expand Up @@ -236,7 +238,7 @@ function buildCallGraph(
const isCycle = visited.has(fnName);

currentPath.push({
name: fnName,
name: fn?.name ?? fnName,
localStack: local,
cumulativeStack: newCumulative,
isRecursive: fn?.isRecursive || isCycle,
Expand All @@ -263,7 +265,7 @@ function buildCallGraph(
currentPath.pop();
}

traverse(root.name, 0);
traverse(idOf(root), 0);
}

// If no chains were formed (e.g. disjoint functions), make a 1-step chain per function
Expand Down Expand Up @@ -306,7 +308,13 @@ export function mergeStackReports(reports: StackReport[]): StackReport | null {
if (!reports || reports.length === 0) { return null; }
if (reports.length === 1) { return reports[0]; }

const functionMap = new Map<string, StackFunction>();
// A function is identified by its name and the file defining it: two
// translation units can each have their own `static int helper()`.
// Functions without a known file (e.g. inline ones from a header) are
// merged by name, as the same definition seen from several files.
const identityOf = (fn: StackFunction) => fn.file ? `${fn.name}\u0000${fn.file}` : fn.name;
const merged = new Map<string, StackFunction>();
const identitiesByName = new Map<string, Set<string>>();
let peakStack = 0;
let recursiveCount = 0;
let stackLimit = 8388608;
Expand All @@ -322,9 +330,12 @@ export function mergeStackReports(reports: StackReport[]): StackReport | null {
recursiveCount += report.recursiveCount || 0;

for (const fn of report.functions || []) {
const existing = functionMap.get(fn.name);
const identity = identityOf(fn);
if (!identitiesByName.has(fn.name)) { identitiesByName.set(fn.name, new Set()); }
identitiesByName.get(fn.name)!.add(identity);
const existing = merged.get(identity);
if (!existing) {
functionMap.set(fn.name, { ...fn });
merged.set(identity, { ...fn, callees: [], callers: [] });
} else {
existing.localStack = Math.max(existing.localStack, fn.localStack);
existing.maxStack = Math.max(existing.maxStack, fn.maxStack);
Expand All @@ -334,17 +345,37 @@ export function mergeStackReports(reports: StackReport[]): StackReport | null {
existing.exceedsLimit = existing.exceedsLimit || fn.exceedsLimit;
if (!existing.file && fn.file) { existing.file = fn.file; }
if (!existing.line && fn.line) { existing.line = fn.line; }
if (fn.callees?.length) {
existing.callees = Array.from(new Set([...(existing.callees || []), ...fn.callees]));
}
if (fn.callers?.length) {
existing.callers = Array.from(new Set([...(existing.callers || []), ...fn.callers]));
}
}
}
}

const functions = Array.from(functionMap.values());
// Ids stay plain names unless a name has several definitions.
for (const fn of merged.values()) {
fn.id = identitiesByName.get(fn.name)!.size > 1 && fn.file ? `${fn.name}@${fn.file}` : fn.name;
}

// Calls are resolved within the report that saw them: a call to `helper`
// from a.c goes to a.c's helper. A name defined elsewhere only once is an
// external function; a name defined in several other files is ambiguous
// and left unlinked rather than guessed.
for (const report of reports) {
if (!report) { continue; }
const local = new Map((report.functions || []).map(fn => [fn.name, merged.get(identityOf(fn))!]));
for (const fn of report.functions || []) {
const caller = merged.get(identityOf(fn))!;
for (const calleeName of fn.callees ?? []) {
const callee = local.get(calleeName) ?? uniqueByName(calleeName);
if (callee && !caller.callees!.includes(callee.id!)) { caller.callees!.push(callee.id!); }
}
}
}

function uniqueByName(name: string): StackFunction | undefined {
const identities = identitiesByName.get(name);
return identities && identities.size === 1 ? merged.get([...identities][0]) : undefined;
}

const functions = Array.from(merged.values());
if (functions.length === 0) { return null; }

const { nodes, edges, chains } = buildCallGraph(functions);
Expand Down
3 changes: 2 additions & 1 deletion src/extension.ts
Original file line number Diff line number Diff line change
Expand Up @@ -762,11 +762,12 @@ export function activate(context: vscode.ExtensionContext) {
);

context.subscriptions.push(
vscode.commands.registerCommand('ctrace.focusStackFunction', async (functionName?: string) => {
vscode.commands.registerCommand('ctrace.focusStackFunction', async (functionName?: string, file?: string) => {
await vscode.commands.executeCommand('workbench.view.extension.ctrace-sidebar-view');
sidebarProvider.postMessage({
type: 'focus-stack-tab',
functionName,
file: typeof file === 'string' ? file : undefined,
});
})
);
Expand Down
26 changes: 26 additions & 0 deletions src/test/stackManager.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import * as assert from 'assert';
import { StackManager } from '../ctrace/StackManager';

suite('StackManager Test Suite', () => {
teardown(() => StackManager.instance.clear());

const fn = (name: string, file: string | undefined, maxStack: number) =>
({ name, file, localStack: maxStack, maxStack, isRecursive: false });

test('CodeLens gets the definition of the file it is shown in', () => {
StackManager.instance.updateStackData({
peakStack: 32, recursiveCount: 0,
functions: [fn('helper', '/w/a.c', 16), fn('helper', '/w/b.c', 32)],
});
assert.strictEqual(StackManager.instance.getFunction('helper', '/w/a.c')?.maxStack, 16);
assert.strictEqual(StackManager.instance.getFunction('helper', '/w/b.c')?.maxStack, 32);
// c.c has no helper of its own: another file's is not shown there.
assert.strictEqual(StackManager.instance.getFunction('helper', '/w/c.c'), undefined);
});

test('a definition whose file is unknown is still found', () => {
StackManager.instance.updateStackData({ peakStack: 8, recursiveCount: 0, functions: [fn('inline_fn', undefined, 8)] });
assert.strictEqual(StackManager.instance.getFunction('inline_fn', '/w/a.h')?.maxStack, 8);
assert.strictEqual(StackManager.instance.getFunction('inline_fn')?.maxStack, 8);
});
});
36 changes: 36 additions & 0 deletions src/test/stackParser.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,42 @@ import * as assert from 'assert';
import { parseStackReport, mergeStackReports } from '../ctrace/StackParser';

suite('StackParser Test Suite', () => {
test('same-named functions of two files stay distinct after merging', () => {
const report = (fns: [string, number][]) => fns
.map(([name, peak]) => `Function: ${name} \n\tlocal stack: ${peak} bytes\n\tmax stack (including callees): ${peak} bytes\n`)
.join('\n');
// Each file has its own static helper, called by a function of that file.
const aSource = 'static int helper(int n) { return n; }\nint main(void) { return helper(1); }\n';
const bSource = 'static int helper(int n) { return n * 2; }\nint run(void) { return helper(2); }\n';
const a = parseStackReport(report([['helper', 16], ['main', 48]]), aSource, '/w/a.c')!;
const b = parseStackReport(report([['helper', 32], ['run', 64]]), bSource, '/w/b.c')!;

const merged = mergeStackReports([a, b])!;
const helpers = merged.functions.filter(fn => fn.name === 'helper');
assert.strictEqual(helpers.length, 2, 'one row per definition');
const inA = helpers.find(fn => fn.file === '/w/a.c')!;
const inB = helpers.find(fn => fn.file === '/w/b.c')!;
assert.strictEqual(inA.maxStack, 16);
assert.strictEqual(inB.maxStack, 32);
assert.strictEqual(inA.line, 1);
assert.strictEqual(inB.line, 1);
assert.notStrictEqual(inA.id, inB.id);

// Each call reaches the helper of its own file.
const edges = merged.callGraph!.edges.map(edge => `${edge.from} -> ${edge.to}`).sort();
assert.deepStrictEqual(edges, [`main -> ${inA.id}`, `run -> ${inB.id}`].sort());
assert.deepStrictEqual(inA.callers, ['main']);
assert.deepStrictEqual(inB.callers, ['run']);
// Names defined once keep their name as id.
assert.ok(merged.functions.some(fn => fn.id === 'main'));
});

test('a function seen by several files without a known file is merged by name', () => {
const report = 'Function: inline_header_fn \n\tlocal stack: 8 bytes\n\tmax stack (including callees): 8 bytes\n';
const merged = mergeStackReports([parseStackReport(report)!, parseStackReport(report)!])!;
assert.strictEqual(merged.functions.filter(fn => fn.name === 'inline_header_fn').length, 1);
});

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', '',
Expand Down
18 changes: 18 additions & 0 deletions src/test/stackTree.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,24 @@ suite('Stack call tree Test Suite', () => {
assert.strictEqual(lib.resolveName(model, 'missing'), null);
});

test('same-named functions of different files are told apart', () => {
const model = lib.createModel({
peakStack: 64,
functions: [
{ id: 'helper@/w/a.c', name: 'helper', file: '/w/a.c', line: 1, localStack: 16, maxStack: 16, isRecursive: false },
{ id: 'helper@/w/b.c', name: 'helper', file: '/w/b.c', line: 1, localStack: 32, maxStack: 32, isRecursive: false },
{ id: 'main', name: 'main', file: '/w/a.c', localStack: 8, maxStack: 24, isRecursive: false },
],
callGraph: { nodes: [], chains: [], edges: [{ from: 'main', to: 'helper@/w/a.c' }] },
});
assert.strictEqual(model.nodes.size, 3);
assert.strictEqual(lib.resolveName(model, 'helper', '/w/a.c'), 'helper@/w/a.c');
assert.strictEqual(lib.resolveName(model, 'helper', '/w/b.c'), 'helper@/w/b.c');
assert.strictEqual(lib.displayName(model, 'helper@/w/b.c'), 'helper · b.c');
assert.strictEqual(lib.displayName(model, 'main'), 'main');
assert.deepStrictEqual(model.children.get('main'), ['helper@/w/a.c']);
});

test('an empty report does not throw', () => {
const model = lib.createModel({ functions: [], peakStack: 0 });
assert.deepStrictEqual(lib.flattenTree(model, {}).rows, []);
Expand Down
Loading
Loading