-
Notifications
You must be signed in to change notification settings - Fork 67
/
Copy pathfirefoxDebugAdapter.ts
515 lines (382 loc) · 16.6 KB
/
firefoxDebugAdapter.ts
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
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
import { URI } from 'vscode-uri';
import { DebugProtocol } from '@vscode/debugprotocol';
import { DebugSession, StoppedEvent, OutputEvent, Thread, Variable, Breakpoint } from '@vscode/debugadapter';
import { Log } from './util/log';
import { accessorExpression } from './util/misc';
import { DebugAdapterBase } from './debugAdapterBase';
import { ThreadAdapter } from './adapter/thread';
import { SourceAdapter } from './adapter/source';
import { LaunchConfiguration, AttachConfiguration } from '../common/configuration';
import { parseConfiguration } from './configuration';
import { FirefoxDebugSession, ThreadConfiguration } from './firefoxDebugSession';
import { popupAutohidePreferenceKey } from './adapter/addonManager';
import { ObjectGripAdapter } from './adapter/objectGrip';
import { DataBreakpointsManager } from './adapter/dataBreakpointsManager';
import { normalizePath } from './util/fs';
let log = Log.create('FirefoxDebugAdapter');
export class FirefoxDebugAdapter extends DebugAdapterBase {
private session!: FirefoxDebugSession;
public constructor(debuggerLinesStartAt1: boolean, isServer: boolean = false) {
super(debuggerLinesStartAt1, isServer);
if (!isServer) {
Log.consoleLog = (msg: string) => {
this.sendEvent(new OutputEvent(msg + '\n'));
}
}
}
protected initialize(args: DebugProtocol.InitializeRequestArguments): DebugProtocol.Capabilities {
return {
supportsConfigurationDoneRequest: false,
supportsEvaluateForHovers: false,
supportsFunctionBreakpoints: false,
supportsConditionalBreakpoints: true,
supportsSetVariable: true,
supportsCompletionsRequest: true,
supportsDelayedStackTraceLoading: true,
supportsHitConditionalBreakpoints: true,
supportsLogPoints: true,
supportsDataBreakpoints: true,
supportsBreakpointLocationsRequest: true,
supportsRestartFrame: true,
supportsANSIStyling: true,
exceptionBreakpointFilters: [
{
filter: 'all',
label: 'All Exceptions',
default: false
},
{
filter: 'uncaught',
label: 'Uncaught Exceptions',
default: true
},
{
filter: 'debugger',
label: 'Debugger Statements',
default: true
}
]
};
}
protected async launch(args: LaunchConfiguration): Promise<void> {
await this.startSession(args);
}
protected async attach(args: AttachConfiguration): Promise<void> {
await this.startSession(args);
}
private async startSession(config: LaunchConfiguration | AttachConfiguration): Promise<void> {
if (config.log) {
Log.setConfig(config.log);
}
let parsedConfig = await parseConfiguration(config);
this.session = new FirefoxDebugSession(parsedConfig, (ev) => this.sendEvent(ev));
await this.session.start();
}
protected async breakpointLocations(
args: DebugProtocol.BreakpointLocationsArguments
): Promise<{ breakpoints: DebugProtocol.BreakpointLocation[]; }> {
if (!args.source.path) return { breakpoints: [] };
const sourceAdapter = await this.session.sources.getAdapterForPath(normalizePath(args.source.path));
const positions = await sourceAdapter.getBreakableLocations(args.line);
const breakpoints: DebugProtocol.BreakpointLocation[] = [];
for (const position of positions) {
breakpoints.push({ line: position.line, column: position.column + 1 });
}
return { breakpoints };
}
protected setBreakpoints(args: DebugProtocol.SetBreakpointsArguments): { breakpoints: DebugProtocol.Breakpoint[] } {
const requestedBreakpoints = args.breakpoints;
if (requestedBreakpoints === undefined) {
log.error('setBreakpoints request without any breakpoints');
return { breakpoints: [] };
}
// a path for local sources or a url (as seen by either VS Code or Firefox) for remote sources
const sourcePathOrUrl = args.source.path;
if (sourcePathOrUrl === undefined) {
throw 'Couldn\'t set breakpoint: unknown source path';
}
const breakpointInfos = this.session.breakpointsManager.setBreakpoints(requestedBreakpoints, sourcePathOrUrl);
const breakpoints = breakpointInfos.map(breakpointInfo => {
const breakpoint: DebugProtocol.Breakpoint = new Breakpoint(
breakpointInfo.verified,
breakpointInfo.requestedBreakpoint.line,
breakpointInfo.requestedBreakpoint.column
);
breakpoint.id = breakpointInfo.id;
return breakpoint;
});
return { breakpoints };
}
protected setExceptionBreakpoints(args: DebugProtocol.SetExceptionBreakpointsArguments): void {
log.debug(`Setting exception filters: ${JSON.stringify(args.filters)}`);
const threadConfiguration: ThreadConfiguration = {
pauseOnExceptions: args.filters.includes('all') || args.filters.includes('uncaught'),
ignoreCaughtExceptions: !args.filters.includes('all'),
shouldPauseOnDebuggerStatement: args.filters.includes('debugger'),
};
this.session.setThreadConfiguration(threadConfiguration);
}
protected async pause(args: DebugProtocol.PauseArguments): Promise<void> {
let threadAdapter = this.getThreadAdapter(args.threadId);
this.session.setActiveThread(threadAdapter);
await threadAdapter.interrupt();
let stoppedEvent = new StoppedEvent('interrupt', threadAdapter.id);
(<DebugProtocol.StoppedEvent>stoppedEvent).body.allThreadsStopped = false;
this.sendEvent(stoppedEvent);
}
protected async next(args: DebugProtocol.NextArguments): Promise<void> {
let threadAdapter = this.getThreadAdapter(args.threadId);
this.session.setActiveThread(threadAdapter);
await threadAdapter.stepOver();
}
protected async stepIn(args: DebugProtocol.StepInArguments): Promise<void> {
let threadAdapter = this.getThreadAdapter(args.threadId);
this.session.setActiveThread(threadAdapter);
await threadAdapter.stepIn();
}
protected async stepOut(args: DebugProtocol.StepOutArguments): Promise<void> {
let threadAdapter = this.getThreadAdapter(args.threadId);
this.session.setActiveThread(threadAdapter);
await threadAdapter.stepOut();
}
protected async continue(args: DebugProtocol.ContinueArguments): Promise<{ allThreadsContinued?: boolean }> {
let threadAdapter = this.getThreadAdapter(args.threadId);
this.session.setActiveThread(threadAdapter);
await threadAdapter.resume();
return { allThreadsContinued: false };
}
protected async getSource(args: DebugProtocol.SourceArguments): Promise<{ content: string, mimeType?: string }> {
let sourceAdapter: SourceAdapter | undefined;
if (args.sourceReference !== undefined) {
sourceAdapter = this.session.sources.getAdapterForID(args.sourceReference);
} else if (args.source?.path) {
sourceAdapter = this.session.sources.findSourceAdaptersForPathOrUrl(args.source.path)[0];
if (!sourceAdapter && args.source.path.indexOf('?') < 0) {
// workaround for VSCode issue #32845: the url may have contained a query string that got lost,
// in this case we look for a Source whose url is the same if the query string is removed
sourceAdapter = this.session.sources.findSourceAdaptersForUrlWithoutQuery(args.source.path)[0];
}
}
if (!sourceAdapter) {
throw new Error('Failed sourceRequest: the requested source can\'t be found');
}
let sourceGrip = await sourceAdapter.fetchSource();
if (typeof sourceGrip === 'string') {
return { content: sourceGrip, mimeType: 'text/javascript' };
} else {
let longStringGrip = <FirefoxDebugProtocol.LongStringGrip>sourceGrip;
let longStringActor = this.session.getOrCreateLongStringGripActorProxy(longStringGrip);
let content = await longStringActor.fetchContent();
return { content, mimeType: 'text/javascript' };
}
}
protected getThreads(): { threads: DebugProtocol.Thread[] } {
log.debug(`${this.session.threads.count} threads`);
let threads = this.session.threads.map(
(threadAdapter) => new Thread(threadAdapter.id, `${threadAdapter.name}: ${threadAdapter.url}`));
return { threads };
}
protected async getStackTrace(args: DebugProtocol.StackTraceArguments): Promise<{ stackFrames: DebugProtocol.StackFrame[], totalFrames?: number }> {
let threadAdapter = this.getThreadAdapter(args.threadId);
this.session.setActiveThread(threadAdapter);
let [frameAdapters, totalFrames] =
await threadAdapter.fetchStackFrames(args.startFrame || 0, args.levels || 0);
let stackFrames = await Promise.all(
frameAdapters.map((frameAdapter) => frameAdapter.getStackframe())
);
return { stackFrames, totalFrames };
}
protected async getScopes(args: DebugProtocol.ScopesArguments): Promise<{ scopes: DebugProtocol.Scope[] }> {
let frameAdapter = this.session.frames.find(args.frameId);
if (!frameAdapter) {
throw new Error('Failed scopesRequest: the requested frame can\'t be found');
}
this.session.setActiveThread(frameAdapter.threadAdapter);
const scopeAdapters = await frameAdapter.getScopeAdapters();
const scopes = scopeAdapters.map((scopeAdapter) => scopeAdapter.getScope());
return { scopes };
}
protected async getVariables(args: DebugProtocol.VariablesArguments): Promise<{ variables: DebugProtocol.Variable[] }> {
let variablesProvider = this.session.variablesProviders.find(args.variablesReference);
if (!variablesProvider) {
throw new Error('Failed variablesRequest: the requested object reference can\'t be found');
}
this.session.setActiveThread(variablesProvider.threadAdapter);
try {
let variables = await variablesProvider.threadAdapter.fetchVariables(variablesProvider);
return { variables };
} catch(err) {
let msg: string;
if (err === 'No such actor') {
msg = 'Value can\'t be inspected - this is probably due to Firefox bug #1249962';
} else {
msg = String(err);
}
return { variables: [ new Variable('Error from debugger', msg) ]};
}
}
protected async setVariable(args: DebugProtocol.SetVariableArguments): Promise<{ value: string, variablesReference?: number }> {
let variablesProvider = this.session.variablesProviders.find(args.variablesReference);
if (variablesProvider === undefined) {
throw new Error('Failed setVariableRequest: the requested context can\'t be found')
}
if (variablesProvider.referenceFrame === undefined) {
throw new Error('Failed setVariableRequest: the requested context has no associated stack frame');
}
let referenceExpression = accessorExpression(variablesProvider.referenceExpression, args.name);
let setterExpression = `${referenceExpression} = ${args.value}`;
let frameActorName = variablesProvider.referenceFrame.frame.actor;
let result = await variablesProvider.threadAdapter.evaluate(setterExpression, false, frameActorName);
return { value: result.value, variablesReference: result.variablesReference };
}
protected async evaluate(args: DebugProtocol.EvaluateArguments): Promise<{ result: string, type?: string, variablesReference: number, namedVariables?: number, indexedVariables?: number }> {
let variable: Variable | undefined = undefined;
if (args.context === 'watch') {
if (args.frameId !== undefined) {
let frameAdapter = this.session.frames.find(args.frameId);
if (frameAdapter !== undefined) {
this.session.setActiveThread(frameAdapter.threadAdapter);
let threadAdapter = frameAdapter.threadAdapter;
let frameActorName = frameAdapter.frame.actor;
variable = await threadAdapter.evaluate(args.expression, true, frameActorName);
} else {
log.warn(`Couldn\'t find specified frame for evaluating ${args.expression}`);
throw 'not available';
}
} else {
let threadAdapter = this.session.getActiveThread();
if (threadAdapter !== undefined) {
variable = await threadAdapter.evaluate(args.expression, true);
} else {
log.info(`Couldn't find a thread for evaluating watch ${args.expression}`);
throw 'not available';
}
}
} else {
let threadAdapter = this.session.getActiveThread();
if (threadAdapter !== undefined) {
let frameActorName: string | undefined = undefined;
if (args.frameId !== undefined) {
let frameAdapter = this.session.frames.find(args.frameId);
if (frameAdapter !== undefined) {
frameActorName = frameAdapter.frame.actor;
}
}
variable = await threadAdapter.evaluate(args.expression, false, frameActorName);
} else {
log.info(`Couldn't find a thread for evaluating ${args.expression}`);
throw 'not available';
}
}
return {
result: variable.value,
variablesReference: variable.variablesReference
};
}
protected async getCompletions(args: DebugProtocol.CompletionsArguments): Promise<{ targets: DebugProtocol.CompletionItem[] }> {
let matches: string[];
if (args.frameId !== undefined) {
let frameAdapter = this.session.frames.find(args.frameId);
if (frameAdapter === undefined) {
log.warn(`Couldn\'t find specified frame for auto-completing ${args.text}`);
throw 'not available';
}
this.session.setActiveThread(frameAdapter.threadAdapter);
let threadAdapter = frameAdapter.threadAdapter;
let frameActorName = frameAdapter.frame.actor;
matches = await threadAdapter.autoComplete(args.text, args.column - 1, frameActorName);
} else {
let threadAdapter = this.session.getActiveThread();
if (threadAdapter === undefined) {
log.warn(`Couldn't find a thread for auto-completing ${args.text}`);
throw 'not available';
}
matches = await threadAdapter.autoComplete(args.text, args.column - 1);
}
return {
targets: matches.map((match) => <DebugProtocol.CompletionItem>{ label: match })
};
}
protected async dataBreakpointInfo(args: DebugProtocol.DataBreakpointInfoArguments): Promise<{ dataId: string | null, description: string, accessTypes?: DebugProtocol.DataBreakpointAccessType[], canPersist?: boolean }> {
if (!this.session.dataBreakpointsManager) {
return {
dataId: null,
description: "Your version of Firefox doesn't support watchpoints / data breakpoints"
};
}
if (args.variablesReference !== undefined) {
const provider = this.session.variablesProviders.find(args.variablesReference);
if (provider instanceof ObjectGripAdapter) {
try {
await provider.actor.threadLifetime();
provider.threadAdapter.threadLifetime(provider);
return {
dataId: DataBreakpointsManager.encodeDataId(args.variablesReference, args.name),
description: args.name,
accessTypes: [ 'read', 'write' ]
};
} catch {}
}
}
return {
dataId: null,
description: 'Data breakpoints are only supported on object properties'
};
}
protected async setDataBreakpoints(args: DebugProtocol.SetDataBreakpointsArguments): Promise<{ breakpoints: DebugProtocol.Breakpoint[] }> {
if (!this.session.dataBreakpointsManager) {
if (args.breakpoints.length === 0) {
return { breakpoints: [] };
} else {
throw "Your version of Firefox doesn't support watchpoints / data breakpoints";
}
}
await this.session.dataBreakpointsManager.setDataBreakpoints(args.breakpoints);
return { breakpoints: new Array(args.breakpoints.length).fill({ verified: true }) }
}
protected async restartFrame(args: DebugProtocol.RestartFrameArguments): Promise<void> {
const frameAdapter = this.session.frames.find(args.frameId);
if (!frameAdapter) {
throw new Error('Failed restartFrameRequest: the requested frame can\'t be found');
}
this.session.setActiveThread(frameAdapter.threadAdapter);
await frameAdapter.threadAdapter.restartFrame(frameAdapter.frame.actor);
}
protected async reloadAddon(): Promise<void> {
if (!this.session.addonManager) {
throw 'This command is only available when debugging an addon'
}
await this.session.addonManager.reloadAddon();
}
protected async toggleSkippingFile(url: string): Promise<void> {
if (url.startsWith('file://')) {
const path = URI.parse(url).fsPath;
await this.session.skipFilesManager.toggleSkipping(path);
} else {
await this.session.skipFilesManager.toggleSkipping(url);
}
}
protected async setPopupAutohide(enabled: boolean): Promise<void> {
await this.session.preferenceActor.setBoolPref(popupAutohidePreferenceKey, !enabled);
}
protected async togglePopupAutohide(): Promise<boolean> {
const currentValue = await this.session.preferenceActor.getBoolPref(popupAutohidePreferenceKey);
const newValue = !currentValue;
await this.session.preferenceActor.setBoolPref(popupAutohidePreferenceKey, newValue);
return !newValue;
}
protected setActiveEventBreakpoints(args: string[] | undefined): Promise<void> {
return this.session.eventBreakpointsManager.setActiveEventBreakpoints(args ?? []);
}
protected async disconnect(args: DebugProtocol.DisconnectArguments): Promise<void> {
await this.session.stop();
}
private getThreadAdapter(threadId: number): ThreadAdapter {
let threadAdapter = this.session.threads.find(threadId);
if (!threadAdapter) {
throw new Error(`Unknown threadId ${threadId}`);
}
return threadAdapter;
}
}
DebugSession.run(FirefoxDebugAdapter);