forked from microsoft/vscode-node-debug
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnodeDebug.ts
More file actions
4260 lines (3488 loc) · 133 KB
/
Copy pathnodeDebug.ts
File metadata and controls
4260 lines (3488 loc) · 133 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
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import {
LoggingDebugSession, DebugSession, Logger, logger,
Thread, Source, StackFrame, Scope, Variable, Breakpoint,
TerminatedEvent, InitializedEvent, StoppedEvent, OutputEvent, LoadedSourceEvent,
Handles, ErrorDestination, CapabilitiesEvent
} from 'vscode-debugadapter';
import {DebugProtocol} from 'vscode-debugprotocol';
import {
NodeV8Protocol, NodeV8Event, NodeV8Response,
V8SetBreakpointArgs, V8SetVariableValueArgs, V8RestartFrameArgs, V8BacktraceArgs,
V8ScopeResponse, V8EvaluateResponse, V8FrameResponse,
V8EventBody, V8BreakEventBody, V8ExceptionEventBody,
V8Ref, V8Handle, V8Property, V8Object, V8Simple, V8Function, V8Frame, V8Scope, V8Script
} from './nodeV8Protocol';
import {ISourceMaps, SourceMaps, SourceMap} from './sourceMaps';
import * as PathUtils from './pathUtilities';
import * as WSL from './wslSupport';
import * as CP from 'child_process';
import * as Net from 'net';
import * as URL from 'url';
import * as Path from 'path';
import * as FS from 'fs';
import * as nls from 'vscode-nls';
let localize = nls.loadMessageBundle();
type FilterType = 'named' | 'indexed' | 'all';
export interface VariableContainer {
Expand(session: NodeDebugSession, filter: FilterType, start: number | undefined, count: number | undefined): Promise<Variable[]>;
SetValue(session: NodeDebugSession, name: string, value: string): Promise<Variable>;
}
type ExpanderFunction = (start: number, count: number) => Promise<Variable[]>;
export class Expander implements VariableContainer {
public static SET_VALUE_ERROR = localize('setVariable.error', "Setting value not supported");
private _expanderFunction : ExpanderFunction;
public constructor(func: ExpanderFunction) {
this._expanderFunction = func;
}
public Expand(session: NodeDebugSession, filter: string, start: number, count: number) : Promise<Variable[]> {
return this._expanderFunction(start, count);
}
public SetValue(session: NodeDebugSession, name: string, value: string) : Promise<Variable> {
return Promise.reject(new Error(Expander.SET_VALUE_ERROR));
}
}
export class PropertyContainer implements VariableContainer {
private _evalName: string | undefined;
private _object: V8Object;
private _this: V8Object | undefined;
public constructor(evalName: string | undefined, obj: V8Object, ths?: V8Object) {
this._evalName = evalName;
this._object = obj;
this._this = ths;
}
public Expand(session: NodeDebugSession, filter: FilterType, start: number, count: number) : Promise<Variable[]> {
if (filter === 'named') {
return session._createProperties(this._evalName, this._object, 'named').then(variables => {
if (this._this) {
return session._createVariable(this._evalName, 'this', this._this).then(variable => {
if (variable) {
variables.push(variable);
}
return variables;
});
} else {
return variables;
}
});
}
if (typeof start === 'number' && typeof count === 'number') {
return session._createProperties(this._evalName, this._object, 'indexed', start, count);
} else {
return session._createProperties(this._evalName, this._object, 'all').then(variables => {
if (this._this) {
return session._createVariable(this._evalName, 'this', this._this).then(variable => {
if (variable) {
variables.push(variable);
}
return variables;
});
} else {
return variables;
}
});
}
}
public SetValue(session: NodeDebugSession, name: string, value: string) : Promise<Variable> {
return session._setPropertyValue(this._object.handle, name, value);
}
}
export class SetMapContainer implements VariableContainer {
private _evalName: string | undefined;
private _object: V8Object;
public constructor(evalName: string | undefined, obj: V8Object) {
this._evalName = evalName;
this._object = obj;
}
public Expand(session: NodeDebugSession, filter: FilterType, start: number, count: number) : Promise<Variable[]> {
if (filter === 'named') {
return session._createSetMapProperties(this._evalName, this._object);
}
if (this._object.type === 'set') {
return session._createSetElements(this._object, start, count);
} else {
return session._createMapElements(this._object, start, count);
}
}
public SetValue(session: NodeDebugSession, name: string, value: string) : Promise<Variable> {
return Promise.reject(new Error(Expander.SET_VALUE_ERROR));
}
}
export class ScopeContainer implements VariableContainer {
private _frame: number;
private _scope: number;
private _object: V8Object;
private _this: V8Object | undefined;
public constructor(scope: V8Scope, obj: V8Object, ths?: V8Object) {
this._frame = scope.frameIndex;
this._scope = scope.index;
this._object = obj;
this._this = ths;
}
public Expand(session: NodeDebugSession, filter: FilterType, start: number, count: number) : Promise<Variable[]> {
return session._createProperties('', this._object, filter).then(variables => {
if (this._this) {
return session._createVariable('', 'this', this._this).then(variable => {
if (variable) {
variables.push(variable);
}
return variables;
});
} else {
return variables;
}
});
}
public SetValue(session: NodeDebugSession, name: string, value: string) : Promise<Variable> {
return session._setVariableValue(this._frame, this._scope, name, value);
}
}
type ReasonType = 'step' | 'breakpoint' | 'exception' | 'pause' | 'entry' | 'debugger_statement' | 'frame_entry';
class Script {
contents: string;
sourceMap: SourceMap;
constructor(script: V8Script) {
this.contents = script.source;
}
}
type HitterFunction = (hitCount: number) => boolean;
class InternalSourceBreakpoint {
line: number;
orgLine: number;
column: number;
orgColumn: number;
condition: string | undefined;
hitCount: number;
hitter: HitterFunction | undefined;
verificationMessage: string;
constructor(line: number, column: number = 0, condition?: string, logMessage?: string, hitter?: HitterFunction) {
this.line = this.orgLine = line;
this.column = this.orgColumn = column;
if (logMessage) {
this.condition = logMessageToExpression(logMessage);
if (condition) {
this.condition = `(${condition}) && ${this.condition}`;
}
} else if (condition) {
this.condition = condition;
}
this.hitCount = 0;
this.hitter = hitter;
}
}
/**
* A SourceSource represents the source contents of an internal module or of a source map with inlined contents.
*/
class SourceSource {
scriptId: number; // if 0 then source contains the file contents of a source map, otherwise a scriptID.
source: string | undefined;
constructor(sid: number, content?: string) {
this.scriptId = sid;
this.source = content;
}
}
/**
* Arguments shared between Launch and Attach requests.
*/
interface CommonArguments {
/** comma separated list of trace selectors. Supported:
* 'all': all
* 'la': launch/attach
* 'ls': load scripts
* 'bp': breakpoints
* 'sm': source maps
* 'va': data structure access
* 'ss': smart steps
* 'rc': ref caching
* */
trace?: boolean | string;
/** The debug port to attach to. */
port: number;
/** The TCP/IP address of the port (remote addresses only supported for node >= 5.0). */
address?: string;
/** Retry for this number of milliseconds to connect to the node runtime. */
timeout?: number;
/** Automatically stop target after launch. If not specified, target does not stop. */
stopOnEntry?: boolean;
/** Configure source maps. By default source maps are enabled (since v1.9.11). */
sourceMaps?: boolean;
/** obsolete: Where to look for the generated code. Only used if sourceMaps is true. */
outDir?: string;
/** output files glob patterns */
outFiles?: string[];
/** Try to automatically step over uninteresting source. */
smartStep?: boolean;
/** automatically skip these files. */
skipFiles?: string[];
/** Request frontend to restart session on termination. */
restart?: boolean;
/** Node's root directory. */
remoteRoot?: string;
/** VS Code's root directory. */
localRoot?: string;
// unofficial flags
/** Step back supported. */
stepBack?: boolean;
/** Control mapping of node.js scripts to files on disk. */
mapToFilesOnDisk?: boolean;
// internal attributes
/** Debug session ID */
__sessionId: string;
}
type ConsoleType = 'internalConsole' | 'integratedTerminal' | 'externalTerminal';
/**
* This interface should always match the schema found in the node-debug extension manifest.
*/
interface LaunchRequestArguments extends DebugProtocol.LaunchRequestArguments, CommonArguments {
/** An absolute path to the program to debug. */
program: string;
/** Optional arguments passed to the debuggee. */
args?: string[];
/** Launch the debuggee in this working directory (specified as an absolute path). If omitted the debuggee is lauched in its own directory. */
cwd?: string;
/** Absolute path to the runtime executable to be used. Default is the runtime executable on the PATH. */
runtimeExecutable?: string;
/** Optional arguments passed to the runtime executable. */
runtimeArgs?: string[];
/** Optional environment variables to pass to the debuggee. The string valued properties of the 'environmentVariables' are used as key/value pairs. */
env?: { [key: string]: string | null; };
/** Optional path to .env file. */
envFile?: string;
/** Deprecated: if true launch the target in an external console. */
externalConsole?: boolean;
/** Where to launch the debug target. */
console?: ConsoleType;
/** Use Windows Subsystem Linux */
useWSL?: boolean;
}
/**
* This interface should always match the schema found in the node-debug extension manifest.
*/
interface AttachRequestArguments extends DebugProtocol.AttachRequestArguments, CommonArguments {
// currently nothing is 'attach' specific
}
export class NodeDebugSession extends LoggingDebugSession {
private static MAX_STRING_LENGTH = 10000; // max string size to return in 'evaluate' request
private static MAX_JSON_LENGTH = 500000; // max size of stringified object to return in 'evaluate' request
private static NODE_TERMINATION_POLL_INTERVAL = 3000;
private static ATTACH_TIMEOUT = 10000;
private static RUNINTERMINAL_TIMEOUT = 5000;
private static PREVIEW_PROPERTIES = 3; // maximum number of properties to show in object/array preview
private static PREVIEW_MAX_STRING_LENGTH = 50; // truncate long strings for object/array preview
private static NODE = 'node';
private static DUMMY_THREAD_ID = 1;
private static DUMMY_THREAD_NAME = 'Node';
private static FIRST_LINE_OFFSET = 62;
private static PROTO = '__proto__';
private static DEBUG_INJECTION = 'debugInjection.js';
private static NODE_INTERNALS = '<node_internals>';
private static NODE_INTERNALS_PREFIX = /^<node_internals>[/\\]/;
private static NODE_INTERNALS_VM = /^<node_internals>[/\\]VM([0-9]+)/;
private static JS_EXTENSIONS = [ '.js', '.es6', '.jsx', '.mjs' ];
private static NODE_SHEBANG_MATCHER = new RegExp('#! */usr/bin/env +node');
private static LONG_STRING_MATCHER = /\.\.\. \(length: [0-9]+\)$/;
private static HITCOUNT_MATCHER = /(>|>=|=|==|<|<=|%)?\s*([0-9]+)/;
private static PROPERTY_NAME_MATCHER = /^[$_\w][$_\w0-9]*$/;
// tracing
private _trace: string[] | undefined;
private _traceAll = false;
// options
private _tryToInjectExtension = true;
private _skipRejects = false; // do not stop on rejected promises
private _maxVariablesPerScope = 100; // only load this many variables for a scope
private _smartStep = false; // try to automatically step over uninteresting source
private _skipFiles: string[] | undefined; // skip glob patterns
private _mapToFilesOnDisk = true; // by default try to map node.js scripts to files on disk
private _compareContents = true; // by default verify that script contents is same as file contents
private _supportsRunInTerminalRequest = false;
// session state
private _node: NodeV8Protocol;
private _attachSuccessful: boolean;
private _processId: number = -1; // pid of the program launched
private _nodeProcessId: number = -1; // pid of the node runtime
private _isWSL = false;
private _functionBreakpoints = new Array<number>(); // node function breakpoint ids
private _scripts = new Map<number, Promise<Script>>(); // script cache
private _files = new Map<string, Promise<string>>(); // file cache
private _scriptId2Handle = new Map<number, number>();
private _inlinedContentHandle = new Map<string, number>();
private _modifiedSources = new Set<string>(); // track edited files
private _hitCounts = new Map<number, InternalSourceBreakpoint>(); // breakpoint ID -> ignore count
// session configurations
private _noDebug = false;
private _attachMode = false;
private _localRoot: string | undefined;
private _remoteRoot: string | undefined;
private _restartMode = false;
private _port: number | undefined;
private _sourceMaps: ISourceMaps;
private _console: ConsoleType = 'internalConsole';
private _stopOnEntry: boolean;
private _stepBack = false;
// state valid between stop events
public _variableHandles = new Handles<VariableContainer>();
private _frameHandles = new Handles<V8Frame>();
private _sourceHandles = new Handles<SourceSource>();
private _refCache = new Map<number, V8Handle>();
// internal state
private _isTerminated: boolean;
private _inShutdown: boolean;
private _pollForNodeProcess = false;
private _exception: V8ExceptionEventBody | undefined;
private _restartFramePending: boolean;
private _stoppedReason: string;
private _nodeInjectionAvailable = false;
private _needContinue: boolean;
private _needBreakpointEvent: boolean;
private _needDebuggerEvent: boolean;
private _gotEntryEvent: boolean;
private _gotDebuggerEvent = false;
private _entryPath: string;
private _entryLine: number; // entry line in *.js file (not in the source file)
private _entryColumn: number; // entry column in *.js file (not in the source file)
private _smartStepCount = 0;
private _catchRejects = false;
private _disableSkipFiles = false;
public constructor() {
super('node-debug.txt');
// this debugger uses zero-based lines and columns which is the default
// so the following two calls are not really necessary.
this.setDebuggerLinesStartAt1(false);
this.setDebuggerColumnsStartAt1(false);
this._node = new NodeV8Protocol(response => {
// if request successful, cache alls refs
if (response.success && response.refs) {
const oldSize = this._refCache.size;
for (let r of response.refs) {
this._cache(r.handle, r);
}
if (this._refCache.size !== oldSize) {
this.log('rc', `NodeV8Protocol hook: ref cache size: ${this._refCache.size}`);
}
}
});
this._node.on('break', (event: NodeV8Event) => {
this._stopped('break');
this._handleNodeBreakEvent(<V8BreakEventBody>event.body);
});
this._node.on('exception', (event: NodeV8Event) => {
this._stopped('exception');
this._handleNodeExceptionEvent(<V8ExceptionEventBody>event.body);
});
/*
this._node.on('beforeCompile', (event: NodeV8Event) => {
//this.outLine(`beforeCompile ${this._scriptToPath(event.body.script)}`);
this.sendEvent(new Event('customScriptLoad', { script: this._scriptToPath(event.body.script) }));
});
*/
this._node.on('afterCompile', (event: NodeV8Event) => {
//this.outLine(`afterCompile ${this._scriptToPath(event.body.script)}`);
this.sendEvent(new LoadedSourceEvent('new', this._scriptToSource(event.body.script)));
//this.sendEvent(new Event('scriptLoaded', { path: this._scriptToPath(event.body.script) }));
});
this._node.on('close', (event: NodeV8Event) => {
this._terminated('node v8protocol close');
});
this._node.on('error', (event: NodeV8Event) => {
this._terminated('node v8protocol error');
});
/*
this._node.on('diagnostic', (event: NodeV8Event) => {
this.outLine(`diagnostic event ${event.body.reason}`);
});
*/
}
/**
* Analyse why node has stopped and sends StoppedEvent if necessary.
*/
private _handleNodeExceptionEvent(eventBody: V8ExceptionEventBody) : void {
// should we skip this location?
if (this._skip(eventBody)) {
this._node.command('continue');
return;
}
let description: string | undefined;
// in order to identify rejects extract source at current location
if (eventBody.sourceLineText && typeof eventBody.sourceColumn === 'number') {
let source = eventBody.sourceLineText.substr(eventBody.sourceColumn);
if (source.indexOf('reject(') === 0) {
if (this._skipRejects && !this._catchRejects) {
this._node.command('continue');
return;
}
description = localize('exception.paused.promise.rejection', "Paused on Promise Rejection");
if (eventBody.exception.text) {
eventBody.exception.text = localize('exception.promise.rejection.text', "Promise Rejection ({0})", eventBody.exception.text);
} else {
eventBody.exception.text = localize('exception.promise.rejection', "Promise Rejection");
}
}
}
// send event
this._exception = eventBody;
this._sendStoppedEvent('exception', description, eventBody.exception.text);
}
/**
* Analyse why node has stopped and sends StoppedEvent if necessary.
*/
private _handleNodeBreakEvent(eventBody: V8BreakEventBody) : void {
const breakpoints = eventBody.breakpoints;
// check for breakpoints
if (Array.isArray(breakpoints) && breakpoints.length > 0) {
this._disableSkipFiles = this._skip(eventBody);
const id = breakpoints[0];
if (!this._gotEntryEvent && id === 1) { // 'stop on entry point' is implemented as a breakpoint with ID 1
this.log('la', '_handleNodeBreakEvent: suppressed stop-on-entry event');
// do not send event now
this._rememberEntryLocation(eventBody.script.name, eventBody.sourceLine, eventBody.sourceColumn);
return;
}
this._sendBreakpointStoppedEvent(id);
return;
}
// in order to identify debugger statements extract source at current location
if (eventBody.sourceLineText && typeof eventBody.sourceColumn === 'number') {
let source = eventBody.sourceLineText.substr(eventBody.sourceColumn);
if (source.indexOf('debugger') === 0) {
this._gotDebuggerEvent = true;
this._sendStoppedEvent('debugger_statement');
return;
}
}
// must be the result of a 'step'
let reason: ReasonType = 'step';
if (this._restartFramePending) {
this._restartFramePending = false;
reason = 'frame_entry';
}
if (!this._disableSkipFiles) {
// should we continue until we find a better place to stop?
if ((this._smartStep && this._sourceMaps) || this._skipFiles) {
this._skipGenerated(eventBody).then(r => {
if (r) {
this._node.command('continue', { stepaction: 'in' });
this._smartStepCount++;
} else {
this._sendStoppedEvent(<ReasonType>reason);
}
});
return;
}
}
this._sendStoppedEvent(reason);
}
private _sendBreakpointStoppedEvent(breakpointId: number): void {
// evaluate hit counts
let ibp = this._hitCounts.get(breakpointId);
if (ibp) {
ibp.hitCount++;
if (ibp.hitter && !ibp.hitter(ibp.hitCount)) {
this._node.command('continue');
return;
}
}
this._sendStoppedEvent('breakpoint');
}
private _sendStoppedEvent(reason: ReasonType, description?: string, exception_text?: string): void {
if (this._smartStepCount > 0) {
this.log('ss', `_handleNodeBreakEvent: ${this._smartStepCount} steps skipped`);
this._smartStepCount = 0;
}
const e = new StoppedEvent(reason, NodeDebugSession.DUMMY_THREAD_ID, exception_text);
if (!description) {
switch (reason) {
case 'step':
description = localize('reason.description.step', "Paused on step");
break;
case 'breakpoint':
description = localize('reason.description.breakpoint', "Paused on breakpoint");
break;
case 'exception':
description = localize('reason.description.exception', "Paused on exception");
break;
case 'pause':
description = localize('reason.description.user_request', "Paused on user request");
break;
case 'entry':
description = localize('reason.description.entry', "Paused on entry");
break;
case 'debugger_statement':
description = localize('reason.description.debugger_statement', "Paused on debugger statement");
break;
case 'frame_entry':
description = localize('reason.description.restart', "Paused on frame entry");
break;
}
}
(<DebugProtocol.StoppedEvent>e).body.description = description;
this.sendEvent(e);
}
private isSkipped(path: string): boolean {
return this._skipFiles ? PathUtils.multiGlobMatches(this._skipFiles, path) : false;
}
/**
* Returns true if a source location of the given event should be skipped.
*/
private _skip(event: V8EventBody) : boolean {
if (this._skipFiles) {
let path = this._scriptToPath(event.script);
// if launch.json defines localRoot and remoteRoot try to convert remote path back to a local path
let localPath = this._remoteToLocal(path);
return PathUtils.multiGlobMatches(this._skipFiles, localPath);
}
return false;
}
/**
* Returns true if a source location of the given event should be skipped.
*/
private _skipGenerated(event: V8EventBody) : Promise<boolean> {
let path = this._scriptToPath(event.script);
// if launch.json defines localRoot and remoteRoot try to convert remote path back to a local path
let localPath = this._remoteToLocal(path);
if (this._skipFiles) {
if (PathUtils.multiGlobMatches(this._skipFiles, localPath)) {
return Promise.resolve(true);
}
return Promise.resolve(false);
}
if (this._smartStep) {
// try to map
let line = event.sourceLine;
let column = this._adjustColumn(line, event.sourceColumn);
return this._sourceMaps.CannotMapLine(localPath, null, line, column).then(skip => {
return skip;
});
}
return Promise.resolve(false);
}
private toggleSkippingResource(response: DebugProtocol.Response, resource: string) {
resource = decodeURI(<string>URL.parse(resource).pathname);
if (this.isSkipped(resource)) {
if (!this._skipFiles) {
this._skipFiles = new Array<string>();
}
this._skipFiles.push('!' + resource);
} else {
if (!this._skipFiles) {
this._skipFiles = new Array<string>();
}
this._skipFiles.push(resource);
}
this.sendResponse(response);
}
/**
* create a path for a script following these rules:
* - script name is an absolute path: return name as is
* - script name is an internal module: return "<node_internals/name"
* - script has no name: return "<node_internals/VMnnn" where nnn is the script ID
*/
private _scriptToPath(script: V8Script): string {
let name = script.name;
if (name) {
if (PathUtils.isAbsolutePath(name)) {
return name;
}
} else {
name = `VM${script.id}`;
}
return `${NodeDebugSession.NODE_INTERNALS}/${name}`;
}
/**
* create a Source for a script following these rules:
* - script name is an absolute path: return name as is
* - script name is an internal module: return "<node_internals/name"
* - script has no name: return "<node_internals/VMnnn" where nnn is the script ID
*/
private _scriptToSource(script: V8Script): Source {
let path = script.name;
if (path) {
if (!PathUtils.isAbsolutePath(path)) {
path = `${NodeDebugSession.NODE_INTERNALS}/${path}`;
}
} else {
path = `${NodeDebugSession.NODE_INTERNALS}/VM${script.id}`;
}
return new Source(Path.basename(path), path, this._getScriptIdHandle(script.id));
}
/**
* Special treatment for internal modules:
* we remove the '<node_internals>/' or '<node_internals>\' prefix and return either the name of the module or its ID
*/
private _pathToScript(path: string): number | string {
const result = NodeDebugSession.NODE_INTERNALS_VM.exec(path);
if (result && result.length >= 2) {
return + result[1];
}
return path.replace(NodeDebugSession.NODE_INTERNALS_PREFIX, '');
}
/**
* clear everything that is no longer valid after a new stopped event.
*/
private _stopped(reason: string): void {
this._stoppedReason = reason;
this.log('la', `_stopped: got ${reason} event from node`);
this._exception = undefined;
this._variableHandles.reset();
this._frameHandles.reset();
this._refCache = new Map<number, V8Object>();
this.log('rc', `_stopped: new ref cache`);
}
/**
* The debug session has terminated.
*/
private _terminated(reason: string): void {
this.log('la', `_terminated: ${reason}`);
if (!this._isTerminated) {
this._isTerminated = true;
if (this._restartMode && this._attachSuccessful && !this._inShutdown) {
this.sendEvent(new TerminatedEvent({ port: this._port }));
} else {
this.sendEvent(new TerminatedEvent());
}
}
}
//---- initialize request -------------------------------------------------------------------------------------------------
protected initializeRequest(response: DebugProtocol.InitializeResponse, args: DebugProtocol.InitializeRequestArguments): void {
this.log('la', `initializeRequest: adapterID: ${args.adapterID}`);
if (args.locale) {
localize = nls.config({ locale: args.locale })();
}
if (typeof args.supportsRunInTerminalRequest === 'boolean') {
this._supportsRunInTerminalRequest = args.supportsRunInTerminalRequest;
}
//---- Send back feature and their options
response.body = response.body || {};
// This debug adapter supports the configurationDoneRequest.
response.body.supportsConfigurationDoneRequest = true;
// This debug adapter supports function breakpoints.
response.body.supportsFunctionBreakpoints = true;
// This debug adapter supports conditional breakpoints.
response.body.supportsConditionalBreakpoints = true;
// This debug adapter does not support a side effect free evaluate request for data hovers.
response.body.supportsEvaluateForHovers = false;
// This debug adapter supports two exception breakpoint filters
response.body.exceptionBreakpointFilters = [
{
label: localize('exceptions.all', "All Exceptions"),
filter: 'all',
default: false
},
{
label: localize('exceptions.uncaught', "Uncaught Exceptions"),
filter: 'uncaught',
default: true
}
];
if (this._skipRejects) {
response.body.exceptionBreakpointFilters.push({
label: localize('exceptions.rejects', "Promise Rejects"),
filter: 'rejects',
default: false
});
}
// This debug adapter supports setting variables
response.body.supportsSetVariable = true;
// This debug adapter supports the restartFrame request
response.body.supportsRestartFrame = true;
// This debug adapter supports the completions request
response.body.supportsCompletionsRequest = true;
// This debug adapter supports the exception info request
response.body.supportsExceptionInfoRequest = true;
// This debug adapter supports delayed loading of stackframes
response.body.supportsDelayedStackTraceLoading = true;
// This debug adapter supports log points
response.body.supportsLogPoints = true;
// This debug adapter supports terminate request
response.body.supportsTerminateRequest = true;
this.sendResponse(response);
}
//---- launch request -----------------------------------------------------------------------------------------------------
protected launchRequest(response: DebugProtocol.LaunchResponse, args: LaunchRequestArguments): void {
if (this._processCommonArgs(response, args)) {
return;
}
if (args.__restart && typeof args.__restart.port === 'number') {
this._attach(response, args, args.__restart.port, undefined, args.timeout);
return;
}
this._noDebug = (typeof args.noDebug === 'boolean') && args.noDebug;
if (typeof args.console === 'string') {
switch (args.console) {
case 'internalConsole':
case 'integratedTerminal':
case 'externalTerminal':
this._console = args.console;
break;
default:
this.sendErrorResponse(response, 2028, localize('VSND2028', "Unknown console type '{0}'.", args.console));
return;
}
} else if (typeof args.externalConsole === 'boolean' && args.externalConsole) {
this._console = 'externalTerminal';
}
if (args.useWSL) {
if (!WSL.subsystemLinuxPresent()) {
this.sendErrorResponse(response, 2007, localize('attribute.wls.not.exist', "Cannot find Windows Subsystem Linux installation"));
return;
}
this._isWSL = true;
}
let runtimeExecutable = args.runtimeExecutable;
if (args.useWSL) {
runtimeExecutable = runtimeExecutable || NodeDebugSession.NODE;
} else if (runtimeExecutable) {
if (!Path.isAbsolute(runtimeExecutable)) {
const re = PathUtils.findOnPath(runtimeExecutable, args.env);
if (!re) {
this.sendErrorResponse(response, 2001, localize('VSND2001', "Cannot find runtime '{0}' on PATH. Make sure to have '{0}' installed.", '{_runtime}'), { _runtime: runtimeExecutable });
return;
}
runtimeExecutable = re;
} else {
const re = PathUtils.findExecutable(runtimeExecutable, args.env);
if (!re) {
this.sendNotExistErrorResponse(response, 'runtimeExecutable', runtimeExecutable);
return;
}
runtimeExecutable = re;
}
} else {
const re = PathUtils.findOnPath(NodeDebugSession.NODE, args.env);
if (!re) {
this.sendErrorResponse(response, 2001, localize('VSND2001', "Cannot find runtime '{0}' on PATH. Make sure to have '{0}' installed.", '{_runtime}'), { _runtime: NodeDebugSession.NODE });
return;
}
runtimeExecutable = re;
}
let runtimeArgs = args.runtimeArgs || [];
const programArgs = args.args || [];
let programPath = args.program;
if (programPath) {
if (!Path.isAbsolute(programPath)) {
this.sendRelativePathErrorResponse(response, 'program', programPath);
return;
}
if (!FS.existsSync(programPath)) {
if (!FS.existsSync(programPath + '.js')) {
this.sendNotExistErrorResponse(response, 'program', programPath);
return;
}
programPath += '.js';
}
programPath = Path.normalize(programPath);
if (PathUtils.normalizeDriveLetter(programPath) !== PathUtils.realPath(programPath)) {
this.outLine(localize('program.path.case.mismatch.warning', "Program path uses differently cased character as file on disk; this might result in breakpoints not being hit."));
}
}
if (!args.runtimeArgs && !this._noDebug) {
runtimeArgs = [ '--nolazy' ];
}
if (programPath) {
if (NodeDebugSession.isJavaScript(programPath)) {
if (this._sourceMaps) {
// if programPath is a JavaScript file and sourceMaps are enabled, we don't know whether
// programPath is the generated file or whether it is the source (and we need source mapping).
// Typically this happens if a tool like 'babel' or 'uglify' is used (because they both transpile js to js).
// We use the source maps to find a 'source' file for the given js file.
this._sourceMaps.MapPathFromSource(programPath).then(generatedPath => {
if (generatedPath && generatedPath !== programPath) {
// programPath must be source because there seems to be a generated file for it
this.log('sm', `launchRequest: program '${programPath}' seems to be the source; launch the generated file '${generatedPath}' instead`);
programPath = generatedPath;
} else {
this.log('sm', `launchRequest: program '${programPath}' seems to be the generated file`);
}
this.launchRequest2(response, args, programPath, programArgs, <string> runtimeExecutable, runtimeArgs);
});
return;
}
} else {
// node cannot execute the program directly
if (!this._sourceMaps) {
this.sendErrorResponse(response, 2002, localize('VSND2002', "Cannot launch program '{0}'; configuring source maps might help.", '{path}'), { path: programPath });
return;
}
this._sourceMaps.MapPathFromSource(programPath).then(generatedPath => {
if (!generatedPath) { // cannot find generated file
if (args.outFiles || args.outDir) {
this.sendErrorResponse(response, 2009, localize('VSND2009', "Cannot launch program '{0}' because corresponding JavaScript cannot be found.", '{path}'), { path: programPath });
} else {
this.sendErrorResponse(response, 2003, localize('VSND2003', "Cannot launch program '{0}'; setting the '{1}' attribute might help.", '{path}', 'outFiles'), { path: programPath });
}
return;
}
this.log('sm', `launchRequest: program '${programPath}' seems to be the source; launch the generated file '${generatedPath}' instead`);
programPath = generatedPath;
this.launchRequest2(response, args, programPath, programArgs, <string> runtimeExecutable, runtimeArgs);
});
return;
}
}
this.launchRequest2(response, args, programPath, programArgs, runtimeExecutable, runtimeArgs);
}
private async launchRequest2(response: DebugProtocol.LaunchResponse, args: LaunchRequestArguments, programPath: string, programArgs: string[], runtimeExecutable: string, runtimeArgs: string[]): Promise<void> {
let program: string | undefined;
let workingDirectory = args.cwd;
if (workingDirectory) {
if (!Path.isAbsolute(workingDirectory)) {
this.sendRelativePathErrorResponse(response, 'cwd', workingDirectory);
return;
}
if (!FS.existsSync(workingDirectory)) {
this.sendNotExistErrorResponse(response, 'cwd', workingDirectory);
return;
}
// if working dir is given and if the executable is within that folder, we make the executable path relative to the working dir
if (programPath) {
program = Path.relative(workingDirectory, programPath);
}
}
else if (programPath) { // should not happen
// if no working dir given, we use the direct folder of the executable