Repository navigation
Expand file tree
/
Copy pathdart_debug_impl.ts
More file actions
1939 lines (1666 loc) · 75.7 KB
/
Copy pathdart_debug_impl.ts
File metadata and controls
1939 lines (1666 loc) · 75.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
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
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* eslint-disable no-underscore-dangle */
import { DebugSession, Event, InitializedEvent, OutputEvent, Scope, Source, StackFrame, StoppedEvent, TerminatedEvent } from "@vscode/debugadapter";
import { DebugProtocol } from "@vscode/debugprotocol";
import * as fs from "fs";
import * as path from "path";
import { debugLaunchProgressId, debugTerminatingProgressId, pleaseReportBug } from "../shared/constants";
import { DartLaunchArgs } from "../shared/debugging/interfaces";
import { LogCategory, LogSeverity } from "../shared/enums";
import { LogMessage, SpawnedProcess } from "../shared/interfaces";
import { PackageMap } from "../shared/pub/package_map";
import { PromiseCompleter, errorMessage, errorMessageWithStack, notUndefined, uniq, uriToFilePath } from "../shared/utils";
import { sortBy } from "../shared/utils/array";
import { applyColor, faint } from "./colors";
import { vmServiceListeningBannerPattern } from "./constants";
import { DebuggerResult, VM, VMClass, VMClassRef, VMErrorRef, VMEvent, VMFrame, VMInstance, VMInstanceRef, VMIsolate, VMIsolateRef, VMMapEntry, VMObj, VMScript, VMScriptRef, VMSentinel, VMStack, VMTypeRef, VMWriteEvent, Version, VmExceptionMode, VmServiceConnection } from "./dart_debug_protocol";
import { DebugAdapterLogger } from "./logging";
import { mayContainStackFrame, parseStackFrame } from "./stack_trace";
import { ThreadInfo, ThreadManager } from "./threads";
import { formatPathForVm } from "./utils";
import { VmServiceCapabilities } from "./vm_service";
const maxValuesToCallToString = 100;
// Prefix that appears at the start of stack frame names that are unoptimized
// which we'd prefer not to show to the user.
const unoptimizedPrefix = "[Unoptimized] ";
const trailingSemicolonPattern = new RegExp(`;\\s*$`, "m");
const threadExceptionExpression = "$_threadException";
// TODO: supportsSetVariable
// TODO: class variables?
// TODO: library variables?
// stepBackRequest(response: DebugProtocol.StepBackResponse, args: DebugProtocol.StepBackArguments): void;
// restartFrameRequest(response: DebugProtocol.RestartFrameResponse, args: DebugProtocol.RestartFrameArguments): void;
// completionsRequest(response: DebugProtocol.CompletionsResponse, args: DebugProtocol.CompletionsArguments): void;
export abstract class DartDebugSession extends DebugSession {
// TODO: Tidy all this up
protected childProcess?: SpawnedProcess | RemoteEditorTerminalProcess;
/** The additional process IDs to terminate when terminating a debugging session.
*
* A Set is used so a Process ID does not appear multiple times within the collection as
* that can cause a (eg. testing) session to be terminated prematurely while waiting for it to end.
*/
protected readonly additionalPidsToTerminate = new Set<number>();
protected expectAdditionalPidToTerminate = false;
private additionalPidCompleter = new PromiseCompleter<void>();
protected processExited = false;
public vmService?: VmServiceConnection;
protected cwd?: string;
public noDebug?: boolean;
private sendLogsToClient = false;
protected toolEnv?: any;
public debugSdkLibraries = false;
public debugExternalPackageLibraries = false;
public showDartDeveloperLogs = true;
protected subscribeToStdout = false;
public evaluateGettersInDebugViews = false;
protected evaluateToStringInDebugViews = false;
public readonly vmServiceCapabilities = VmServiceCapabilities.empty;
protected threadManager: ThreadManager;
public packageMap?: PackageMap;
protected sendStdOutToConsole = true;
protected parseVmServiceUriFromStdOut = true;
protected requiresProgram = true;
protected processExit: Promise<{ code: number | null, signal: string | null }> = Promise.resolve({ code: 0, signal: null });
protected maxLogLineLength = 1000; // This should always be overriden in launch/attach requests but we have it here for narrower types.
protected logCategory = LogCategory.General; // This isn't used as General, since both debuggers override it.
protected isTerminating = false;
protected readonly logger = new DebugAdapterLogger(this, LogCategory.VmService);
protected debuggerInit: Promise<void> | undefined;
protected get shouldConnectDebugger() {
return !this.noDebug;
}
public constructor() {
// Don't allow unhandled promises to terminate the DA, instead send a log event
// to the client.
// TODO: Track down and fix anywhere that unhandled promises can occur!
process.on("unhandledRejection", (reason, promise) => {
this.logger.error(`UNHANDLED: ${reason}, ${promise}`);
});
super();
this.threadManager = new ThreadManager(this.logger, this);
}
protected initializeRequest(
response: DebugProtocol.InitializeResponse,
args: DebugProtocol.InitializeRequestArguments,
): void {
response.body = response.body || {};
response.body.supportsConfigurationDoneRequest = true;
response.body.supportsEvaluateForHovers = true;
response.body.supportsDelayedStackTraceLoading = true;
response.body.supportsConditionalBreakpoints = true;
response.body.supportsLogPoints = true;
response.body.supportsTerminateRequest = true;
response.body.supportsRestartFrame = true;
response.body.supportsClipboardContext = true;
response.body.exceptionBreakpointFilters = [
{ filter: "All", label: "All Exceptions", default: false },
{ filter: "Unhandled", label: "Uncaught Exceptions", default: true },
];
this.sendResponse(response);
}
protected async launchRequest(response: DebugProtocol.LaunchResponse, args: DartLaunchArgs & DebugProtocol.LaunchRequestArguments): Promise<void> {
if (!args || !args.dartSdkPath || (this.requiresProgram && !args.program)) {
this.logToUser("Unable to restart debugging. Please try ending the debug session and starting again.\n");
this.sendEvent(new TerminatedEvent());
return;
}
// Force relative paths to absolute.
if (args.program && !path.isAbsolute(args.program)) {
if (!args.cwd) {
return this.errorResponse(response, "Unable to start debugging. program was specified as a relative path without cwd.");
}
args.program = path.join(args.cwd, args.program);
}
this.startProgress(debugLaunchProgressId, "Launching");
this.cwd = args.cwd;
this.noDebug = args.noDebug;
// Set default exception mode based on noDebug. This will be sent to threads
// prior to VS Code sending (or, in the case of noDebug, due to not sending)
// the exception mode.
await this.threadManager.setExceptionPauseMode(this.noDebug ? "None" : "Unhandled");
this.packageMap = PackageMap.load(this.logger, PackageMap.findPackagesFile(args.program || args.cwd));
this.readSharedArgs(args);
this.sendResponse(response);
try {
const process = await this.spawnProcess(args);
this.childProcess = process;
this.processExited = false;
this.processExit = new Promise((resolve) => process.on("exit", (code, signal) => resolve({ code, signal })));
process.stdout.setEncoding("utf8");
process.stdout.on("data", async (data: Buffer | string) => {
let match: RegExpExecArray | null = null;
if (this.shouldConnectDebugger && this.parseVmServiceUriFromStdOut && !this.vmService) {
match = vmServiceListeningBannerPattern.exec(data.toString());
}
if (match)
await this.initDebugger(this.convertObservatoryUriToVmServiceUri(match[1]));
else if (this.sendStdOutToConsole)
this.logStdout(data.toString());
});
process.stderr.setEncoding("utf8");
process.stderr.on("data", (data: Buffer | string) => {
this.logToUserBuffered(data.toString(), "stderr");
});
process.on("error", (error) => {
this.logToUser(`${error}\n`, "stderr");
});
void this.processExit.then(async ({ code, signal }) => {
this.processExited = true;
this.log(`Process exited (${signal ? `${signal}`.toLowerCase() : code})`);
if (!code && !signal)
this.logToUser("Exited\n");
else
this.logToUser(`Exited (${signal ? `${signal}`.toLowerCase() : code})\n`);
// To reduce the chances of losing async logs, wait a short period
// before terminating.
await this.raceIgnoringErrors(() => this.lastLoggingEvent, 500);
setImmediate(() => {
this.sendEvent(new TerminatedEvent());
});
});
} catch (e) {
this.logToUser(`Unable to start debugging: ${e}`);
this.sendEvent(new TerminatedEvent());
return;
}
if (!this.shouldConnectDebugger) {
this.endProgress(debugLaunchProgressId);
this.sendEvent(new InitializedEvent());
// If we're not connecting a debugger and we spawned a remote process, we have
// no way of knowing when the process terminates and will have to just end the debug
// session immediately (it has no value anyway).
if (this.childProcess && this.childProcess instanceof RemoteEditorTerminalProcess)
setImmediate(() => this.sendEvent(new TerminatedEvent()));
}
}
private readSharedArgs(args: DartLaunchArgs) {
this.debugExternalPackageLibraries = args.debugExternalPackageLibraries;
this.debugSdkLibraries = args.debugSdkLibraries;
this.evaluateGettersInDebugViews = args.evaluateGettersInDebugViews;
this.evaluateToStringInDebugViews = args.evaluateToStringInDebugViews;
this.maxLogLineLength = args.maxLogLineLength;
this.sendLogsToClient = !!args.sendLogsToClient;
this.showDartDeveloperLogs = args.showDartDeveloperLogs;
this.toolEnv = args.toolEnv;
}
protected abstract attachRequest(response: DebugProtocol.AttachResponse, args: DartLaunchArgs & DebugProtocol.AttachRequestArguments): Promise<void>;
protected sourceFileForArgs(args: DartLaunchArgs): string {
return args.cwd ? path.relative(args.cwd, args.program!) : args.program!;
}
protected abstract spawnProcess(args: DartLaunchArgs): Promise<SpawnedProcess>;
protected convertObservatoryUriToVmServiceUri(uri: string) {
const wsUri = uri.trim();
if (wsUri.endsWith("/ws"))
return wsUri;
else if (wsUri.endsWith("/ws/"))
return wsUri.substr(0, wsUri.length - 1);
else if (wsUri.endsWith("/"))
return `${wsUri}ws`;
else
return `${wsUri}/ws`;
}
protected log(message: string, severity = LogSeverity.Info) {
if (this.sendLogsToClient)
this.sendEvent(new Event("dart.log", { message, severity, category: LogCategory.VmService } as LogMessage));
}
protected async initDebugger(uri: string): Promise<void> {
// On some cloud providers we get an IPv6 loopback which fails to connect
// correctly. Assume that if we get this, it's safe to use the "localhost" hostname.
uri = uri.replace("[::]", "localhost");
this.log(`Initialising debugger for ${uri}`);
// Send the uri back to the editor so it can be used to launch browsers etc.
let browserFriendlyUri = uri;
if (browserFriendlyUri.endsWith("/ws"))
browserFriendlyUri = uri.substring(0, uri.length - 2);
if (browserFriendlyUri.startsWith("ws:"))
browserFriendlyUri = "http:" + browserFriendlyUri.substring(3);
let vmServiceUri = uri;
if (vmServiceUri.startsWith("http:"))
vmServiceUri = "ws:" + browserFriendlyUri.substring(5);
const evt = new Event("dart.debuggerUris", {
vmServiceUri: vmServiceUri.toString(),
});
this.sendEvent(evt);
if (!this.shouldConnectDebugger)
return;
this.debuggerInit = new Promise<void>((resolve, reject) => {
this.log(`Connecting to VM Service at ${uri}`);
this.logToUser(`Connecting to VM Service at ${uri}\n`);
this.vmService = new VmServiceConnection(uri);
this.vmService.onLogging((message) => this.log(message));
// TODO: Extract some code here and change to async/await. This is
// super confusing, for ex. it's not clear the resolve() inside onOpen
// fires immediately opon opening, not when all the code in the getVM
// callback fires (so it may as well have come first - unless it's
// a bug/race and it was supposed to be after all the setup!).
this.vmService.onOpen(async () => {
if (!this.vmService)
return;
// Read the version to update capabilities before doing anything else.
await this.vmService.getVersion().then(async (versionResult) => {
const version: Version = versionResult.result as Version;
this.vmServiceCapabilities.version = `${version.major}.${version.minor}.0`;
if (!this.vmService)
return;
// Subscribe to streams before we get a list of active isolates, otherwise we could have a race
// between getting the list and then starting to listen for events.
await this.subscribeToStreams();
await this.vmService.getVM().then(async (vmResult): Promise<void> => {
if (!this.vmService)
return;
const vm: VM = vmResult.result as VM;
// If we own this process (we launched it, didn't attach) and the PID we get from the VM service is different, then
// we should keep a ref to this process to terminate when we quit. This avoids issues where our process is a shell
// (we use shell execute to fix issues on Windows) and the kill signal isn't passed on correctly.
// See: https://github.com/Dart-Code/Dart-Code/issues/907
if (this.childProcess) {
this.recordAdditionalPid(vm.pid);
}
const isolates = (await Promise.all(vm.isolates.map((isolateRef) => this.vmService!.getIsolate(isolateRef.id))))
// Filter to just Isolates, in case we got an collected Sentinels.
// https://github.com/flutter/devtools/issues/2324#issuecomment-690128227
.filter((resp) => resp.result.type === "Isolate");
// TODO: Is it valid to assume the first (only?) isolate with a rootLib is the one we care about here?
// If it's always the first, could we even just query the first instead of getting them all before we
// start the other processing?
const rootIsolateResult = isolates.find((isolate) => !!(isolate.result as VMIsolate).rootLib);
const rootIsolate = rootIsolateResult && rootIsolateResult.result as VMIsolate;
if (rootIsolate && rootIsolate.extensionRPCs) {
// If we're attaching, we won't see ServiceExtensionAdded events for extensions already loaded so
// we need to enumerate them here.
rootIsolate.extensionRPCs.forEach((id) => this.notifyServiceExtensionAvailable(id, rootIsolate.id));
}
if (!this.packageMap) {
// TODO: There's a race here if the isolate is not yet runnable, it might not have rootLib yet. We don't
// currently fill this in later.
if (rootIsolate && rootIsolate.rootLib)
this.packageMap = PackageMap.load(this.logger, PackageMap.findPackagesFile(this.convertVMUriToSourcePath(rootIsolate.rootLib.uri)));
}
await Promise.all(isolates.map(async (response) => {
const isolate: VMIsolate = response.result as VMIsolate;
await this.threadManager.registerThread(
isolate,
isolate.runnable ? "IsolateRunnable" : "IsolateStart",
);
if (isolate.pauseEvent.kind.startsWith("Pause")) {
await this.handlePauseEvent(isolate.pauseEvent);
}
}));
this.endProgress(debugLaunchProgressId);
this.sendEvent(new InitializedEvent());
});
});
resolve();
});
this.vmService.onClose((code: number, message: string) => {
this.log(`VM service connection closed: ${code} (${message})`);
// If we don't have a process (eg. we're attached) or we ran as a terminal, then this is our signal to quit,
// since we won't get a process exit event.
if (!this.childProcess || this.childProcess instanceof RemoteEditorTerminalProcess) {
this.sendEvent(new TerminatedEvent());
} else {
// In some cases the VM service closes but we never get the exit/close events from the process
// so this is a fallback to terminate the session after a short period. Without this, we have
// issues like https://github.com/Dart-Code/Dart-Code/issues/1268 even though when testing from
// the terminal the app does terminate as expected.
// 2019-07-10: Increased delay because when we tell Flutter to stop the VM service quits quickly and
// this code results in a TerminatedEvent() even though the process hasn't quit. The TerminatedEvent()
// results in VS Code sending disconnectRequest() and we then try to more forefully kill.
setTimeout(() => {
if (!this.processExited) {
this.sendEvent(new TerminatedEvent());
}
}, 5000);
}
});
this.vmService.onError((error) => {
reject(error);
});
});
return this.debuggerInit;
}
protected recordAdditionalPid(pid: number) {
this.additionalPidsToTerminate.add(pid);
this.additionalPidCompleter.resolve();
}
private async subscribeToStreams(): Promise<void> {
if (!this.vmService)
return;
const serviceStreamName = this.vmServiceCapabilities.serviceStreamIsPublic ? "Service" : "_Service";
await Promise.all([
this.vmService.on("Isolate", (event: VMEvent) => this.handleIsolateEvent(event)),
this.vmService.on("Debug", (event: VMEvent) => this.handleDebugEvent(event)),
this.vmService.on(serviceStreamName, (event: VMEvent) => this.handleServiceEvent(event)),
]);
if (this.vmServiceCapabilities.hasLoggingStream && this.showDartDeveloperLogs) {
await this.vmService.on("Logging", (event: VMEvent) => this.handleLoggingEvent(event)).catch((e) => {
// For web, the protocol version says this is supported, but it throws.
// TODO: Remove this catch block if/when the stable release does not throw.
this.logger.info(errorMessageWithStack(e));
});
}
// We don't know for certain we have a connected DDS that supports custom streams, so wrap in try/catch
try {
await this.vmService.on("ToolEvent", (event: VMEvent) => this.handleToolEvent(event)).catch((e) => {
this.logger.info(errorMessageWithStack(e));
});
} catch (e) { }
if (this.subscribeToStdout) {
await this.vmService.on("Stdout", (event: VMWriteEvent) => this.handleStdoutEvent(event)).catch((e) => {
// Some embedders may not provide Stdout and it's not clear if they will throw, so
// just catch/log errors here.
this.logger.info(errorMessageWithStack(e));
});
}
}
protected async terminate(force: boolean): Promise<void> {
const signal = force ? "SIGKILL" : "SIGINT";
const request = force ? "DISC" : "TERM";
this.log(`${request}: Requested to terminate with ${signal}...`);
if (this.childProcess && !this.processExited) {
this.log(`${request}: Terminating processes...`);
for (const pid of this.additionalPidsToTerminate) {
if (pid === this.childProcess.pid)
continue;
try {
this.log(`${request}: Terminating related process ${pid} with ${signal}...`);
process.kill(pid, signal);
// Don't remove these PIDs from the list as we don't know that they actually quit yet.
} catch (e) {
// Sometimes this process will have already gone away (eg. the app finished/terminated)
// so logging here just results in lots of useless info.
}
}
if (!this.processExited) {
if (this.childProcess.pid) {
try {
this.log(`${request}: Terminating main process with ${signal}...`);
process.kill(this.childProcess.pid, signal);
} catch (e) {
// This tends to throw a lot because the shell process quit when we terminated the related
// VM process above, so just swallow the error.
}
} else {
this.log(`${request}: Process had no PID.`);
}
// If we didn't quit, it might be because we're paused.
await this.tryRemoveAllBreakpointsAndResumeAllThreads(request);
} else {
this.log(`${request}: Main process had already quit.`);
}
// Don't do this - because the process might ignore our kill (eg. test framework lets the current
// test finish) so we may need to send again it we get another disconnectRequest.
// We also use !childProcess to mean we're attached.
// this.childProcess = undefined;
} else {
this.log(`${request}: Did not need to terminate processes`);
}
this.log(`${request}: Removing all stored data...`);
this.threadManager.removeAllStoredData();
this.log(`${request}: Waiting for process to finish...`);
await this.processExit;
this.log(`${request}: Disconnecting...`);
}
// When shutting down, we may need to remove all breakpoints and resume all threads
// to avoid things like waiting for tests to exit that will never exit. We don't wait
// for any responses here as if the VM has shut down we won't get them.
private async tryRemoveAllBreakpointsAndResumeAllThreads(request: string) {
this.log(`${request}: Disabling break-on-exception and removing all breakpoints`);
await this.raceIgnoringErrors(() => Promise.all([
this.threadManager.setExceptionPauseMode("None"),
...this.threadManager.threads.map((thread) => thread.removeAllBreakpoints()),
]));
this.log(`${request}: Unpausing all threads...`);
await this.raceIgnoringErrors(() => Promise.all([
...this.threadManager.threads.map((thread) => thread.resume()),
]));
}
// Run some code, but don't wait longer than a certain time period for the result
// as it may never come. Returns true if the operation completed.
private async raceIgnoringErrors(action: () => Promise<any>, timeoutMilliseconds = 250): Promise<boolean> {
try {
await this.withTimeout(action(), timeoutMilliseconds);
return true;
} catch (e) {
this.log(`Error while while waiting for action: ${e}`);
return false;
}
}
protected async terminateRequest(
response: DebugProtocol.TerminateResponse,
args: DebugProtocol.TerminateArguments,
): Promise<void> {
this.log(`Termination requested!`);
this.isTerminating = true;
this.startProgress(debugTerminatingProgressId, "Terminating debug session");
if (this.expectAdditionalPidToTerminate && !this.additionalPidsToTerminate.size) {
this.log(`Waiting for main process PID before terminating`);
this.updateProgress(debugTerminatingProgressId, "Waiting for process");
const didGetPid = await this.raceIgnoringErrors(() => this.additionalPidCompleter.promise, 20000);
if (didGetPid)
this.log(`Got main process PID, continuing...`);
else
this.log(`Timed out waiting for main process PID, continuing anyway...`);
this.updateProgress(debugTerminatingProgressId, "Terminating process");
}
// If we wait for terminate() to complete, VS code will report a timeout after 1000ms
// so we have to acknowledge the request even if it takes longer to complete.
super.terminateRequest(response, args);
try {
await this.terminate(false);
} catch (e: any) {
this.logger.error(e);
this.logToUser(errorMessage(e));
}
}
protected async disconnectRequest(
response: DebugProtocol.DisconnectResponse,
args: DebugProtocol.DisconnectArguments,
): Promise<void> {
this.log(`Disconnect requested!`);
this.isTerminating = true;
try {
const succeeded = await this.raceIgnoringErrors(() => this.terminate(false), 2000);
// If we hit the 2s timeout, then terminate more forcefully.
if (!succeeded)
await this.terminate(true);
} catch (e) {
return this.errorResponse(response, `${e}`);
}
// If we call super.disconnectRequest before other async code finishes, the TerminatedEvent()
// might not be sent, so wait as least as long as the code in the processExit handler, which is
// just a setImmediate after the last logging event (capped at 500).
await this.raceIgnoringErrors(() => this.lastLoggingEvent, 500);
await new Promise((resolve) => setTimeout(resolve, 10));
super.disconnectRequest(response, args);
}
protected async setBreakPointsRequest(
response: DebugProtocol.SetBreakpointsResponse,
args: DebugProtocol.SetBreakpointsArguments,
): Promise<void> {
if (this.noDebug) {
response.body = { breakpoints: (args.breakpoints || []).map((b) => ({ verified: false })) };
this.sendResponse(response);
return;
}
const source: DebugProtocol.Source = args.source;
const breakpoints: DebugProtocol.SourceBreakpoint[] = args.breakpoints || [];
// Format the path correctly for the VM.
// TODO: The `|| source.name` stops a crash (#1566) but doesn't actually make
// the breakpoints work. This needs more work.
const uri = formatPathForVm(source.path || source.name!);
try {
const result = await this.threadManager.setBreakpoints(uri, breakpoints);
const bpResponse = [];
for (const bpRes of result) {
bpResponse.push({ verified: !!bpRes });
}
response.body = { breakpoints: bpResponse };
this.sendResponse(response);
} catch (error) {
this.errorResponse(response, `${error}`);
}
}
protected async setExceptionBreakPointsRequest(
response: DebugProtocol.SetExceptionBreakpointsResponse,
args: DebugProtocol.SetExceptionBreakpointsArguments,
): Promise<void> {
const filters: string[] = args.filters;
let mode: VmExceptionMode = "None";
// If we're running in noDebug mode, we'll always set None.
if (!this.noDebug) {
if (filters.includes("Unhandled"))
mode = "Unhandled";
if (filters.includes("All"))
mode = "All";
}
await this.threadManager.setExceptionPauseMode(mode);
this.sendResponse(response);
}
protected configurationDoneRequest(
response: DebugProtocol.ConfigurationDoneResponse,
args: DebugProtocol.ConfigurationDoneArguments,
): void {
this.sendResponse(response);
this.threadManager.receivedConfigurationDone();
}
protected pauseRequest(response: DebugProtocol.PauseResponse, args: DebugProtocol.PauseArguments): void {
const thread = this.threadManager.getThreadInfoFromNumber(args.threadId);
if (!thread) {
this.errorResponse(response, `No thread with id ${args.threadId}`);
return;
}
if (!this.vmService) {
this.errorResponse(response, `No VM service connection`);
return;
}
this.vmService.pause(thread.ref.id)
.then(() => {
this.sendResponse(response);
})
.catch((error) => this.errorResponse(response, `${error}`));
}
protected sourceRequest(response: DebugProtocol.SourceResponse, args: DebugProtocol.SourceArguments): void {
const sourceReference = args.sourceReference;
const data = this.threadManager.getStoredData(sourceReference);
const scriptRef: VMScriptRef = data.data as VMScriptRef;
data.thread.getScript(scriptRef).then((script: VMScript) => {
if (script.source) {
response.body = { content: script.source, mimeType: "text/x-dart" };
} else {
response.success = false;
response.message = "<source not available>";
}
this.sendResponse(response);
}).catch((error) => this.errorResponse(response, `${error}`));
}
protected threadsRequest(response: DebugProtocol.ThreadsResponse): void {
response.body = { threads: this.threadManager.getThreads() };
this.sendResponse(response);
}
protected async stackTraceRequest(response: DebugProtocol.StackTraceResponse, args: DebugProtocol.StackTraceArguments): Promise<void> {
const stackFrameBatch = 20;
const thread = this.threadManager.getThreadInfoFromNumber(args.threadId);
const startFrame = args.startFrame || 0;
const levels = args.levels;
if (!thread) {
this.errorResponse(response, `No thread with id ${args.threadId}`);
return;
}
if (!thread.paused) {
this.errorResponse(response, `Thread ${args.threadId} is not paused`);
return;
}
if (!this.vmService) {
this.errorResponse(response, `No VM service connection`);
return;
}
try {
let isTruncated: boolean;
let totalFrames: number;
let stackFrames: DebugProtocol.StackFrame[] = [];
// Newer VM Service allows us to cap the frames to avoid fetching more than we need.
// They do not support an offset, however earlier frames will be internally cached
// so fetching 40 frames if we've already had 0-20 should only incur the cost of the
// new 20.
const supportsGetStackLimit = this.vmServiceCapabilities.supportsGetStackLimit;
const limit = supportsGetStackLimit && levels
? startFrame + levels
: undefined;
// If the request is only for the top frame, we may be able to satisfy this using the
// `topFrame` field of the pause event.
if (startFrame === 0 && levels === 1 && thread.pauseEvent?.topFrame) {
totalFrames = 1 + stackFrameBatch; // Claim we had more +stackFrameBatch frames to force another request.
stackFrames.push(await this.convertStackFrame(thread, thread.pauseEvent?.topFrame, true, true, Infinity));
} else {
const result = await this.vmService.getStack(thread.ref.id, limit);
const stack: VMStack = result.result as VMStack;
let vmFrames = stack.asyncCausalFrames || stack.frames;
const framesReceived = vmFrames.length;
isTruncated = stack.truncated ?? false;
let firstAsyncMarkerIndex = vmFrames.findIndex((f) => f.kind === "AsyncSuspensionMarker");
if (firstAsyncMarkerIndex === -1)
firstAsyncMarkerIndex = Infinity;
// Drop frames that are earlier than what we wanted.
vmFrames = vmFrames.slice(startFrame);
// Drop off any that are after where we wanted.
if (levels && vmFrames.length > levels)
vmFrames = vmFrames.slice(0, levels);
const hasAnyDebuggableFrames = !!vmFrames.find((f) => f.location?.script?.uri && this.isDebuggable(f.location?.script?.uri));
stackFrames = await Promise.all(vmFrames.map((f, i) => this.convertStackFrame(thread, f, startFrame + i === 0, hasAnyDebuggableFrames, firstAsyncMarkerIndex)));
totalFrames = supportsGetStackLimit
// If the stack was truncated, we should say there are 20(stackFrameBatch) more frames, otherwise use the real count.
? isTruncated ? framesReceived + stackFrameBatch : framesReceived
// If we don't support limit, the number received is always correct.
: framesReceived;
}
response.body = {
stackFrames,
totalFrames,
};
this.sendResponse(response);
} catch (error) {
this.errorResponse(response, `${error}`);
}
}
private async convertStackFrame(thread: ThreadInfo, frame: VMFrame, isTopFrame: boolean, hasDebuggableFrames: boolean, firstAsyncMarkerIndex: number): Promise<DebugProtocol.StackFrame> {
const frameId = thread.storeData(frame);
if (frame.kind === "AsyncSuspensionMarker") {
const stackFrame: DebugProtocol.StackFrame = new StackFrame(frameId, "<asynchronous gap>");
stackFrame.presentationHint = "label";
return stackFrame;
}
const frameName =
frame && frame.code && frame.code.name
? (
frame.code.name.startsWith(unoptimizedPrefix)
? frame.code.name.substring(unoptimizedPrefix.length)
: frame.code.name
)
: "<unknown>";
const location = frame.location;
if (!location) {
const stackFrame: DebugProtocol.StackFrame = new StackFrame(frameId, frameName);
stackFrame.presentationHint = "subtle";
return stackFrame;
}
const uri = location.script.uri;
let sourcePath = this.convertVMUriToSourcePath(uri);
let canShowSource = sourcePath && fs.existsSync(sourcePath);
// Download the source if from a "dart:" uri.
let sourceReference: number | undefined;
if (uri.startsWith("dart:") || uri.startsWith("org-dartlang-app:")) {
sourcePath = undefined;
sourceReference = thread.storeData(location.script);
canShowSource = true;
}
const shortName = this.formatUriForShortDisplay(uri);
const stackFrame: DebugProtocol.StackFrame = new StackFrame(
frameId,
frameName,
canShowSource ? new Source(shortName, sourcePath, sourceReference, undefined, location.script) : undefined,
0, 0,
);
// The top frame is only allowed to be deemphasized when it's an exception and there is some user-code in the
// stack (so the editor can walk up the stack to user code).
// If the reason for stopping was a breakpoint, step, etc., then we should always leave the frame focusable.
const isStoppedAtException = thread.exceptionReference !== 0;
const allowDeemphasizingFrame = !isTopFrame || (isStoppedAtException && hasDebuggableFrames);
// If we wouldn't debug this source, then deemphasize in the stack.
if (stackFrame.source) {
if (this.isSdkLibrary(uri))
stackFrame.source.origin = "from the SDK";
else if (this.isExternalLibrary(uri))
stackFrame.source.origin = uri.startsWith("package:flutter/") ? "from the Flutter framework" : "from external packages";
if (allowDeemphasizingFrame && !this.isDebuggable(uri))
stackFrame.source.presentationHint = "deemphasize";
}
stackFrame.canRestart = !isTopFrame && frame.index < firstAsyncMarkerIndex;
// Resolve the line and column information.
if (location.line && location.column) {
stackFrame.line = location.line;
stackFrame.column = location.column;
} else {
try {
const script = await thread.getScript(location.script);
const fileLocation = this.resolveFileLocation(script, location.tokenPos);
if (fileLocation) {
stackFrame.line = fileLocation.line;
stackFrame.column = fileLocation.column;
}
} catch (e) {
this.logger.error(e);
}
}
return stackFrame;
}
private isDebuggable(uri: string): boolean {
if (this.isSdkLibrary(uri))
return this.debugSdkLibraries;
if (this.isExternalLibrary(uri))
return this.debugExternalPackageLibraries;
return true;
}
protected scopesRequest(response: DebugProtocol.ScopesResponse, args: DebugProtocol.ScopesArguments): void {
const frameId = args.frameId;
const data = this.threadManager.getStoredData(frameId);
const frame: VMFrame = data.data as VMFrame;
// TODO: class variables? library variables?
const variablesReference = data.thread.storeData(frame);
const scopes: Scope[] = [];
if (data.thread.exceptionReference) {
scopes.push(new Scope("Exceptions", data.thread.exceptionReference));
}
scopes.push(new Scope("Locals", variablesReference));
response.body = { scopes };
this.sendResponse(response);
}
protected async variablesRequest(response: DebugProtocol.VariablesResponse, args: DebugProtocol.VariablesArguments): Promise<void> {
if (!this.vmService) {
this.errorResponse(response, `No VM service connection`);
return;
}
const variablesReference = args.variablesReference;
// implement paged arrays
// let filter = args.filter; // optional; either "indexed" or "named"
const requestedStart = args.start; // (optional) index of the first variable to return; if omitted children start at 0
const startNumeric = requestedStart || 0;
const requestedCount = args.count; // (optional) number of variables to return. If count is missing or 0, all variables are returned
const data = this.threadManager.getStoredData(variablesReference);
if (!data) {
this.errorResponse(response, `Variable is no longer available (maybe debug session finished?)`);
return;
}
const thread = data.thread;
if (data.data.type === "Frame") {
const frame: VMFrame = data.data as VMFrame;
let variables: DebugProtocol.Variable[] = [];
if (frame.vars) {
const framePromises = frame.vars
.filter((variable) => !variable.value || variable.value.type !== "@TypeArguments")
.map((variable, i) => this.instanceRefToVariable(thread, true, variable.name, variable.name, variable.value, i <= maxValuesToCallToString));
const frameVariables = await Promise.all(framePromises);
variables = variables.concat(frameVariables);
}
variables = sortBy(variables, (v) => v.name);
response.body = { variables };
this.sendResponse(response);
} else if (data.data.type === "MapEntry") {
const mapRef = data.data as VMMapEntry;
const keyResult = this.vmService.getObject(thread.ref.id, mapRef.keyId);
const valueResult = this.vmService.getObject(thread.ref.id, mapRef.valueId);
const variables: DebugProtocol.Variable[] = [];
let canEvaluateValueName = false;
let valueEvaluateName = "value";
try {
const keyDebuggerResult = await keyResult;
const keyInstanceRef = keyDebuggerResult.result as VMInstanceRef;
variables.push(await this.instanceRefToVariable(thread, false, "key", "key", keyInstanceRef, true));
if (this.isSimpleKind(keyInstanceRef.kind) && mapRef.mapEvaluateName) {
canEvaluateValueName = true;
valueEvaluateName = `${mapRef.mapEvaluateName}[${this.valueAsString(keyInstanceRef)}]`;
}
} catch (error) {
variables.push({ name: "key", value: this.errorAsDisplayValue(error), variablesReference: 0 });
}
try {
const valueDebuggerResult = await valueResult;
const valueInstanceRef = valueDebuggerResult.result as VMInstanceRef;
variables.push(await this.instanceRefToVariable(thread, canEvaluateValueName, valueEvaluateName, "value", valueInstanceRef, true));
} catch (error) {
variables.push({ name: "value", value: this.errorAsDisplayValue(error), variablesReference: 0 });
}
response.body = { variables };
this.sendResponse(response);
} else if (data.data.type === InspectedVariable.type) {
const variable = data.data as InspectedVariable;
response.body = {
variables: [
{ name: "insp", value: "<inspected variable>", variablesReference: variable.variablesReference },
],
};
this.sendResponse(response);
} else {
const instanceRef = data.data as InstanceWithEvaluateName;
try {
const result = await this.vmService.getObject(thread.ref.id, instanceRef.id, requestedStart, requestedCount);
let variables: DebugProtocol.Variable[] = [];
// If we're the top-level exception, or our parent has an evaluateName of undefined (its children)
// we cannot evaluate (this will disable "Add to Watch" etc).
const canEvaluate = instanceRef.evaluateName !== undefined;
if (result.result.type === "Sentinel") {
variables.push({
name: "<evalError>",
value: (result.result as VMSentinel).valueAsString,
variablesReference: 0,
});
} else {
const obj: VMObj = result.result as VMObj;
if (obj.type === "Instance") {
const instance = obj as VMInstance;
// TODO: show by kind instead
if (this.isSimpleKind(instance.kind)) {
variables.push(await this.instanceRefToVariable(thread, canEvaluate, `${instanceRef.evaluateName}`, instance.kind, instanceRef, true));
} else if (instance.elements) {
const elementPromises = instance.elements.map(async (element: VMInstanceRef | VMSentinel, i) => this.instanceRefToVariable(thread, canEvaluate, `${instanceRef.evaluateName}[${i + startNumeric}]`, `[${i + startNumeric}]`, element, i <= maxValuesToCallToString));
// Add them in order.
const elementVariables = await Promise.all(elementPromises);
variables = variables.concat(elementVariables);
} else if (instance.associations) {
const len = instance.associations.length;
for (let i = 0; i < len; i++) {
const association = instance.associations[i];
const keyName = this.valueAsString(association.key, true);
const valueName = this.valueAsString(association.value, true);
let variablesReference = 0;
if (association.key.type !== "Sentinel" && association.value.type !== "Sentinel") {
const mapRef: VMMapEntry = {
keyId: (association.key as VMInstanceRef).id,
mapEvaluateName: instanceRef.evaluateName,
type: "MapEntry",
valueId: (association.value as VMInstanceRef).id,
};
variablesReference = thread.storeData(mapRef);
}
variables.push({
name: `${i + startNumeric}`,
type: `${keyName} -> ${valueName}`,
value: `${keyName} -> ${valueName}`,
variablesReference,
});
}
} else if (instance.fields) {
const fieldAndGetterPromises: Array<Promise<DebugProtocol.Variable>> = [];
const fields = sortBy(instance.fields, (f) => f.decl?.name ?? f.name);
const fieldPromises = fields.map(async (field, i) => {
const name = field.decl?.name ?? (typeof field.name === "number" ? `\$${field.name}` : field.name);
return this.instanceRefToVariable(thread, canEvaluate, `${instanceRef.evaluateName}.${name}`, name, field.value, i <= maxValuesToCallToString);
});
fieldAndGetterPromises.push(...fieldPromises);
// Add getters
if (this.evaluateGettersInDebugViews && instance.class) {
let getterNames = await this.getGetterNamesForHierarchy(thread.ref, instance.class);
getterNames = getterNames.sort();
// Call each getter, adding the result as a variable.
const getterPromises = getterNames.map(async (getterName, i) => {
try {
const getterResult = await this.vmService!.evaluate(thread.ref.id, instanceRef.id, getterName, true);
if (getterResult.result.type === "@Error") {
const message = (getterResult.result as VMErrorRef).message.replace("Unhandled exception:", "").trim();
return {
name: getterName,
value: `<${message}>`,
variablesReference: 0,
};