-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathextension.js
More file actions
228 lines (191 loc) · 7.7 KB
/
extension.js
File metadata and controls
228 lines (191 loc) · 7.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
const vscode = require('vscode');
const fs = require('fs');
const path = require('path');
const yaml = require('js-yaml');
const CIFUZZ_BUILD = '.cifuzz/build';
const FINDINGS_DIR = '.cifuzz-findings';
function getWorkspaceRoot() {
const ws = vscode.workspace.workspaceFolders;
if (!ws || ws.length === 0) {
vscode.window.showErrorMessage('No workspace open');
return null;
}
return ws[0].uri.fsPath;
}
/**
* Scans the findings directory and returns structured data for each finding.
* @param {string} root The workspace root path.
* @returns {Array<Object>} An array of finding objects.
*/
function getAllFindings(root) {
const findingsRoot = path.join(root, FINDINGS_DIR);
if (!fs.existsSync(findingsRoot)) {
vscode.window.showErrorMessage(`Directory ${FINDINGS_DIR} not found at ${findingsRoot}`);
return [];
}
const entries = fs.readdirSync(findingsRoot, { withFileTypes: true })
.filter(e => e.isDirectory())
.map(e => path.join(findingsRoot, e.name));
const findings = [];
for (const folder of entries) {
const findJsonPath = path.join(folder, 'finding.json');
if (fs.existsSync(findJsonPath)) {
try {
const data = JSON.parse(fs.readFileSync(findJsonPath, 'utf8'));
findings.push(data);
} catch (e) {
vscode.window.showWarningMessage(`Invalid JSON in ${findJsonPath}`);
}
}
}
return findings;
}
async function generateProfiles() {
const root = getWorkspaceRoot();
if (!root) { return; }
const cifuzzFiles = await vscode.workspace.findFiles('**/cifuzz.yaml', undefined, 1);
if (cifuzzFiles.length === 0) {
vscode.window.showErrorMessage('Cannot find cifuzz.yaml in workspace');
return;
}
const cifuzzPath = cifuzzFiles[0].fsPath;
let cfg;
try {
cfg = yaml.load(fs.readFileSync(cifuzzPath, 'utf8'));
} catch (e) {
vscode.window.showErrorMessage('Error loading cifuzz.yaml: ' + e.message);
return;
}
const engine = cfg.engine || 'libfuzzer-clang';
const sanitizers = cfg.sanitizers || ['address+undefined'];
const engineDir = path.join(root, CIFUZZ_BUILD, engine);
const searchPrefix = sanitizers.join('+');
const launch = {
version: '0.2.0',
configurations: []
};
const seenTests = new Set();
const allFindingsData = getAllFindings(root);
for (const data of allFindingsData) {
const test = data.fuzz_test;
const id = data.name;
const candidates = [];
function walk(dir) {
if (!fs.existsSync(dir)) return;
for (const fn of fs.readdirSync(dir)) {
const fp = path.join(dir, fn);
if (fs.statSync(fp).isDirectory()) { walk(fp); }
else if (fn === test) { candidates.push(fp); }
}
}
// Binary can be in different path, based on the engine args (eg address+undefined-D4JOLPY3)
// As we don't know which one cifuzz will use, we just take the latest binary built
if (fs.existsSync(engineDir)) {
const matchingDirs = fs.readdirSync(engineDir).filter(entry => {
const fullPath = path.join(engineDir, entry);
return fs.statSync(fullPath).isDirectory() && entry.startsWith(searchPrefix);
});
for (const dir of matchingDirs) {
walk(path.join(engineDir, dir));
}
}
console.warn(candidates);
if (candidates.length === 0) {
console.warn("Cannot find binary for ", test);
continue;
}
// Sort by creation date
candidates.sort((a, b) => fs.statSync(b).mtimeMs - fs.statSync(a).mtimeMs);
const bin = candidates[0];
console.warn(bin)
const crashingInputPath = path.join(root, FINDINGS_DIR, id, 'crashing-input');
const makeEntry = (suffix, arg) => ({
name: `${test} | ${suffix}`,
type: 'cppdbg',
request: 'launch',
program: bin,
cwd: '${workspaceFolder}',
args: arg ? [arg] : [],
stopAtEntry: false,
environment: [{ name: 'ASAN_SYMBOLIZER_PATH', value: '/usr/bin/llvm-symbolizer' }, { name: 'ASAN_OPTIONS', value: 'halt_on_error=1:detect_leaks=0' }],
externalConsole: false,
MIMode: 'gdb',
setupCommands: [{ description: 'Enable pretty-printing for gdb', text: '-enable-pretty-printing', ignoreFailures: true }]
});
launch.configurations.push(makeEntry(id, crashingInputPath));
if (!seenTests.has(test)) {
launch.configurations.push(makeEntry('CORPUS', null));
seenTests.add(test);
}
}
if (launch.configurations.length === 0) {
vscode.window.showInformationMessage('No new debug profiles were generated.');
return;
}
const config = vscode.workspace.getConfiguration('launch');
await config.update('configurations', launch.configurations, false);
vscode.window.showInformationMessage(`Successfully generated ${launch.configurations.length} debug profiles. You may need to reload the window for them to appear in the debug panel.`);
}
async function addFindingBreakpoint() {
const root = getWorkspaceRoot();
if (!root) { return; }
const allFindings = getAllFindings(root);
if (allFindings.length === 0) {
vscode.window.showInformationMessage('No findings available to add a breakpoint for.');
return;
}
const quickPickItems = allFindings.map(finding => ({
label: finding.name,
description: `(Fuzz Test: ${finding.fuzz_test})`,
detail: `Crash in ${finding.stack_trace?.[0]?.SourceFile || 'unknown file'}`,
findingData: finding
}));
const selectedItem = await vscode.window.showQuickPick(quickPickItems, {
placeHolder: 'Select a finding to add a breakpoint for'
});
if (!selectedItem) {
console.log('User cancelled breakpoint selection.');
return;
}
const { stack_trace, name: id } = selectedItem.findingData;
let breakpointFrame = null;
if (Array.isArray(stack_trace) && stack_trace.length > 0) {
breakpointFrame = stack_trace.find(frame => frame && frame.SourceFile && !frame.SourceFile.toLowerCase().includes('fuzz'));
if (!breakpointFrame) { breakpointFrame = stack_trace[0]; }
}
if (breakpointFrame && breakpointFrame.SourceFile && breakpointFrame.Line > 0) {
const fileUri = vscode.Uri.file(path.join(root, breakpointFrame.SourceFile));
const line = breakpointFrame.Line - 1; // API is 0-based
const location = new vscode.Location(fileUri, new vscode.Position(line, 0));
const breakpoint = new vscode.SourceBreakpoint(
location,
true
);
vscode.debug.addBreakpoints([breakpoint]);
vscode.window.showInformationMessage(`Added breakpoint for finding: ${id}`);
console.log(`Added breakpoint for API: ${fileUri.fsPath}:${breakpointFrame.Line}`);
} else {
vscode.window.showErrorMessage(`Could not add breakpoint for ${id}: No valid stack trace information found.`);
}
}
function activate(context) {
const generateProfilesCommand = vscode.commands.registerCommand('cifuzz.generateDebugProfiles', async () => {
try {
await generateProfiles();
} catch (error) {
console.error("Failed to generate debug profiles:", error);
vscode.window.showErrorMessage(`An unexpected error occurred: ${error.message}`);
}
});
const addBreakpointCommand = vscode.commands.registerCommand('cifuzz.addFindingBreakpoint', async () => {
try {
await addFindingBreakpoint();
} catch (error) {
console.error("Failed to add breakpoint:", error);
vscode.window.showErrorMessage(`An unexpected error occurred: ${error.message}`);
}
});
context.subscriptions.push(generateProfilesCommand, addBreakpointCommand);
}
function deactivate() {}
module.exports = { activate, deactivate };