-
Notifications
You must be signed in to change notification settings - Fork 284
/
threads.ts
2017 lines (1779 loc) · 68.5 KB
/
threads.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 * as l10n from '@vscode/l10n';
import { randomBytes } from 'crypto';
import Cdp from '../cdp/api';
import { DebugType } from '../common/contributionUtils';
import { EventEmitter } from '../common/events';
import { HrTime } from '../common/hrnow';
import { ILogger, LogTag } from '../common/logging';
import { isInstanceOf, truthy } from '../common/objUtils';
import { Base0Position, Base1Position, Range } from '../common/positions';
import { IDeferred, delay, getDeferred } from '../common/promiseUtil';
import { IRenameProvider } from '../common/sourceMaps/renameProvider';
import * as sourceUtils from '../common/sourceUtils';
import { StackTraceParser } from '../common/stackTraceParser';
import { PositionToOffset } from '../common/stringUtils';
import * as urlUtils from '../common/urlUtils';
import { fileUrlToAbsolutePath } from '../common/urlUtils';
import { AnyLaunchConfiguration, IChromiumBaseConfiguration, OutputSource } from '../configuration';
import Dap from '../dap/api';
import * as errors from '../dap/errors';
import { ProtocolError } from '../dap/protocolError';
import { NodeWorkerTarget } from '../targets/node/nodeWorkerTarget';
import { ITarget } from '../targets/targets';
import { IShutdownParticipants } from '../ui/shutdownParticipants';
import { BreakpointManager, EntryBreakpointMode } from './breakpoints';
import { UserDefinedBreakpoint } from './breakpoints/userDefinedBreakpoint';
import { ICompletions } from './completions';
import { ExceptionMessage, IConsole, QueryObjectsMessage } from './console';
import { customBreakpoints } from './customBreakpoints';
import { IEvaluator, LocationEvaluateOptions } from './evaluator';
import { IExceptionPauseService } from './exceptionPauseService';
import * as objectPreview from './objectPreview';
import { PreviewContextType, getContextForType } from './objectPreview/contexts';
import { ExpectedPauseReason, IPausedDetails, StepDirection } from './pause';
import { SmartStepper } from './smartStepping';
import {
ISourceScript,
ISourceWithMap,
IUiLocation,
Source,
base1To0,
isSourceWithWasm,
} from './source';
import { IPreferredUiLocation, SourceContainer } from './sourceContainer';
import { InlinedFrame, StackFrame, StackTrace, isStackFrameElement } from './stackTrace';
import {
serializeForClipboard,
serializeForClipboardTmpl,
} from './templates/serializeForClipboard';
import { IVariableStoreLocationProvider, VariableStore } from './variableStore';
export class ExecutionContext {
public readonly sourceMapLoads = new Map<string, Promise<IUiLocation[]>>();
public readonly scripts: Script[] = [];
constructor(public readonly description: Cdp.Runtime.ExecutionContextDescription) {}
get isDefault(): boolean {
return this.description.auxData && this.description.auxData['isDefault'];
}
/** Removes all scripts associated with the context */
async remove(container: SourceContainer) {
await Promise.all(
this.scripts.map(async s => {
const source = await s.source;
source.filterScripts(s => s.executionContextId !== this.description.id);
if (!source.scripts.length) {
container.removeSource(source);
}
}),
);
}
}
export type Script = ISourceScript & {
source: Promise<Source>;
resolvedSource?: Source;
};
export type ScriptWithSourceMapHandler = (
script: Script,
sources: Source[],
) => Promise<IUiLocation[]>;
export type SourceMapDisabler = (hitBreakpoints: string[]) => ISourceWithMap[];
export type RawLocation = {
lineNumber: number; // 1-based
columnNumber: number; // 1-based
scriptId: Cdp.Runtime.ScriptId;
};
class DeferredContainer<T> {
private _dapDeferred: IDeferred<T> = getDeferred();
constructor(private readonly _obj: T) {}
resolve(): void {
this._dapDeferred.resolve(this._obj);
}
with<Return>(callback: (obj: T) => Return): Return | Promise<Return> {
if (this._dapDeferred.hasSettled()) {
return callback(this._obj);
} else {
return this._dapDeferred.promise.then(obj => callback(obj));
}
}
}
const excludedCallerSearchDepth = 50;
const sourcesEqual = (a: Dap.Source, b: Dap.Source) =>
a.sourceReference === b.sourceReference &&
urlUtils.comparePathsWithoutCasing(a.path || '', b.path || '');
const getReplSourceSuffix = () =>
`\n//# sourceURL=eval-${randomBytes(4).toString('hex')}${
sourceUtils.SourceConstants.ReplExtension
}\n`;
/** Auxillary data present in Cdp.Debugger.Paused events in recent Chrome versions */
interface IInstrumentationPauseAuxData {
scriptId: string;
url: string;
sourceMapURL: string;
}
/**
* Queue used to avoid getting into a bad state if the user runs multiple
* state-changing commands concurrently. Some things can cause V8 to block
* and take a while responding to requests. Mutliple requests of the same
* operation type get coalesced, while other operation types are
* run sequentially.
*/
class StateQueue {
private queue?: { operation: string; result: Promise<unknown> };
public async enqueue<T>(operation: string, fn: () => Promise<T>) {
// If we would no-op the task because it's already ongoing, make sure we flush
// microtasks first to avoid a race https://github.com/microsoft/vscode/issues/204581
if (this.queue?.operation === operation) {
await new Promise<void>(r => queueMicrotask(r));
}
if (!this.queue || this.queue.operation !== operation) {
const promise = this.queue?.result.then(fn, fn) ?? fn();
const queued = (this.queue = {
operation,
result: promise.finally(() => {
if (this.queue === queued) {
this.queue = undefined;
}
}),
});
}
return this.queue.result as Promise<T>;
}
}
const enum CustomBreakpointPrefix {
XHR = 'x',
Event = 'e',
}
export class Thread implements IVariableStoreLocationProvider {
private static _lastThreadId = 0;
public readonly id: number;
private _cdp: Cdp.Api;
private _pausedDetails?: IPausedDetails;
private _pausedVariables?: VariableStore;
private _pausedForSourceMapScriptId?: string;
private _executionContexts: Map<number, ExecutionContext> = new Map();
readonly replVariables: VariableStore;
readonly _sourceContainer: SourceContainer;
private _pauseOnSourceMapBreakpointIds?: Cdp.Debugger.BreakpointId[];
private _selectedContext: ExecutionContext | undefined;
static _allThreadsByDebuggerId = new Map<Cdp.Runtime.UniqueDebuggerId, Thread>();
private _scriptWithSourceMapHandler?: ScriptWithSourceMapHandler;
private _sourceMapDisabler?: SourceMapDisabler;
private _expectedPauseReason?: ExpectedPauseReason;
private _excludedCallers: readonly Dap.ExcludedCaller[] = [];
private _enabledCustomBreakpoints?: ReadonlySet<string>;
private readonly stateQueue = new StateQueue();
private readonly _onPausedEmitter = new EventEmitter<IPausedDetails>();
private readonly _dap: DeferredContainer<Dap.Api>;
private disposed = false;
public debuggerReady = getDeferred<void>();
/**
* Details set when a "step in" is issued. Used allow async stepping in
* sourcemapped worker scripts, and step in targets.
* @see https://github.com/microsoft/vscode-js-debug/issues/223
*/
private _waitingForStepIn?: {
// Last paused details
lastDetails?: IPausedDetails;
// Target we're stepping into, if we stepped into a target
intoTargetBreakpoint?: Cdp.Debugger.BreakpointId;
};
public readonly onPaused = this._onPausedEmitter.event;
constructor(
sourceContainer: SourceContainer,
cdp: Cdp.Api,
dap: Dap.Api,
private readonly target: ITarget,
renameProvider: IRenameProvider,
private readonly logger: ILogger,
private readonly evaluator: IEvaluator,
private readonly completer: ICompletions,
private readonly launchConfig: AnyLaunchConfiguration,
private readonly _breakpointManager: BreakpointManager,
private readonly console: IConsole,
private readonly exceptionPause: IExceptionPauseService,
private readonly _smartStepper: SmartStepper,
private readonly shutdown: IShutdownParticipants,
) {
this._dap = new DeferredContainer(dap);
this._sourceContainer = sourceContainer;
this._cdp = cdp;
this.id = Thread._lastThreadId++;
this.replVariables = new VariableStore(renameProvider, this._cdp, dap, launchConfig, this);
sourceContainer.onSourceMappedSteppingChange(() => this.refreshStackTrace());
this._initialize();
}
public setExcludedCallers(callers: readonly Dap.ExcludedCaller[]) {
this._excludedCallers = callers;
}
cdp(): Cdp.Api {
return this._cdp;
}
name(): string {
return this.target.name();
}
pausedDetails(): IPausedDetails | undefined {
return this._pausedDetails;
}
pausedVariables(): VariableStore | undefined {
return this._pausedVariables;
}
defaultExecutionContext(): ExecutionContext | undefined {
for (const context of this._executionContexts.values()) {
if (context.isDefault) return context;
}
}
public resume(): Promise<Dap.ContinueResult | Dap.Error> {
return this.stateQueue.enqueue('resume', async () => {
this._sourceContainer.clearDisabledSourceMaps();
if (!(await this._cdp.Debugger.resume({}))) {
// We don't report the failure if the target wasn't paused. VS relies on this behavior.
if (this._pausedDetails !== undefined) {
return errors.createSilentError(l10n.t('Unable to resume'));
}
}
return { allThreadsContinued: false };
});
}
public pause(): Promise<Dap.PauseResult | Dap.Error> {
return this.stateQueue.enqueue('pause', async () => {
this._expectedPauseReason = { reason: 'pause' };
if (await this._cdp.Debugger.pause({})) {
return {};
}
return errors.createSilentError(l10n.t('Unable to pause'));
});
}
public stepOver(): Promise<Dap.NextResult | Dap.Error> {
return this.stateQueue.enqueue('stepOver', async () => {
this._expectedPauseReason = { reason: 'step', direction: StepDirection.Over };
const skipList = await this.getCurrentSkipList(StepDirection.Over);
if (await this._cdp.Debugger.stepOver({ skipList })) {
return {};
}
return errors.createSilentError(l10n.t('Unable to step next'));
});
}
public stepInto(targetId?: number): Promise<Dap.StepInResult | Dap.Error> {
return this.stateQueue.enqueue('stepInto', async () => {
this._waitingForStepIn = { lastDetails: this._pausedDetails };
this._expectedPauseReason = { reason: 'step', direction: StepDirection.In };
const stepInTarget = this._pausedDetails?.stepInTargets?.[targetId as number];
if (stepInTarget) {
const breakpoint = await this._cdp.Debugger.setBreakpoint({
location: stepInTarget.breakLocation,
});
this._waitingForStepIn.intoTargetBreakpoint = breakpoint?.breakpointId;
if (await this._cdp.Debugger.resume({})) {
return {};
}
} else {
const skipList = await this.getCurrentSkipList(StepDirection.In);
if (await this._cdp.Debugger.stepInto({ breakOnAsyncCall: true, skipList })) {
return {};
}
}
return errors.createSilentError(l10n.t('Unable to step in'));
});
}
public stepOut(): Promise<Dap.StepOutResult | Dap.Error> {
return this.stateQueue.enqueue('stepOut', async () => {
this._expectedPauseReason = { reason: 'step', direction: StepDirection.Out };
if (await this._cdp.Debugger.stepOut({})) {
return {};
}
return errors.createSilentError(l10n.t('Unable to step out'));
});
}
private async getCurrentSkipList(direction: StepDirection) {
if (!this._pausedDetails) {
return;
}
const [frame] = await this._pausedDetails.stackTrace.loadFrames(1);
if (!frame || !isStackFrameElement(frame)) {
return undefined;
}
const list = await frame.getStepSkipList(direction);
if (!list) {
return undefined;
}
// make sure to simplify the range, as V8 is picky about
// wanting the ranges in order and non-overlapping.
return Range.simplify(list).map(
(r): Cdp.Debugger.LocationRange => ({
start: r.begin.base0,
end: r.end.base0,
scriptId: frame.root.scriptId,
}),
);
}
_stackFrameNotFoundError(): Dap.Error {
return errors.createSilentError(l10n.t('Stack frame not found'));
}
_evaluateOnAsyncFrameError(): Dap.Error {
return errors.createSilentError(l10n.t('Unable to evaluate on async stack frame'));
}
async restartFrame(params: Dap.RestartFrameParams): Promise<Dap.RestartFrameResult | Dap.Error> {
const stackFrame = this._pausedDetails?.stackTrace.frame(params.frameId)?.root;
if (!stackFrame) {
return this._stackFrameNotFoundError();
}
const callFrameId = stackFrame.callFrameId();
if (!callFrameId) {
return errors.createUserError(l10n.t('Cannot restart asynchronous frame'));
}
// Cast is necessary since the devtools-protocol is being slow to update:
// https://github.com/microsoft/vscode-js-debug/issues/1283#issuecomment-1148219994
// https://github.com/ChromeDevTools/devtools-protocol/issues/263
const ok = await this._cdp.Debugger.restartFrame({
callFrameId,
mode: 'StepInto',
} as Cdp.Debugger.RestartFrameParams);
if (!ok) {
return errors.createUserError(l10n.t('Frame could not be restarted'));
}
this._expectedPauseReason = {
reason: 'frame_entry',
description: l10n.t('Paused on frame entry'),
};
// Chromium versions before 104 didn't have an explicit `canBeRestarted`
// flag on their call frame. And on those versions, when we `restartFrame`,
// we need to manually `stepInto` to unpause. However, with 104, restarting
// the frame will automatically resume execution.
if (!stackFrame.canExplicitlyBeRestarted) {
await this._cdp.Debugger.stepInto({});
}
return {};
}
async stackTrace(params: Dap.StackTraceParams): Promise<Dap.StackTraceResult | Dap.Error> {
if (!this._pausedDetails) return errors.createSilentError(l10n.t('Thread is not paused'));
return this._pausedDetails.stackTrace.toDap(params);
}
async scopes(params: Dap.ScopesParams): Promise<Dap.ScopesResult | Dap.Error> {
const stackFrame = this._pausedDetails
? this._pausedDetails.stackTrace.frame(params.frameId)
: undefined;
if (!stackFrame) return this._stackFrameNotFoundError();
return stackFrame.scopes();
}
async exceptionInfo(): Promise<Dap.ExceptionInfoResult | Dap.Error> {
const exception = this._pausedDetails && this._pausedDetails.exception;
if (!exception) return errors.createSilentError(l10n.t('Thread is not paused on exception'));
const preview = objectPreview.previewException(exception);
return {
exceptionId: preview.title,
breakMode: 'all',
details: {
stackTrace: preview.stackTrace,
evaluateName: undefined, // This is not used by vscode.
},
};
}
/**
* Focuses the page for which the thread is attached.
*/
public async revealPage() {
this._cdp.Page.bringToFront({});
return {};
}
public async completions(
params: Dap.CompletionsParams,
): Promise<Dap.CompletionsResult | Dap.Error> {
let stackFrame: StackFrame | undefined;
if (params.frameId !== undefined) {
stackFrame = this._pausedDetails
? this._pausedDetails.stackTrace.frame(params.frameId)?.root
: undefined;
if (!stackFrame) return this._stackFrameNotFoundError();
if (!stackFrame.callFrameId()) return this._evaluateOnAsyncFrameError();
}
// If we're changing an execution context, don't bother with JS completion.
if (params.line === 1 && params.text.startsWith('cd ')) {
return { targets: this.getExecutionContextCompletions(params) };
}
const targets = await this.completer.completions({
executionContextId: this._selectedContext ? this._selectedContext.description.id : undefined,
stackFrame,
expression: params.text,
position: new Base1Position(params.line || 1, params.column),
});
// Merge the actual completion items with the synthetic target changing items.
return { targets: [...this.getExecutionContextCompletions(params), ...targets] };
}
private getExecutionContextCompletions(params: Dap.CompletionsParams): Dap.CompletionItem[] {
if (params.line && params.line > 1) {
return [];
}
const prefix = params.text.slice(0, params.column).trim();
return [...this._executionContexts.values()]
.map(c => `cd ${this.target.executionContextName(c.description)}`)
.filter(label => label.startsWith(prefix))
.map(label => ({ label, start: 0, length: params.text.length }));
}
/**
* Evaluates the expression on the stackframe if it's a WASM stackframe with
* evaluation information. Returns undefined otherwise.
*/
private async _evaluteWasm(
stackFrame: StackFrame | InlinedFrame | undefined,
args: Dap.EvaluateParamsExtended,
variables: VariableStore,
): Promise<Dap.Variable | undefined> {
if (!stackFrame) {
return;
}
const root = stackFrame.root;
const cfId = root.callFrameId();
const source = await root.scriptSource?.source;
if (!isSourceWithWasm(source) || !cfId) {
return;
}
const symbols = await source.sourceMap.value.promise;
if (!symbols.evaluate) {
return;
}
const position = new Base0Position(
stackFrame instanceof InlinedFrame ? stackFrame.inlineFrameIndex : 0,
root.rawPosition.base0.columnNumber,
);
const result = await symbols.evaluate(cfId, position, args.expression);
if (result) {
return await variables
.createFloatingVariable(args.expression, result)
.toDap(args.context as PreviewContextType, args.format);
}
}
/**
* Evaluates the expression on the stackframe.
*/
private async _evaluteJs(
stackFrame: StackFrame | InlinedFrame | undefined,
args: Dap.EvaluateParamsExtended,
variables: VariableStore,
): Promise<Dap.Variable> {
// For clipboard evaluations, return a safe JSON-stringified string.
const params: Cdp.Runtime.EvaluateParams =
args.context === 'clipboard'
? {
expression: serializeForClipboardTmpl.expr(args.expression, '2'),
includeCommandLineAPI: true,
returnByValue: true,
objectGroup: 'console',
}
: {
expression: args.expression,
includeCommandLineAPI: true,
objectGroup: 'console',
generatePreview: true,
timeout: args.context === 'hover' ? this.getHoverEvalTimeout() : undefined,
};
if (args.context === 'repl') {
params.expression = sourceUtils.wrapObjectLiteral(params.expression);
if (params.expression.indexOf('await') !== -1) {
const rewritten = sourceUtils.rewriteTopLevelAwait(params.expression);
if (rewritten) {
params.expression = rewritten;
params.awaitPromise = true;
}
}
params.expression += getReplSourceSuffix();
}
if (args.evaluationOptions)
this.cdp().DotnetDebugger.setEvaluationOptions({
options: args.evaluationOptions,
type: 'evaluation',
});
let location: LocationEvaluateOptions | undefined;
if (args.source && args.line && args.column) {
const variables = this._pausedVariables;
const source = this._sourceContainer.source(args.source);
if (source && variables) {
location = { source, position: new Base1Position(args.line, args.column), variables };
}
}
const callFrameId = stackFrame?.root.callFrameId();
const responsePromise = this.evaluator.evaluate(
callFrameId
? { ...params, callFrameId }
: {
...params,
contextId: this._selectedContext ? this._selectedContext.description.id : undefined,
},
{ isInternalScript: false, stackFrame: stackFrame?.root, location },
);
// Report result for repl immediately so that the user could see the expression they entered.
if (args.context === 'repl') {
return await this._evaluateRepl(args, responsePromise, args.format);
}
const response = await responsePromise;
if (!response) throw new ProtocolError(errors.createSilentError(l10n.t('Unable to evaluate')));
if (response.exceptionDetails) {
let text = response.exceptionDetails.exception
? objectPreview.previewException(response.exceptionDetails.exception).title
: response.exceptionDetails.text;
if (!text.startsWith('Uncaught')) text = 'Uncaught ' + text;
throw new ProtocolError(errors.createSilentError(text));
}
return variables
.createFloatingVariable(params.expression, response.result)
.toDap(args.context as PreviewContextType, args.format);
}
public async evaluate(args: Dap.EvaluateParamsExtended): Promise<Dap.EvaluateResult> {
let callFrameId: Cdp.Debugger.CallFrameId | undefined;
let stackFrame: StackFrame | InlinedFrame | undefined;
if (args.frameId !== undefined) {
stackFrame = this._pausedDetails
? this._pausedDetails.stackTrace.frame(args.frameId)
: undefined;
if (!stackFrame) {
throw new ProtocolError(this._stackFrameNotFoundError());
}
callFrameId = stackFrame.root.callFrameId();
if (!callFrameId) {
throw new ProtocolError(this._evaluateOnAsyncFrameError());
}
}
if (args.context === 'repl' && args.expression.startsWith('cd ')) {
const contextName = args.expression.substring('cd '.length).trim();
for (const ec of this._executionContexts.values()) {
if (this.target.executionContextName(ec.description) === contextName) {
this._selectedContext = ec;
return {
result: `[${contextName}]`,
variablesReference: 0,
};
}
}
}
const variableStore = callFrameId ? this._pausedVariables : this.replVariables;
if (!variableStore) {
throw new ProtocolError(errors.createSilentError(l10n.t('Unable to evaluate')));
}
const variable =
(await this._evaluteWasm(stackFrame, args, variableStore)) ??
(await this._evaluteJs(stackFrame, args, variableStore));
return {
type: variable.type,
result: variable.value,
variablesReference: variable.variablesReference,
namedVariables: variable.namedVariables,
indexedVariables: variable.indexedVariables,
memoryReference: variable.memoryReference,
};
}
private getHoverEvalTimeout() {
const configuredTimeout = this.launchConfig.timeouts?.hoverEvaluation;
if (configuredTimeout === undefined) {
return 500;
}
if (configuredTimeout <= 0) {
return undefined;
}
return configuredTimeout;
}
async _evaluateRepl(
originalCall: Dap.EvaluateParams,
responsePromise:
| Promise<Cdp.Runtime.EvaluateResult | undefined>
| Promise<Cdp.Debugger.EvaluateOnCallFrameResult | undefined>,
format: Dap.ValueFormat | undefined,
): Promise<Dap.Variable> {
const response = await responsePromise;
if (!response) return { name: originalCall.expression, value: '', variablesReference: 0 };
if (response.exceptionDetails) {
const formattedException = await new ExceptionMessage(response.exceptionDetails).toDap(this);
throw new ProtocolError(errors.replError(formattedException.output));
}
const contextName =
this._selectedContext && this.defaultExecutionContext() !== this._selectedContext
? `\x1b[33m[${this.target.executionContextName(this._selectedContext.description)}] `
: '';
const resultVar = await this.replVariables
.createFloatingVariable(originalCall.expression, response.result)
.toDap(PreviewContextType.Repl, format);
const budget = getContextForType(PreviewContextType.Repl).budget;
// If it looks like output was truncated by the budget, show a message
// after the output is returned hinting they can copy the whole thing.
if (resultVar.variablesReference === 0 && resultVar.value.length === budget) {
setImmediate(() =>
this.console.enqueue(this, {
toDap: () => ({
output: l10n.t(
'Output has been truncated to the first {0} characters. Run `{1}` to copy the full output.',
budget,
`copy(${originalCall.expression.trim()})`,
),
category: 'stdout',
}),
}),
);
}
return { ...resultVar, value: `${contextName}${resultVar.value}` };
}
private _initialize() {
this._cdp.Runtime.on('executionContextCreated', event => {
this._executionContextCreated(event.context);
});
this._cdp.Runtime.on('executionContextDestroyed', event => {
this._executionContextDestroyed(event.executionContextId);
});
this._cdp.Runtime.on('executionContextsCleared', () => {
this._ensureDebuggerEnabledAndRefreshDebuggerId();
this.replVariables.clear();
this._executionContextsCleared();
});
this._cdp.Inspector.on('targetReloadedAfterCrash', () => {
// It was reported that crashing targets sometimes loses breakpoints.
// I could not reproduce this by calling `Page.crash()`, but put this fix
// in nevertheless; it should be safe.
this._breakpointManager.reapply();
});
if (this.launchConfig.outputCapture === OutputSource.Console) {
this._cdp.Runtime.on('consoleAPICalled', event => {
this.console.dispatch(this, event);
});
this._cdp.Runtime.on('exceptionThrown', event => {
this.console.enqueue(this, new ExceptionMessage(event.exceptionDetails));
});
}
this._cdp.Runtime.on('inspectRequested', event => {
if (event.hints['copyToClipboard']) {
this._copyObjectToClipboard(event.object);
} else if (event.hints['queryObjects']) {
this.console.enqueue(this, new QueryObjectsMessage(event.object, this.cdp()));
} else this._revealObject(event.object);
});
this._cdp.Debugger.on('paused', async event => this._onPaused(event));
this._cdp.Debugger.on('resumed', () => this.onResumed());
this._cdp.Debugger.on('scriptParsed', event => this._onScriptParsed(event));
this._cdp.Debugger.on('scriptFailedToParse', event => this._onScriptParsed(event));
this._cdp.Runtime.enable({});
// The profilder domain is required to be always on in order to support
// console.profile/console.endProfile. Otherwise, these just no-op.
this._cdp.Profiler.enable({});
this._ensureDebuggerEnabledAndRefreshDebuggerId();
if (this.launchConfig.noDebug) {
this.logger.info(LogTag.RuntimeLaunch, 'Running with noDebug, so debug domains are disabled');
}
this.target.initialize();
this._dap.with(dap =>
dap.thread({
reason: 'started',
threadId: this.id,
}),
);
}
dapInitialized() {
this._dap.resolve();
}
/**
* Implements DAP `stepInTargets` request.
*
* @todo location information is patched in until ratification of
* https://github.com/microsoft/debug-adapter-protocol/issues/274
*/
public async getStepInTargets(frameId: number): Promise<
(Dap.StepInTarget & {
line?: number;
column?: number;
endLine?: number;
endColumn?: number;
})[]
> {
const pausedDetails = this._pausedDetails;
if (!pausedDetails) {
return [];
}
const frame = pausedDetails.stackTrace.frames.find(f => f.frameId === frameId);
if (!(frame instanceof StackFrame)) {
return [];
}
const pausedLocation = await frame.uiLocation();
if (!pausedLocation) {
return [];
}
const rawPausedLocation = pausedDetails.event.callFrames[0].location;
const [locations, content] = await Promise.all([
this._breakpointManager
.getBreakpointLocations(
this,
pausedLocation.source,
new Base1Position(pausedLocation.lineNumber, 1),
new Base1Position(pausedLocation.lineNumber + 1, 1),
)
.then(l =>
// remove the currently-paused location
l.filter(
l =>
l.breakLocation.lineNumber !== rawPausedLocation.lineNumber ||
l.breakLocation.columnNumber !== rawPausedLocation.columnNumber,
),
),
pausedLocation.source.content(),
]);
// V8's breakpoint locations are placed directly before the function to
// be called, which is perfect, e.g `this.*greet()`. However, once mapped,
// many tools will make the entire `this.greet(` a single range, which
// means default behavior of reading the next word will not give a good
// location. Instead, look over the source content manually to build ranges.
const idStart = pausedDetails.stepInTargets?.length || 0;
pausedDetails.stepInTargets = pausedDetails.stepInTargets?.concat(locations) || locations;
const lines = content && new PositionToOffset(content);
return locations
.map((location, i) => {
const preferred = location.uiLocations.find(l => l.source === pausedLocation.source);
if (!preferred) {
return;
}
if (!lines) {
return {
id: idStart + i,
label: `Column ${preferred}`,
line: preferred.lineNumber,
column: preferred.columnNumber,
};
}
const target = sourceUtils.getStepTargetInfo(
content.slice(
lines.getLineOffset(preferred.lineNumber - 1),
lines.getLineOffset(preferred.lineNumber),
),
preferred.columnNumber - 1,
);
if (!target) {
return;
}
return {
id: idStart + i,
label: target.text,
line: preferred.lineNumber,
column: target.start + 1,
endLine: preferred.lineNumber,
endColumn: target.end + 1,
};
})
.filter(truthy);
}
async refreshStackTrace() {
if (!this._pausedDetails) {
return;
}
this._pausedDetails = await this._createPausedDetails(this._pausedDetails.event);
this._onThreadResumed();
await this._onThreadPaused(this._pausedDetails);
}
private _executionContextCreated(description: Cdp.Runtime.ExecutionContextDescription) {
const context = new ExecutionContext(description);
this._executionContexts.set(description.id, context);
}
async _executionContextDestroyed(contextId: number) {
const context = this._executionContexts.get(contextId);
if (!context) return;
this._executionContexts.delete(contextId);
await this.shutdown.shutdownContext();
context.remove(this._sourceContainer);
}
async _executionContextsCleared() {
const removedContexts = [...this._executionContexts.values()];
const pausedDetails = this._pausedDetails;
this._executionContexts.clear();
await this.shutdown.shutdownContext();
for (const context of removedContexts) {
context.remove(this._sourceContainer);
}
this._breakpointManager.executionContextWasCleared();
if (pausedDetails && pausedDetails === this._pausedDetails) {
this.onResumed();
}
}
_ensureDebuggerEnabledAndRefreshDebuggerId() {
if (this.launchConfig.noDebug) {
return this.debuggerReady.resolve();
}
// There is a bug in Chrome that does not retain debugger id
// across cross-process navigations. Refresh it upon clearing contexts.
this._cdp.Debugger.enable({}).then(response => {
this.debuggerReady.resolve();
if (response) {
Thread._allThreadsByDebuggerId.set(response.debuggerId, this);
}
});
this.exceptionPause.apply(this._cdp);
}
private async _onPaused(event: Cdp.Debugger.PausedEvent) {
const hitBreakpoints = event.hitBreakpoints ?? [];
// "Break on start" is not actually a by-spec reason in CDP, it's added on from Node.js, so cast `as string`:
// https://github.com/nodejs/node/blob/9cbf6af5b5ace0cc53c1a1da3234aeca02522ec6/src/node_contextify.cc#L913
// And Deno uses `debugCommand:
// https://github.com/denoland/deno/blob/2703996dea73c496d79fcedf165886a1659622d1/core/inspector.rs#L571
const isInspectBrk =
(event.reason as string) === 'Break on start' || event.reason === 'debugCommand';
const location = event.callFrames[0]?.location as Cdp.Debugger.Location | undefined;
const scriptId = (event.data as IInstrumentationPauseAuxData)?.scriptId || location?.scriptId;
const isSourceMapPause =
scriptId &&
(event.reason === 'instrumentation' ||
this._breakpointManager.isEntrypointBreak(hitBreakpoints, scriptId) ||
hitBreakpoints.some(bp => this._pauseOnSourceMapBreakpointIds?.includes(bp)));
this.evaluator.setReturnedValue(event.callFrames[0]?.returnValue);
if (isSourceMapPause) {
if (
(this.launchConfig as IChromiumBaseConfiguration).perScriptSourcemaps === 'auto' &&
this._shouldEnablePerScriptSms(event)
) {
await this._enablePerScriptSourcemaps();
}
if (event.data && !isInspectBrk) {
event.data.__rewriteAs = 'breakpoint';
}
const expectedPauseReason = this._expectedPauseReason;
if (scriptId && (await this._handleSourceMapPause(scriptId, location))) {
// Pause if we just resolved a breakpoint that's on this
// location; this won't have existed before now.
} else if (isInspectBrk) {
// Inspect-brk is handled later on
} else if (await this.isCrossThreadStep(event)) {
// Check if we're stepping into an async-loaded script (#223)
event.data = { ...event.data, __rewriteAs: 'step' };
} else if (
await this._breakpointManager.shouldPauseAt(
event,
hitBreakpoints,
this.target.entryBreakpoint,
true,
)
) {
// Check if there are any user-defined breakpoints on this line
} else if (expectedPauseReason?.reason === 'step') {
// Check if we're in the middle of a step, e.g. stepping over a
// function compilation. Stepping in should still remain paused,
// and an instrumentation pause in step out should not be possible.
if (expectedPauseReason.direction === StepDirection.In) {
// no-op
} else {
return this._cdp.Debugger.resume({});
}
} else {
// If none of this above, it's pure instrumentation.
return this.resume();
}
} else {
const wantsPause =
event.reason === 'exception' || event.reason === 'promiseRejection'
? await this.exceptionPause.shouldPauseAt(event)
: await this._breakpointManager.shouldPauseAt(
event,
hitBreakpoints,
this.target.entryBreakpoint,
false,
);
if (!wantsPause) {
return this.resume();
}