-
Notifications
You must be signed in to change notification settings - Fork 229
Expand file tree
/
Copy pathdebug-session.ts
More file actions
640 lines (568 loc) · 18.1 KB
/
debug-session.ts
File metadata and controls
640 lines (568 loc) · 18.1 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
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
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
import {
ContinuedEvent,
Event,
ExitedEvent,
InitializedEvent,
LoggingDebugSession,
OutputEvent,
ProgressEndEvent,
StoppedEvent,
TerminatedEvent,
} from "@vscode/debugadapter";
import type { DebugProtocol as Protocol } from "@vscode/debugprotocol";
import type { Disposable } from "vscode";
import { CancellationTokenSource } from "vscode-jsonrpc";
import type { BaseLogger, LogOptions } from "../common/logging";
import { queryServerLogger } from "../common/logging/vscode";
import { QueryResultType } from "../query-server/messages";
import type {
CoreQueryResult,
CoreQueryRun,
QueryRunner,
} from "../query-server";
// eslint-disable-next-line import/no-namespace -- There are two different debug protocols, so we should make a distinction.
import type * as CodeQLProtocol from "./debug-protocol";
import type { QuickEvalContext } from "../run-queries-shared";
import { getErrorMessage } from "../common/helpers-pure";
import { DisposableObject } from "../common/disposable-object";
import { basename } from "path";
// More complete implementations of `Event` for certain events, because the classes from
// `@vscode/debugadapter` make it more difficult to provide some of the message values.
class ProgressStartEvent extends Event implements Protocol.ProgressStartEvent {
public readonly event = "progressStart";
public readonly body: {
progressId: string;
title: string;
requestId?: number;
cancellable?: boolean;
message?: string;
percentage?: number;
};
constructor(
progressId: string,
title: string,
message?: string,
percentage?: number,
) {
super("progressStart");
this.body = {
progressId,
title,
message,
percentage,
};
}
}
class ProgressUpdateEvent
extends Event
implements Protocol.ProgressUpdateEvent
{
public readonly event = "progressUpdate";
public readonly body: {
progressId: string;
message?: string;
percentage?: number;
};
constructor(progressId: string, message?: string, percentage?: number) {
super("progressUpdate");
this.body = {
progressId,
message,
percentage,
};
}
}
class EvaluationStartedEvent
extends Event
implements CodeQLProtocol.EvaluationStartedEvent
{
public readonly type = "event";
public readonly event = "codeql-evaluation-started";
public readonly body: CodeQLProtocol.EvaluationStartedEvent["body"];
constructor(
id: string,
outputDir: string,
quickEvalContext: QuickEvalContext | undefined,
) {
super("codeql-evaluation-started");
this.body = {
id,
outputDir,
quickEvalContext,
};
}
}
class EvaluationCompletedEvent
extends Event
implements CodeQLProtocol.EvaluationCompletedEvent
{
public readonly type = "event";
public readonly event = "codeql-evaluation-completed";
public readonly body: CodeQLProtocol.EvaluationCompletedEvent["body"];
constructor(result: CoreQueryResult) {
super("codeql-evaluation-completed");
this.body = result;
}
}
/**
* Possible states of the debug session. Used primarily to guard against unexpected requests.
*/
type State =
| "uninitialized"
| "initialized"
| "running"
| "stopped"
| "terminated";
// IDs for error messages generated by the debug adapter itself.
/** Received a DAP message while in an unexpected state. */
const ERROR_UNEXPECTED_STATE = 1;
/** ID of the "thread" that represents the query evaluation. */
const QUERY_THREAD_ID = 1;
/** The user-visible name of the query evaluation thread. */
const QUERY_THREAD_NAME = "Evaluation thread";
/**
* An active query evaluation within a debug session.
*
* This class encapsulates the state and resources associated with the running query, to avoid
* having multiple properties within `QLDebugSession` that are only defined during query evaluation.
*/
class RunningQuery extends DisposableObject {
private readonly tokenSource = this.push(new CancellationTokenSource());
public readonly queryRun: CoreQueryRun;
private readonly queryPath: string;
public constructor(
queryRunner: QueryRunner,
config: CodeQLProtocol.LaunchConfig,
private readonly quickEvalContext: QuickEvalContext | undefined,
queryStorageDir: string,
private readonly logger: BaseLogger,
private readonly sendEvent: (event: Event) => void,
) {
super();
this.queryPath = config.query;
// Create the query run, which will give us some information about the query even before the
// evaluation has completed.
this.queryRun = queryRunner.createQueryRun(
config.database,
[
{
queryPath: this.queryPath,
outputBaseName: "results",
quickEvalPosition: quickEvalContext?.quickEvalPosition,
quickEvalCountOnly: quickEvalContext?.quickEvalCount,
},
],
true,
config.additionalPacks,
config.extensionPacks,
config.additionalRunQueryArgs,
queryStorageDir,
basename(config.query),
undefined,
);
}
public get id(): string {
return this.queryRun.id;
}
/**
* Evaluates the query, firing progress events along the way. The evaluation can be cancelled by
* calling `cancel()`.
*
* This function does not throw exceptions to report query evaluation failure. It just returns an
* evaluation result with a failure message instead.
*/
public async evaluate(): Promise<
CodeQLProtocol.EvaluationCompletedEvent["body"]
> {
// Send the `EvaluationStarted` event first, to let the client known where the outputs are
// going to show up.
this.sendEvent(
new EvaluationStartedEvent(
this.queryRun.id,
this.queryRun.outputDir.querySaveDir,
this.quickEvalContext,
),
);
try {
// Report progress via the debugger protocol.
const progressStart = new ProgressStartEvent(
this.queryRun.id,
"Running query",
undefined,
0,
);
progressStart.body.cancellable = true;
this.sendEvent(progressStart);
try {
const completedQuery = await this.queryRun.evaluate(
(p) => {
const progressUpdate = new ProgressUpdateEvent(
this.queryRun.id,
p.message,
(p.step * 100) / p.maxStep,
);
this.sendEvent(progressUpdate);
},
this.tokenSource.token,
this.logger,
);
return (
completedQuery.results.get(this.queryPath) ?? {
resultType: QueryResultType.OTHER_ERROR,
message: "Missing query results",
evaluationTime: 0,
outputBaseName: "unknown",
}
);
} finally {
this.sendEvent(new ProgressEndEvent(this.queryRun.id));
}
} catch (e) {
const message = getErrorMessage(e);
return {
resultType: QueryResultType.OTHER_ERROR,
message,
evaluationTime: 0,
outputBaseName: "unknown",
};
}
}
/**
* Attempts to cancel the running evaluation.
*/
public cancel(): void {
this.tokenSource.cancel();
}
}
/**
* An in-process implementation of the debug adapter for CodeQL queries.
*
* For now, this is pretty much just a wrapper around the query server.
*/
export class QLDebugSession extends LoggingDebugSession implements Disposable {
/** A `BaseLogger` that sends output to the debug console. */
private readonly logger: BaseLogger = {
log: async (message: string, _options: LogOptions): Promise<void> => {
// Only send the output event if we're still connected to the query evaluation.
if (this.runningQuery !== undefined) {
this.sendEvent(new OutputEvent(message, "console"));
}
},
};
private state: State = "uninitialized";
private terminateOnComplete = false;
private args: CodeQLProtocol.LaunchRequest["arguments"] | undefined =
undefined;
private runningQuery: RunningQuery | undefined = undefined;
private lastResultType: QueryResultType = QueryResultType.CANCELLATION;
constructor(
private readonly queryStorageDir: string,
private readonly queryRunner: QueryRunner,
) {
super();
}
public dispose(): void {
if (this.runningQuery !== undefined) {
this.runningQuery.cancel();
}
}
protected dispatchRequest(request: Protocol.Request): void {
// We just defer to the base class implementation, but having this override makes it easy to set
// a breakpoint that will be hit for any message received by the debug adapter.
void queryServerLogger.log(`DAP request: ${request.command}`);
super.dispatchRequest(request);
}
private unexpectedState(response: Protocol.Response): void {
this.sendErrorResponse(
response,
ERROR_UNEXPECTED_STATE,
"CodeQL debug adapter received request '{_request}' while in unexpected state '{_actualState}'.",
{
_request: response.command,
_actualState: this.state,
},
);
}
protected initializeRequest(
response: Protocol.InitializeResponse,
_args: Protocol.InitializeRequestArguments,
): void {
switch (this.state) {
case "uninitialized":
response.body = response.body ?? {};
response.body.supportsStepBack = false;
response.body.supportsStepInTargetsRequest = false;
response.body.supportsRestartFrame = false;
response.body.supportsGotoTargetsRequest = false;
response.body.supportsCancelRequest = true;
response.body.supportsTerminateRequest = true;
response.body.supportsModulesRequest = false;
response.body.supportsConfigurationDoneRequest = true;
response.body.supportsRestartRequest = false;
this.state = "initialized";
this.sendResponse(response);
this.sendEvent(new InitializedEvent());
break;
default:
this.unexpectedState(response);
break;
}
}
protected disconnectRequest(
response: Protocol.DisconnectResponse,
_args: Protocol.DisconnectArguments,
_request?: Protocol.Request,
): void {
// The client is forcing a disconnect. We'll signal cancellation, but since this request means
// that the debug session itself is about to go away, we'll stop processing events from the
// evaluation to avoid sending them to the client that is no longer interested in them.
this.terminateOrDisconnect(response, true);
}
protected terminateRequest(
response: Protocol.TerminateResponse,
_args: Protocol.TerminateArguments,
_request?: Protocol.Request,
): void {
// The client is requesting a graceful termination. This will signal the cancellation token of
// any in-progress evaluation, but that evaluation will continue to report events (like
// progress) until the cancellation takes effect.
this.terminateOrDisconnect(response, false);
}
private terminateOrDisconnect(
response: Protocol.Response,
force: boolean,
): void {
const runningQuery = this.runningQuery;
if (force) {
// Disconnect from the running query so that we stop processing its progress events.
this.runningQuery = undefined;
}
if (runningQuery !== undefined) {
this.terminateOnComplete = true;
runningQuery.cancel();
} else if (this.state === "stopped") {
this.terminateAndExit();
}
this.sendResponse(response);
}
protected launchRequest(
response: Protocol.LaunchResponse,
args: CodeQLProtocol.LaunchRequest["arguments"],
_request?: Protocol.Request,
): void {
switch (this.state) {
case "initialized":
this.args = args;
// If `noDebug` is set, then terminate after evaluation instead of stopping.
this.terminateOnComplete = this.args.noDebug === true;
response.body = response.body ?? {};
// Send the response immediately. We'll send a "stopped" message when the evaluation is complete.
this.sendResponse(response);
void this.evaluate(this.args.quickEvalContext);
break;
default:
this.unexpectedState(response);
break;
}
}
protected nextRequest(
response: Protocol.NextResponse,
_args: Protocol.NextArguments,
_request?: Protocol.Request,
): void {
this.stepRequest(response);
}
protected stepInRequest(
response: Protocol.StepInResponse,
_args: Protocol.StepInArguments,
_request?: Protocol.Request,
): void {
this.stepRequest(response);
}
protected stepOutRequest(
response: Protocol.Response,
_args: Protocol.StepOutArguments,
_request?: Protocol.Request,
): void {
this.stepRequest(response);
}
protected stepBackRequest(
response: Protocol.StepBackResponse,
_args: Protocol.StepBackArguments,
_request?: Protocol.Request,
): void {
this.stepRequest(response);
}
private stepRequest(response: Protocol.Response): void {
switch (this.state) {
case "stopped":
this.sendResponse(response);
// We don't do anything with stepping yet, so just announce that we've stopped without
// actually doing anything.
// We don't even send the `EvaluationCompletedEvent`.
this.reportStopped();
break;
default:
this.unexpectedState(response);
break;
}
}
protected continueRequest(
response: Protocol.ContinueResponse,
_args: Protocol.ContinueArguments,
_request?: Protocol.Request,
): void {
switch (this.state) {
case "stopped":
response.body = response.body ?? {};
response.body.allThreadsContinued = true;
// Send the response immediately. We'll send a "stopped" message when the evaluation is complete.
this.sendResponse(response);
void this.evaluate(undefined);
break;
default:
this.unexpectedState(response);
break;
}
}
protected cancelRequest(
response: Protocol.CancelResponse,
args: Protocol.CancelArguments,
_request?: Protocol.Request,
): void {
if (
args.progressId !== undefined &&
this.runningQuery?.id === args.progressId
) {
this.runningQuery.cancel();
}
this.sendResponse(response);
}
protected threadsRequest(
response: Protocol.ThreadsResponse,
_request?: Protocol.Request,
): void {
response.body = response.body ?? {};
response.body.threads = [
{
id: QUERY_THREAD_ID,
name: QUERY_THREAD_NAME,
},
];
this.sendResponse(response);
}
protected stackTraceRequest(
response: Protocol.StackTraceResponse,
_args: Protocol.StackTraceArguments,
_request?: Protocol.Request,
): void {
response.body = response.body ?? {};
response.body.stackFrames = []; // No frames for now.
super.stackTraceRequest(response, _args, _request);
}
protected customRequest(
command: string,
response: CodeQLProtocol.Response,
args: unknown,
request?: Protocol.Request,
): void {
switch (command) {
case "codeql-quickeval": {
this.quickEvalRequest(
response,
args as CodeQLProtocol.QuickEvalRequest["arguments"],
);
break;
}
default:
super.customRequest(command, response, args, request);
break;
}
}
protected quickEvalRequest(
response: CodeQLProtocol.QuickEvalResponse,
args: CodeQLProtocol.QuickEvalRequest["arguments"],
): void {
switch (this.state) {
case "stopped":
// Send the response immediately. We'll send a "stopped" message when the evaluation is complete.
this.sendResponse(response);
// For built-in requests that are expected to cause execution (`launch`, `continue`, `step`, etc.),
// the adapter does not send a `continued` event because the client already knows that's what
// is supposed to happen. For a custom request, though, we have to notify the client.
this.sendEvent(new ContinuedEvent(QUERY_THREAD_ID, true));
void this.evaluate(args.quickEvalContext);
break;
default:
this.unexpectedState(response);
break;
}
}
/**
* Runs the query or quickeval, and notifies the debugger client when the evaluation completes.
*
* This function is invoked from the `launch` and `continue` handlers, without awaiting its
* result.
*/
private async evaluate(
quickEvalContext: QuickEvalContext | undefined,
): Promise<void> {
const args = this.args!;
const runningQuery = new RunningQuery(
this.queryRunner,
args,
quickEvalContext,
this.queryStorageDir,
this.logger,
(event) => {
// If `this.runningQuery` is undefined, it means that we've already disconnected from this
// evaluation, and do not want any further events.
if (this.runningQuery !== undefined) {
this.sendEvent(event);
}
},
);
this.runningQuery = runningQuery;
this.state = "running";
try {
const result = await runningQuery.evaluate();
this.completeEvaluation(result);
} finally {
this.runningQuery = undefined;
runningQuery.dispose();
}
}
/**
* Mark the evaluation as completed, and notify the client of the result.
*/
private completeEvaluation(
result: CodeQLProtocol.EvaluationCompletedEvent["body"],
): void {
this.lastResultType = result.resultType;
// Report the evaluation result
this.sendEvent(new EvaluationCompletedEvent(result));
if (result.resultType !== QueryResultType.SUCCESS) {
// Report the result message as "important" output
const message = result.message ?? "Unknown error";
const outputEvent = new OutputEvent(message, "console");
this.sendEvent(outputEvent);
}
this.reportStopped();
}
private reportStopped(): void {
if (this.terminateOnComplete) {
this.terminateAndExit();
} else {
// Report the session as "stopped", but keep the session open.
this.sendEvent(new StoppedEvent("entry", QUERY_THREAD_ID));
this.state = "stopped";
}
}
private terminateAndExit(): void {
// Report the debugging session as terminated.
this.sendEvent(new TerminatedEvent());
// Report the debuggee as exited.
this.sendEvent(new ExitedEvent(this.lastResultType));
this.state = "terminated";
}
}