This repository has been archived by the owner on Oct 2, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 119
/
chromeDebugAdapter.ts
2438 lines (2079 loc) · 107 KB
/
chromeDebugAdapter.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
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
/*---------------------------------------------------------
* Copyright (C) Microsoft Corporation. All rights reserved.
*--------------------------------------------------------*/
import {DebugProtocol} from 'vscode-debugprotocol';
import {InitializedEvent, TerminatedEvent, Handles, ContinuedEvent, BreakpointEvent, OutputEvent, Logger, logger, LoadedSourceEvent} from 'vscode-debugadapter';
import {ICommonRequestArgs, ILaunchRequestArgs, ISetBreakpointsArgs, ISetBreakpointsResponseBody, IStackTraceResponseBody,
IAttachRequestArgs, IScopesResponseBody, IVariablesResponseBody,
ISourceResponseBody, IThreadsResponseBody, IEvaluateResponseBody, ISetVariableResponseBody, IDebugAdapter,
ICompletionsResponseBody, IToggleSkipFileStatusArgs, IInternalStackTraceResponseBody, IGetLoadedSourcesResponseBody,
IExceptionInfoResponseBody, ISetBreakpointResult, TimeTravelRuntime, IRestartRequestArgs, IInitializeRequestArgs} from '../debugAdapterInterfaces';
import {IChromeDebugAdapterOpts, ChromeDebugSession} from './chromeDebugSession';
import {ChromeConnection} from './chromeConnection';
import * as ChromeUtils from './chromeUtils';
import Crdp from '../../crdp/crdp';
import {PropertyContainer, ScopeContainer, ExceptionContainer, isIndexedPropName} from './variables';
import * as variables from './variables';
import {formatConsoleArguments, formatExceptionDetails} from './consoleHelper';
import {StoppedEvent2, ReasonType} from './stoppedEvent';
import * as errors from '../errors';
import * as utils from '../utils';
import {telemetry} from '../telemetry';
import {LineColTransformer} from '../transformers/lineNumberTransformer';
import {BasePathTransformer} from '../transformers/basePathTransformer';
import {RemotePathTransformer} from '../transformers/remotePathTransformer';
import {BaseSourceMapTransformer} from '../transformers/baseSourceMapTransformer';
import {EagerSourceMapTransformer} from '../transformers/eagerSourceMapTransformer';
import {FallbackToClientPathTransformer} from '../transformers/fallbackToClientPathTransformer';
import {BreakOnLoadHelper} from './breakOnLoadHelper';
import * as path from 'path';
import * as nls from 'vscode-nls';
let localize = nls.config(process.env.VSCODE_NLS_CONFIG)();
interface IPropCount {
indexedVariables: number;
namedVariables: number;
}
/**
* Represents a reference to a source/script. `contents` is set if there are inlined sources.
* Otherwise, scriptId can be used to retrieve the contents from the runtime.
*/
export interface ISourceContainer {
/** The runtime-side scriptId of this script */
scriptId?: Crdp.Runtime.ScriptId;
/** The contents of this script, if they are inlined in the sourcemap */
contents?: string;
/** The authored path to this script (only set if the contents are inlined) */
mappedPath?: string;
}
export interface IPendingBreakpoint {
args: ISetBreakpointsArgs;
ids: number[];
requestSeq: number;
bpsSet: boolean;
}
interface IHitConditionBreakpoint {
numHits: number;
shouldPause: (numHits: number) => boolean;
}
export type VariableContext = 'variables' | 'watch' | 'repl' | 'hover';
export type CrdpScript = Crdp.Debugger.ScriptParsedEvent;
export type CrdpDomain = keyof Crdp.CrdpClient;
export type LoadedSourceEventReason = 'new' | 'changed' | 'removed';
export abstract class ChromeDebugAdapter implements IDebugAdapter {
public static EVAL_NAME_PREFIX = ChromeUtils.EVAL_NAME_PREFIX;
public static EVAL_ROOT = '<eval>';
private static SCRIPTS_COMMAND = '.scripts';
private static THREAD_ID = 1;
private static SET_BREAKPOINTS_TIMEOUT = 5000;
private static HITCONDITION_MATCHER = /^(>|>=|=|<|<=|%)?\s*([0-9]+)$/;
private static ASYNC_CALL_STACK_DEPTH = 4;
protected _session: ChromeDebugSession;
protected _domains = new Map<CrdpDomain, Crdp.Schema.Domain>();
private _clientAttached: boolean;
private _currentPauseNotification: Crdp.Debugger.PausedEvent;
private _committedBreakpointsByUrl: Map<string, Crdp.Debugger.BreakpointId[]>;
private _exception: Crdp.Runtime.RemoteObject;
private _setBreakpointsRequestQ: Promise<any>;
private _expectingResumedEvent: boolean;
protected _expectingStopReason: ReasonType;
private _waitAfterStep = Promise.resolve();
private _frameHandles: Handles<Crdp.Debugger.CallFrame>;
private _variableHandles: variables.VariableHandles;
private _breakpointIdHandles: utils.ReverseHandles<Crdp.Debugger.BreakpointId>;
private _sourceHandles: utils.ReverseHandles<ISourceContainer>;
private _scriptsById: Map<Crdp.Runtime.ScriptId, CrdpScript>;
private _scriptsByUrl: Map<string, CrdpScript>;
private _pendingBreakpointsByUrl: Map<string, IPendingBreakpoint>;
private _hitConditionBreakpointsById: Map<Crdp.Debugger.BreakpointId, IHitConditionBreakpoint>;
private _lineColTransformer: LineColTransformer;
protected _chromeConnection: ChromeConnection;
protected _sourceMapTransformer: BaseSourceMapTransformer;
protected _pathTransformer: BasePathTransformer;
protected _hasTerminated: boolean;
protected _inShutdown: boolean;
protected _attachMode: boolean;
protected _launchAttachArgs: ICommonRequestArgs;
protected _port: number;
private _blackboxedRegexes: RegExp[] = [];
private _skipFileStatuses = new Map<string, boolean>();
private _caseSensitivePaths = true;
private _currentStep = Promise.resolve();
private _currentLogMessage = Promise.resolve();
private _nextUnboundBreakpointId = 0;
private _pauseOnPromiseRejections = true;
protected _promiseRejectExceptionFilterEnabled = false;
private _columnBreakpointsEnabled: boolean;
private _smartStepCount = 0;
private _earlyScripts: Crdp.Debugger.ScriptParsedEvent[] = [];
private _initialSourceMapsP = Promise.resolve();
private _lastPauseState: { expecting: ReasonType; event: Crdp.Debugger.PausedEvent };
private _breakOnLoadHelper: BreakOnLoadHelper | null;
// Queue to synchronize new source loaded and source removed events so that 'remove' script events
// won't be send before the corresponding 'new' event has been sent
private _sourceLoadedQueue: Promise<void> = Promise.resolve(null);
public constructor({ chromeConnection, lineColTransformer, sourceMapTransformer, pathTransformer, targetFilter, enableSourceMapCaching }: IChromeDebugAdapterOpts, session: ChromeDebugSession) {
telemetry.setupEventHandler(e => session.sendEvent(e));
this._session = session;
this._chromeConnection = new (chromeConnection || ChromeConnection)(undefined, targetFilter);
this._frameHandles = new Handles<Crdp.Debugger.CallFrame>();
this._variableHandles = new variables.VariableHandles();
this._breakpointIdHandles = new utils.ReverseHandles<Crdp.Debugger.BreakpointId>();
this._sourceHandles = new utils.ReverseHandles<ISourceContainer>();
this._pendingBreakpointsByUrl = new Map<string, IPendingBreakpoint>();
this._hitConditionBreakpointsById = new Map<Crdp.Debugger.BreakpointId, IHitConditionBreakpoint>();
this._lineColTransformer = new (lineColTransformer || LineColTransformer)(this._session);
this._sourceMapTransformer = new (sourceMapTransformer || EagerSourceMapTransformer)(this._sourceHandles, enableSourceMapCaching);
this._pathTransformer = new (pathTransformer || RemotePathTransformer)();
this.clearTargetContext();
}
public get chrome(): Crdp.CrdpClient {
return this._chromeConnection.api;
}
public get scriptsById(): Map<Crdp.Runtime.ScriptId, CrdpScript> {
return this._scriptsById;
}
public get pathTransformer(): BasePathTransformer {
return this._pathTransformer;
}
public get pendingBreakpointsByUrl(): Map<string, IPendingBreakpoint> {
return this._pendingBreakpointsByUrl;
}
public get sourceMapTransformer(): BaseSourceMapTransformer{
return this._sourceMapTransformer;
}
/**
* Called on 'clearEverything' or on a navigation/refresh
*/
protected clearTargetContext(): void {
this._sourceMapTransformer.clearTargetContext();
this._scriptsById = new Map<Crdp.Runtime.ScriptId, Crdp.Debugger.ScriptParsedEvent>();
this._scriptsByUrl = new Map<string, Crdp.Debugger.ScriptParsedEvent>();
this._committedBreakpointsByUrl = new Map<string, Crdp.Debugger.BreakpointId[]>();
this._setBreakpointsRequestQ = Promise.resolve();
this._pathTransformer.clearTargetContext();
}
public initialize(args: IInitializeRequestArgs): DebugProtocol.Capabilities {
if (args.supportsMapURLToFilePathRequest) {
this._pathTransformer = new FallbackToClientPathTransformer(this._session);
}
this._caseSensitivePaths = args.clientID !== 'visualstudio';
if (args.pathFormat !== 'path') {
throw errors.pathFormat();
}
if (args.locale) {
localize = nls.config({ locale: args.locale })();
}
// because session bypasses dispatchRequest
if (typeof args.linesStartAt1 === 'boolean') {
(<any>this)._clientLinesStartAt1 = args.linesStartAt1;
}
if (typeof args.columnsStartAt1 === 'boolean') {
(<any>this)._clientColumnsStartAt1 = args.columnsStartAt1;
}
const exceptionBreakpointFilters = [
{
label: localize('exceptions.all', "All Exceptions"),
filter: 'all',
default: false
},
{
label: localize('exceptions.uncaught', "Uncaught Exceptions"),
filter: 'uncaught',
default: false
}
];
if (this._promiseRejectExceptionFilterEnabled) {
exceptionBreakpointFilters.push({
label: localize('exceptions.promise_rejects', "Promise Rejects"),
filter: 'promise_reject',
default: false
});
}
// This debug adapter supports two exception breakpoint filters
return {
exceptionBreakpointFilters,
supportsConfigurationDoneRequest: true,
supportsSetVariable: true,
supportsConditionalBreakpoints: true,
supportsCompletionsRequest: true,
supportsHitConditionalBreakpoints: true,
supportsRestartFrame: true,
supportsExceptionInfoRequest: true,
supportsDelayedStackTraceLoading: true,
supportsValueFormattingOptions: true
};
}
public configurationDone(): Promise<void> {
return Promise.resolve();
}
public get breakOnLoadActive(): boolean {
return !!this._breakOnLoadHelper;
}
public launch(args: ILaunchRequestArgs): Promise<void> {
this.commonArgs(args);
this._sourceMapTransformer.launch(args);
this._pathTransformer.launch(args);
if (args.breakOnLoadStrategy && args.breakOnLoadStrategy !== 'off') {
this._breakOnLoadHelper = new BreakOnLoadHelper(this, args.breakOnLoadStrategy);
}
if (!args.__restart) {
/* __GDPR__
"debugStarted" : {
"request" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
"args" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }
}
*/
telemetry.reportEvent('debugStarted', { request: 'launch', args: Object.keys(args) });
}
return Promise.resolve();
}
public attach(args: IAttachRequestArgs): Promise<void> {
this._attachMode = true;
this.commonArgs(args);
this._sourceMapTransformer.attach(args);
this._pathTransformer.attach(args);
if (!args.port) {
args.port = 9229;
}
/* __GDPR__
"debugStarted" : {
"request" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
"args" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }
}
*/
telemetry.reportEvent('debugStarted', { request: 'attach', args: Object.keys(args) });
return this.doAttach(args.port, args.url, args.address, args.timeout, args.websocketUrl, args.extraCRDPChannelPort);
}
protected commonArgs(args: ICommonRequestArgs): void {
let logToFile = false;
let logLevel: Logger.LogLevel;
if (args.trace === 'verbose') {
logLevel = Logger.LogLevel.Verbose;
logToFile = true;
} else if (args.trace) {
logLevel = Logger.LogLevel.Warn;
logToFile = true;
} else {
logLevel = Logger.LogLevel.Warn;
}
// The debug configuration provider should have set logFilePath on the launch config. If not, default to 'true' to use the
// "legacy" log file path from the CDA subclass
const logFilePath = args.logFilePath || logToFile;
logger.setup(logLevel, logFilePath);
this._launchAttachArgs = args;
// Enable sourcemaps and async callstacks by default
args.sourceMaps = typeof args.sourceMaps === 'undefined' || args.sourceMaps;
}
public shutdown(): void {
this._inShutdown = true;
this._session.shutdown();
}
protected async terminateSession(reason: string, disconnectArgs?: DebugProtocol.DisconnectArguments, restart?: IRestartRequestArgs): Promise<void> {
logger.log(`Terminated: ${reason}`);
if (!this._hasTerminated) {
logger.log(`Waiting for any pending steps or log messages.`);
await this._currentStep;
await this._currentLogMessage;
logger.log(`Current step and log messages complete`);
/* __GDPR__
"debugStopped" : {
"reason" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }
}
*/
telemetry.reportEvent('debugStopped', { reason });
this._hasTerminated = true;
if (this._clientAttached || (this._launchAttachArgs && (<ILaunchRequestArgs>this._launchAttachArgs).noDebug)) {
this._session.sendEvent(new TerminatedEvent(restart));
}
if (this._chromeConnection.isAttached) {
this._chromeConnection.close();
}
}
}
/**
* Hook up all connection events
*/
protected hookConnectionEvents(): void {
this.chrome.Debugger.onPaused(params => this.onPaused(params));
this.chrome.Debugger.onResumed(() => this.onResumed());
this.chrome.Debugger.onScriptParsed(params => this.onScriptParsed(params));
this.chrome.Debugger.onBreakpointResolved(params => this.onBreakpointResolved(params));
this.chrome.Console.onMessageAdded(params => this.onMessageAdded(params));
this.chrome.Runtime.onConsoleAPICalled(params => this.onConsoleAPICalled(params));
this.chrome.Runtime.onExceptionThrown(params => this.onExceptionThrown(params));
this.chrome.Runtime.onExecutionContextsCleared(() => this.onExecutionContextsCleared());
this._chromeConnection.onClose(() => this.terminateSession('websocket closed'));
}
/**
* Enable clients and run connection
*/
protected runConnection(): Promise<void>[] {
return [
this.chrome.Console.enable()
.catch(e => { /* Specifically ignore a fail here since it's only for backcompat */ }),
utils.toVoidP(this.chrome.Debugger.enable()),
this.chrome.Runtime.enable(),
this._chromeConnection.run()
];
}
protected async doAttach(port: number, targetUrl?: string, address?: string, timeout?: number, websocketUrl?: string, extraCRDPChannelPort?: number): Promise<void> {
// Client is attaching - if not attached to the chrome target, create a connection and attach
this._clientAttached = true;
if (!this._chromeConnection.isAttached) {
if (websocketUrl) {
await this._chromeConnection.attachToWebsocketUrl(websocketUrl, extraCRDPChannelPort);
} else {
await this._chromeConnection.attach(address, port, targetUrl, timeout, extraCRDPChannelPort);
}
this._port = port;
this.hookConnectionEvents();
let patterns: string[] = [];
if (this._launchAttachArgs.skipFiles) {
const skipFilesArgs = this._launchAttachArgs.skipFiles.filter(glob => {
if (glob.startsWith('!')) {
logger.warn(`Warning: skipFiles entries starting with '!' aren't supported and will be ignored. ("${glob}")`);
return false;
}
return true;
});
patterns = skipFilesArgs.map(glob => utils.pathGlobToBlackboxedRegex(glob));
}
if (this._launchAttachArgs.skipFileRegExps) {
patterns = patterns.concat(this._launchAttachArgs.skipFileRegExps);
}
// Make sure debugging domain is enabled before calling refreshBlackboxPatterns() below
await Promise.all(this.runConnection());
if (patterns.length) {
this._blackboxedRegexes = patterns.map(pattern => new RegExp(pattern, 'i'));
this.refreshBlackboxPatterns();
}
await this.initSupportedDomains();
const maxDepth = this._launchAttachArgs.showAsyncStacks ? ChromeDebugAdapter.ASYNC_CALL_STACK_DEPTH : 0;
try {
return await this.chrome.Debugger.setAsyncCallStackDepth({ maxDepth });
} catch (e) {
// Not supported by older runtimes, ignore it.
return;
}
} else {
return Promise.resolve();
}
}
private async initSupportedDomains(): Promise<void> {
try {
const domainResponse = await this.chrome.Schema.getDomains();
domainResponse.domains.forEach(domain => this._domains.set(<any>domain.name, domain));
} catch (e) {
// If getDomains isn't supported for some reason, skip this
}
}
/**
* This event tells the client to begin sending setBP requests, etc. Some consumers need to override this
* to send it at a later time of their choosing.
*/
protected async sendInitializedEvent(): Promise<void> {
// Wait to finish loading sourcemaps from the initial scriptParsed events
if (this._initialSourceMapsP) {
const initialSourceMapsP = this._initialSourceMapsP;
this._initialSourceMapsP = null;
await initialSourceMapsP;
this._session.sendEvent(new InitializedEvent());
await Promise.all(this._earlyScripts.map(script => this.sendLoadedSourceEvent(script)));
this._earlyScripts = null;
}
}
public doAfterProcessingSourceEvents(action: () => void): Promise<void> {
return this._sourceLoadedQueue = this._sourceLoadedQueue.then(action);
}
/**
* e.g. the target navigated
*/
private onExecutionContextsCleared(): Promise<void> {
const cachedScriptParsedEvents = Array.from(this._scriptsById.values());
return this.doAfterProcessingSourceEvents(async () => { // This will not execute until all the on-flight 'new' source events have been processed
for (let scriptedParseEvent of cachedScriptParsedEvents) {
const scriptEvent = await this.scriptToLoadedSourceEvent('removed', scriptedParseEvent);
this._session.sendEvent(scriptEvent);
}
this.clearTargetContext();
});
}
protected async onPaused(notification: Crdp.Debugger.PausedEvent, expectingStopReason = this._expectingStopReason): Promise<void> {
if (notification.asyncCallStackTraceId) {
await this.chrome.Debugger.pauseOnAsyncCall({ parentStackTraceId: notification.asyncCallStackTraceId });
return this.chrome.Debugger.resume();
}
this._variableHandles.onPaused();
this._frameHandles.reset();
this._exception = undefined;
this._lastPauseState = { event: notification, expecting: expectingStopReason };
this._currentPauseNotification = notification;
// If break on load is active, we pass the notification object to breakonload helper
// If it returns true, we continue and return
if (this.breakOnLoadActive) {
let shouldContinue = await this._breakOnLoadHelper.handleOnPaused(notification);
if (shouldContinue) {
this.chrome.Debugger.resume()
.catch(e => {
logger.error("Failed to resume due to exception: " + e.message);
});
return;
}
}
// We can tell when we've broken on an exception. Otherwise if hitBreakpoints is set, assume we hit a
// breakpoint. If not set, assume it was a step. We can't tell the difference between step and 'break on anything'.
let reason: ReasonType;
let smartStepP = Promise.resolve(false);
if (notification.reason === 'exception') {
reason = 'exception';
this._exception = notification.data;
} else if (notification.reason === 'promiseRejection') {
reason = 'promise_rejection';
// After processing smartStep and so on, check whether we are paused on a promise rejection, and should continue past it
if (this._promiseRejectExceptionFilterEnabled && !this._pauseOnPromiseRejections) {
this.chrome.Debugger.resume()
.catch(e => { /* ignore failures */ });
return;
}
this._exception = notification.data;
} else if (notification.hitBreakpoints && notification.hitBreakpoints.length) {
reason = 'breakpoint';
// Did we hit a hit condition breakpoint?
for (let hitBp of notification.hitBreakpoints) {
if (this._hitConditionBreakpointsById.has(hitBp)) {
// Increment the hit count and check whether to pause
const hitConditionBp = this._hitConditionBreakpointsById.get(hitBp);
hitConditionBp.numHits++;
// Only resume if we didn't break for some user action (step, pause button)
if (!expectingStopReason && !hitConditionBp.shouldPause(hitConditionBp.numHits)) {
this.chrome.Debugger.resume()
.catch(e => { /* ignore failures */ });
return;
}
}
}
} else if (expectingStopReason) {
// If this was a step, check whether to smart step
reason = expectingStopReason;
smartStepP = this.shouldSmartStep(this._currentPauseNotification.callFrames[0]);
} else {
reason = 'debugger_statement';
}
this._expectingStopReason = undefined;
smartStepP.then(should => {
if (should) {
this._smartStepCount++;
return this.stepIn(false);
} else {
if (this._smartStepCount > 0) {
logger.log(`SmartStep: Skipped ${this._smartStepCount} steps`);
this._smartStepCount = 0;
}
// Enforce that the stopped event is not fired until we've sent the response to the step that induced it.
// Also with a timeout just to ensure things keep moving
const sendStoppedEvent = () => {
return this._session.sendEvent(new StoppedEvent2(reason, /*threadId=*/ChromeDebugAdapter.THREAD_ID, this._exception));
};
return utils.promiseTimeout(this._currentStep, /*timeoutMs=*/300)
.then(sendStoppedEvent, sendStoppedEvent);
}
}).catch(err => logger.error('Problem while smart stepping: ' + (err && err.stack) ? err.stack : err));
}
public async exceptionInfo(args: DebugProtocol.ExceptionInfoArguments): Promise<IExceptionInfoResponseBody> {
if (args.threadId !== ChromeDebugAdapter.THREAD_ID) {
throw errors.invalidThread(args.threadId);
}
if (this._exception) {
const isError = this._exception.subtype === 'error';
const message = isError ? utils.firstLine(this._exception.description) : (this._exception.description || this._exception.value);
const formattedMessage = message && message.replace(/\*/g, '\\*');
const response: IExceptionInfoResponseBody = {
exceptionId: this._exception.className || this._exception.type || 'Error',
breakMode: 'unhandled',
details: {
stackTrace: this._exception.description && await this.mapFormattedException(this._exception.description),
message,
formattedDescription: formattedMessage, // VS workaround - see https://github.com/Microsoft/vscode/issues/34259
typeName: this._exception.subtype || this._exception.type
}
};
return response;
} else {
throw errors.noStoredException();
}
}
private async shouldSmartStep(frame: Crdp.Debugger.CallFrame): Promise<boolean> {
if (!this.smartStepEnabled()) return Promise.resolve(false);
const stackFrame = this.callFrameToStackFrame(frame);
const clientPath = this._pathTransformer.getClientPathFromTargetPath(stackFrame.source.path) || stackFrame.source.path;
const mapping = await this._sourceMapTransformer.mapToAuthored(clientPath, frame.location.lineNumber, frame.location.columnNumber);
return !mapping;
}
private smartStepEnabled(): boolean {
return this._launchAttachArgs.smartStep;
}
protected onResumed(): void {
this._currentPauseNotification = null;
if (this._expectingResumedEvent) {
this._expectingResumedEvent = false;
// Need to wait to eval just a little after each step, because of #148
this._waitAfterStep = utils.promiseTimeout(null, 50);
} else {
let resumedEvent = new ContinuedEvent(ChromeDebugAdapter.THREAD_ID);
this._session.sendEvent(resumedEvent);
}
}
private async detectColumnBreakpointSupport(scriptId: Crdp.Runtime.ScriptId): Promise<void> {
this._columnBreakpointsEnabled = false; // So it isn't requested multiple times
try {
await this.chrome.Debugger.getPossibleBreakpoints({
start: { scriptId, lineNumber: 0, columnNumber: 0 },
end: { scriptId, lineNumber: 1, columnNumber: 0 },
restrictToFunction: false
});
this._columnBreakpointsEnabled = true;
} catch (e) {
this._columnBreakpointsEnabled = false;
}
this._lineColTransformer.columnBreakpointsEnabled = this._columnBreakpointsEnabled;
}
protected async onScriptParsed(script: Crdp.Debugger.ScriptParsedEvent): Promise<void> {
this.doAfterProcessingSourceEvents(async () => { // This will block future 'removed' source events, until this processing has been completed
if (typeof this._columnBreakpointsEnabled === 'undefined') {
await this.detectColumnBreakpointSupport(script.scriptId).then(async () => {
await this.sendInitializedEvent();
});
}
if (this._earlyScripts) {
this._earlyScripts.push(script);
} else {
await this.sendLoadedSourceEvent(script);
}
});
if (script.url) {
script.url = utils.fixDriveLetter(script.url);
} else {
script.url = ChromeDebugAdapter.EVAL_NAME_PREFIX + script.scriptId;
}
this._scriptsById.set(script.scriptId, script);
this._scriptsByUrl.set(this.fixPathCasing(script.url), script);
const resolvePendingBPs = (source: string) => {
source = source && this.fixPathCasing(source);
const pendingBP = this._pendingBreakpointsByUrl.get(source);
if (pendingBP && !pendingBP.bpsSet) {
this.resolvePendingBreakpoint(pendingBP)
.then(() => this._pendingBreakpointsByUrl.delete(source));
}
};
const mappedUrl = await this._pathTransformer.scriptParsed(script.url);
const sourceMapsP = this._sourceMapTransformer.scriptParsed(mappedUrl, script.sourceMapURL).then(sources => {
if (this._hasTerminated) {
return undefined;
}
if (sources) {
// If break on load is active, check whether we should call resolvePendingBPs
if (this.breakOnLoadActive) {
sources
.filter(source => source !== mappedUrl && this._breakOnLoadHelper.shouldResolvePendingBPs(source)) // Tools like babel-register will produce sources with the same path as the generated script
.forEach(resolvePendingBPs);
} else {
sources
.filter(source => source !== mappedUrl) // Tools like babel-register will produce sources with the same path as the generated script
.forEach(resolvePendingBPs);
}
}
if (script.url === mappedUrl && this._pendingBreakpointsByUrl.has(mappedUrl) && this._pendingBreakpointsByUrl.get(mappedUrl).bpsSet) {
// If the pathTransformer had no effect, and we attempted to set the BPs with that path earlier, then assume that they are about
// to be resolved in this loaded script, and remove the pendingBP.
this._pendingBreakpointsByUrl.delete(mappedUrl);
} else {
// If break on load is active, check whether we should call resolvePendingBPs
if (!this.breakOnLoadActive || (this._breakOnLoadHelper && !sources && this._breakOnLoadHelper.shouldResolvePendingBPs(mappedUrl))) {
resolvePendingBPs(mappedUrl);
}
}
return this.resolveSkipFiles(script, mappedUrl, sources);
});
if (this._initialSourceMapsP) {
this._initialSourceMapsP = <Promise<any>>Promise.all([this._initialSourceMapsP, sourceMapsP]);
}
}
protected async sendLoadedSourceEvent(script: Crdp.Debugger.ScriptParsedEvent, loadedSourceEventReason: LoadedSourceEventReason = 'new'): Promise<void> {
const scriptEvent = await this.scriptToLoadedSourceEvent(loadedSourceEventReason, script);
this._session.sendEvent(scriptEvent);
}
private async resolveSkipFiles(script: CrdpScript, mappedUrl: string, sources: string[], toggling?: boolean): Promise<void> {
if (sources && sources.length) {
const parentIsSkipped = this.shouldSkipSource(script.url);
const libPositions: Crdp.Debugger.ScriptPosition[] = [];
// Figure out skip/noskip transitions within script
let inLibRange = parentIsSkipped;
const allSources = await this.sourceMapTransformer.allSources(mappedUrl);
for (let s of allSources) {
let isSkippedFile = this.shouldSkipSource(s);
if (typeof isSkippedFile !== 'boolean') {
// Inherit the parent's status
isSkippedFile = parentIsSkipped;
}
this._skipFileStatuses.set(s, isSkippedFile);
if ((isSkippedFile && !inLibRange) || (!isSkippedFile && inLibRange)) {
const details = await this.sourceMapTransformer.allSourcePathDetails(mappedUrl);
const detail = details.find(d => d.inferredPath === s);
libPositions.push({
lineNumber: detail.startPosition.line,
columnNumber: detail.startPosition.column
});
inLibRange = !inLibRange;
}
}
// If there's any change from the default, set proper blackboxed ranges
if (libPositions.length || toggling) {
if (parentIsSkipped) {
libPositions.splice(0, 0, { lineNumber: 0, columnNumber: 0});
}
await this.chrome.Debugger.setBlackboxedRanges({
scriptId: script.scriptId,
positions: []
}).catch(() => this.warnNoSkipFiles());
if (libPositions.length) {
this.chrome.Debugger.setBlackboxedRanges({
scriptId: script.scriptId,
positions: libPositions
}).catch(() => this.warnNoSkipFiles());
}
}
} else {
const status = await this.getSkipStatus(mappedUrl);
const skippedByPattern = this.matchesSkipFilesPatterns(mappedUrl);
if (typeof status === 'boolean' && status !== skippedByPattern) {
const positions = status ? [{ lineNumber: 0, columnNumber: 0 }] : [];
this.chrome.Debugger.setBlackboxedRanges({
scriptId: script.scriptId,
positions
}).catch(() => this.warnNoSkipFiles());
}
}
}
private warnNoSkipFiles(): void {
logger.log('Warning: this runtime does not support skipFiles');
}
/**
* If the source has a saved skip status, return that, whether true or false.
* If not, check it against the patterns list.
*/
private shouldSkipSource(sourcePath: string): boolean|undefined {
const status = this.getSkipStatus(sourcePath);
if (typeof status === 'boolean') {
return status;
}
if (this.matchesSkipFilesPatterns(sourcePath)) {
return true;
}
return undefined;
}
/**
* Returns true if this path matches one of the static skip patterns
*/
private matchesSkipFilesPatterns(sourcePath: string): boolean {
return this._blackboxedRegexes.some(regex => {
return regex.test(sourcePath);
});
}
/**
* Returns the current skip status for this path, which is either an authored or generated script.
*/
private getSkipStatus(sourcePath: string): boolean|undefined {
if (this._skipFileStatuses.has(sourcePath)) {
return this._skipFileStatuses.get(sourcePath);
}
return undefined;
}
public async toggleSkipFileStatus(args: IToggleSkipFileStatusArgs): Promise<void> {
if (args.path) {
args.path = utils.fileUrlToPath(args.path);
}
if (!await this.isInCurrentStack(args)) {
// Only valid for files that are in the current stack
const logName = args.path || this.displayNameForSourceReference(args.sourceReference);
logger.log(`Can't toggle the skipFile status for ${logName} - it's not in the current stack.`);
return;
}
// e.g. strip <node_internals>/
if (args.path) {
args.path = this.displayPathToRealPath(args.path);
}
const aPath = args.path || this.fakeUrlForSourceReference(args.sourceReference);
const generatedPath = await this._sourceMapTransformer.getGeneratedPathFromAuthoredPath(aPath);
if (!generatedPath) {
logger.log(`Can't toggle the skipFile status for: ${aPath} - haven't seen it yet.`);
return;
}
const sources = await this._sourceMapTransformer.allSources(generatedPath);
if (generatedPath === aPath && sources.length) {
// Ignore toggling skip status for generated scripts with sources
logger.log(`Can't toggle skipFile status for ${aPath} - it's a script with a sourcemap`);
return;
}
const newStatus = !this.shouldSkipSource(aPath);
logger.log(`Setting the skip file status for: ${aPath} to ${newStatus}`);
this._skipFileStatuses.set(aPath, newStatus);
const targetPath = this._pathTransformer.getTargetPathFromClientPath(generatedPath);
const script = this.getScriptByUrl(targetPath);
await this.resolveSkipFiles(script, generatedPath, sources, /*toggling=*/true);
if (newStatus) {
this.makeRegexesSkip(script.url);
} else {
this.makeRegexesNotSkip(script.url);
}
this.onPaused(this._lastPauseState.event, this._lastPauseState.expecting);
}
private async isInCurrentStack(args: IToggleSkipFileStatusArgs): Promise<boolean> {
const currentStack = await this.stackTrace({ threadId: undefined });
if (args.path) {
return currentStack.stackFrames.some(frame => frame.source.path === args.path);
} else {
return currentStack.stackFrames.some(frame => frame.source.sourceReference === args.sourceReference);
}
}
private makeRegexesNotSkip(noSkipPath: string): void {
let somethingChanged = false;
this._blackboxedRegexes = this._blackboxedRegexes.map(regex => {
const result = utils.makeRegexNotMatchPath(regex, noSkipPath);
somethingChanged = somethingChanged || (result !== regex);
return result;
});
if (somethingChanged) {
this.refreshBlackboxPatterns();
}
}
private makeRegexesSkip(skipPath: string): void {
let somethingChanged = false;
this._blackboxedRegexes = this._blackboxedRegexes.map(regex => {
const result = utils.makeRegexMatchPath(regex, skipPath);
somethingChanged = somethingChanged || (result !== regex);
return result;
});
if (!somethingChanged) {
this._blackboxedRegexes.push(new RegExp(utils.pathToRegex(skipPath, this._caseSensitivePaths), 'i'));
}
this.refreshBlackboxPatterns();
}
private refreshBlackboxPatterns(): void {
this.chrome.Debugger.setBlackboxPatterns({
patterns: this._blackboxedRegexes.map(regex => regex.source)
}).catch(() => this.warnNoSkipFiles());
}
public async loadedSources(args: DebugProtocol.LoadedSourcesArguments): Promise<IGetLoadedSourcesResponseBody> {
const sources = await Promise.all(Array.from(this._scriptsByUrl.values())
.map(script => this.scriptToSource(script)));
return { sources: sources.sort((a, b) => a.path.localeCompare(b.path)) };
}
public resolvePendingBreakpoint(pendingBP: IPendingBreakpoint): Promise<void> {
return this.setBreakpoints(pendingBP.args, pendingBP.requestSeq, pendingBP.ids).then(response => {
response.breakpoints.forEach((bp, i) => {
bp.id = pendingBP.ids[i];
// If any of the unbound breakpoints in this file is on (1,1), we set userBreakpointOnLine1Col1 to true
if (bp.line === 1 && bp.column === 1 && this.breakOnLoadActive) {
this._breakOnLoadHelper.userBreakpointOnLine1Col1 = true;
}
this._session.sendEvent(new BreakpointEvent('changed', bp));
});
});
}
protected onBreakpointResolved(params: Crdp.Debugger.BreakpointResolvedEvent): void {
const script = this._scriptsById.get(params.location.scriptId);
if (!script) {
// Breakpoint resolved for a script we don't know about
return;
}
// If the breakpoint resolved is a stopOnEntry breakpoint, we just return since we don't need to send it to client
if (this.breakOnLoadActive && this._breakOnLoadHelper.stopOnEntryBreakpointIdToRequestedFileName.has(params.breakpointId)) {
return;
}
const committedBps = this._committedBreakpointsByUrl.get(script.url) || [];
if (committedBps.indexOf(params.breakpointId) === -1) {
committedBps.push(params.breakpointId);
}
this._committedBreakpointsByUrl.set(script.url, committedBps);
const bp = <DebugProtocol.Breakpoint>{
id: this._breakpointIdHandles.lookup(params.breakpointId),
verified: true,
line: params.location.lineNumber,
column: params.location.columnNumber
};
const scriptPath = this._pathTransformer.breakpointResolved(bp, script.url);
if (this._pendingBreakpointsByUrl.has(scriptPath)) {
// If we set these BPs before the script was loaded, remove from the pending list
this._pendingBreakpointsByUrl.delete(scriptPath);
}
this._sourceMapTransformer.breakpointResolved(bp, scriptPath);
this._lineColTransformer.breakpointResolved(bp);
this._session.sendEvent(new BreakpointEvent('changed', bp));
}
protected onConsoleAPICalled(params: Crdp.Runtime.ConsoleAPICalledEvent): void {
const result = formatConsoleArguments(params);
if (result) {
this.logObjects(result.args, result.isError, params.stackTrace);
}
}
private async logObjects(objs: Crdp.Runtime.RemoteObject[], isError = false, stackTrace?: Crdp.Runtime.StackTrace): Promise<void> {
// This is an asynchronous method, so ensure that we handle one at a time so that they are sent out in the same order that they came in.
this._currentLogMessage = this._currentLogMessage
.catch(err => logger.error(err.toString()))
.then(async () => {
const category = isError ? 'stderr' : 'stdout';
// Shortcut the common log case to reduce unnecessary back and forth
let e: DebugProtocol.OutputEvent;
if (objs.length === 1 && objs[0].type === 'string') {
let msg = objs[0].value;
if (isError) {
msg = await this.mapFormattedException(msg);
}
e = new OutputEvent(msg + '\n', category);
} else {
e = new OutputEvent('output', category);
e.body.variablesReference = this._variableHandles.create(new variables.LoggedObjects(objs), 'repl');