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
3112 lines (2563 loc) · 98.4 KB
/
Copy pathnodeDebug.ts
File metadata and controls
3112 lines (2563 loc) · 98.4 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 {
DebugSession, Thread, Source, StackFrame, Scope, Variable, Breakpoint,
TerminatedEvent, InitializedEvent, StoppedEvent, OutputEvent,
Handles, ErrorDestination
} from 'vscode-debugadapter';
import {DebugProtocol} from 'vscode-debugprotocol';
import {
NodeV8Protocol, NodeV8Event, NodeV8Response,
V8SetBreakpointArgs, V8SetExceptionBreakArgs,
V8BacktraceResponse, V8ScopeResponse, V8EvaluateResponse, V8FrameResponse,
V8EventBody,
V8Ref, V8Handle, V8Property, V8Object, V8Simple, V8Function, V8Frame, V8Scope, V8Script
} from './nodeV8Protocol';
import {ISourceMaps, SourceMaps, Bias} from './sourceMaps';
import {Terminal, TerminalError} from './terminal';
import * as PathUtils from './pathUtilities';
import * as CP from 'child_process';
import * as Net from 'net';
import * as Path from 'path';
import * as FS from 'fs';
import * as nls from 'vscode-nls';
const localize = nls.config(process.env.VSCODE_NLS_CONFIG)();
export interface VariableContainer {
Expand(session: NodeDebugSession): Promise<Variable[]>;
SetValue(session: NodeDebugSession, name: string, value: string): Promise<string>;
}
export class Expander implements VariableContainer {
public static SET_VALUE_ERROR = localize('setVariable.error', "Setting value not supported");
private _expanderFunction : () => Promise<Variable[]>;
public constructor(func: () => Promise<Variable[]>) {
this._expanderFunction = func;
}
public Expand(session: NodeDebugSession) : Promise<Variable[]> {
return this._expanderFunction();
}
public SetValue(session: NodeDebugSession, name: string, value: string) : Promise<string> {
return Promise.reject(new Error(Expander.SET_VALUE_ERROR));
}
}
export class ArrayContainer implements VariableContainer {
private _array: V8Object;
private _length: number;
private _chunkSize: number;
public constructor(array: V8Object, length: number, chunkSize: number) {
this._array = array;
this._length = length;
this._chunkSize = chunkSize;
}
public Expand(session: NodeDebugSession) : Promise<Variable[]> {
// first add named properties then add ranges
return session._createProperties(this._array, 'named').then(variables => {
for (let start = 0; start < this._length; start += this._chunkSize) {
const end = Math.min(start + this._chunkSize, this._length)-1;
const count = end-start+1;
variables.push(new Variable(`[${start}..${end}]`, ' ', session._variableHandles.create(new RangeContainer(this._array, start, count))));
}
return variables;
});
}
public SetValue(session: NodeDebugSession, name: string, value: string) : Promise<string> {
return session._setPropertyValue(this._array.handle, name, value);
}
}
export class RangeContainer implements VariableContainer {
private _array: V8Object;
private _start: number;
private _count: number;
public constructor(array, start: number, count: number) {
this._array = array;
this._start = start;
this._count = count;
}
public Expand(session: NodeDebugSession) : Promise<Variable[]> {
// experimental support for long arrays not relying on code injection
//return session._createLargeArrayElements(this._array, this._start, this._count);
return session._createProperties(this._array, 'range', this._start, this._count);
}
public SetValue(session: NodeDebugSession, name: string, value: string) : Promise<string> {
return session._setPropertyValue(this._array.handle, name, value);
}
}
export class PropertyContainer implements VariableContainer {
private _object: V8Object;
private _this: V8Object;
public constructor(obj: V8Object, ths?: V8Object) {
this._object = obj;
this._this = ths;
}
public Expand(session: NodeDebugSession) : Promise<Variable[]> {
return session._createProperties(this._object, 'all').then(variables => {
if (this._this) {
return session._createVariable('this', this._this).then(variable => {
variables.push(variable);
return variables;
});
} else {
return variables;
}
});
}
public SetValue(session: NodeDebugSession, name: string, value: string) : Promise<string> {
return session._setPropertyValue(this._object.handle, name, value);
}
}
export class ScopeContainer implements VariableContainer {
private _frame: number;
private _scope: number;
private _object: V8Object;
private _this: V8Object;
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) : Promise<Variable[]> {
return session._createProperties(this._object, 'all').then(variables => {
if (this._this) {
return session._createVariable('this', this._this).then(variable => {
variables.push(variable);
return variables;
});
} else {
return variables;
}
});
}
public SetValue(session: NodeDebugSession, name: string, value: string) : Promise<string> {
return session._setVariableValue(this._frame, this._scope, name, value);
}
}
class Script {
contents: string;
constructor(script: V8Script) {
this.contents = script.source;
}
}
class InternalSourceBreakpoint {
line: number;
orgLine: number;
column: number;
orgColumn: number;
condition: string;
constructor(line: number, column: number = 0, condition?: string) {
this.line = this.orgLine = line;
this.column = this.orgColumn = column;
this.condition = condition;
}
}
/**
* 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;
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?: 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 disabled. */
sourceMaps?: boolean;
/** Where to look for the generated code. Only used if sourceMaps is true. */
outDir?: string;
/** Try to automatically step over uninteresting source. */
smartStep?: boolean;
/** Step back supported. */
stepBack?: boolean;
}
/**
* 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; };
/** If true launch the target in an external console. */
externalConsole?: boolean;
}
/**
* This interface should always match the schema found in the node-debug extension manifest.
*/
interface AttachRequestArguments extends DebugProtocol.AttachRequestArguments, CommonArguments {
/** Request frontend to restart session on termination. */
restart?: boolean;
/** Node's root directory. */
remoteRoot?: string;
/** VS Code's root directory. */
localRoot?: string;
/** Send a USR1 signal to this process. */
processId?: string;
}
export class NodeDebugSession extends DebugSession {
private static MAX_STRING_LENGTH = 10000; // max string size to return in 'evaluate' request
private static NODE_TERMINATION_POLL_INTERVAL = 3000;
private static ATTACH_TIMEOUT = 10000;
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_SHEBANG_MATCHER = new RegExp('#! */usr/bin/env +node');
private static LONG_STRING_MATCHER = /\.\.\. \(length: [0-9]+\)$/;
// tracing
private _trace: string[];
private _traceAll = false;
// options
private _tryToInjectExtension = true;
private _chunkSize = 100; // chunk size for large data structures
private _smartStep = false; // try to automatically step over uninteresting source
// session state
private _adapterID: string;
private _node: NodeV8Protocol;
private _nodeProcessId: number = -1; // pid of the node runtime
private _functionBreakpoints = new Array<number>(); // node function breakpoint ids
private _scripts = new Map<number, Script>();
// session configurations
private _noDebug = false;
private _attachMode = false;
private _localRoot: string;
private _remoteRoot: string;
private _restartMode = false;
private _sourceMaps: ISourceMaps;
private _externalConsole: boolean;
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 _terminalProcess: CP.ChildProcess; // the terminal process or undefined
private _pollForNodeProcess = false;
private _exception: V8Object;
private _lastStoppedEvent: DebugProtocol.StoppedEvent;
private _stoppedReason: string;
private _nodeInjectionAvailable = false;
private _needContinue: boolean;
private _needBreakpointEvent: boolean;
private _gotEntryEvent: boolean;
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;
public constructor() {
super();
// 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(event.body);
});
this._node.on('exception', (event: NodeV8Event) => {
this._stopped('exception');
this._handleNodeBreakEvent(event.body);
});
/*
this._node.on('beforeCompile', (event: NodeV8Event) => {
this.outLine(`beforeCompile ${event.body.name}`);
});
*/
this._node.on('afterCompile', (event: NodeV8Event) => {
this._handleNodeAfterCompileEvent(event.body);
});
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}`);
});
*/
}
/**
* Experimental support for SystemJS module loader (https://github.com/systemjs/systemjs)
*
* Tries to figure out whether JavaScript code has been dynamically generated
* and whether it contains a source map reference.
* If this is the case try to reload breakpoints.
*/
private _handleNodeAfterCompileEvent(eventBody: V8EventBody) {
if (this._sourceMaps) { // this only applies if source maps are enabled
let path = eventBody.script.name;
if (path && Path.extname(path) === '.js!transpiled' && path.indexOf('file://') === 0) {
path = path.substring('file://'.length);
if (!FS.existsSync(path)) { // path does not exist locally.
const script_id = eventBody.script.id;
this._loadScript(script_id).then(script => {
const sources = this._sourceMaps.MapPathToSource(path, script.contents);
if (sources && sources.length >= 0) {
this.outLine(`afterCompile: ${path} maps to ${sources[0]}`);
// trigger resending breakpoints
this.sendEvent(new InitializedEvent());
}
}).catch(err => {
// ignore
});
}
}
}
}
/**
* Analyse why node has stopped and sends StoppedEvent if necessary.
*/
private _handleNodeBreakEvent(eventBody: V8EventBody) : void {
/*
// workaround: load sourcemap for this location to populate cache
if (this._sourceMaps) {
let path = body.script.name;
if (path && PathUtils.isAbsolutePath(path)) {
path = this._remoteToLocal(path);
this._sourceMaps.MapToSource(path, null, 0, 0);
}
}
*/
let isEntry = false;
let reason: string;
let exception_text: string;
// is exception?
if (eventBody.exception) {
this._exception = eventBody.exception;
exception_text = eventBody.exception.text;
reason = localize({ key: 'reason.exception', comment: ['https://github.com/Microsoft/vscode/issues/4568'] }, "exception");
}
// is breakpoint?
if (!reason) {
const breakpoints = eventBody.breakpoints;
if (isArray(breakpoints) && breakpoints.length > 0) {
const id = breakpoints[0];
if (!this._gotEntryEvent && id === 1) { // 'stop on entry point' is implemented as a breakpoint with id 1
isEntry = true;
this.log('la', '_analyzeBreak: suppressed stop-on-entry event');
reason = localize({ key: 'reason.entry', comment: ['https://github.com/Microsoft/vscode/issues/4568'] }, "entry");
this._rememberEntryLocation(eventBody.script.name, eventBody.sourceLine, eventBody.sourceColumn);
} else {
reason = localize({ key: 'reason.breakpoint', comment: ['https://github.com/Microsoft/vscode/issues/4568'] }, "breakpoint");
}
}
}
// is debugger statement?
if (!reason) {
const sourceLine = eventBody.sourceLineText;
if (sourceLine && sourceLine.indexOf('debugger') >= 0) {
reason = localize({ key: 'reason.debugger_statement', comment: ['https://github.com/Microsoft/vscode/issues/4568'] }, "debugger statement");
}
}
// no reason yet: must be the result of a 'step'
if (!reason) {
// should we continue until we find a better place to stop?
if (this._smartStep && this._skipGenerated(eventBody)) {
this._node.command('continue', { stepaction: 'in' });
this._smartStepCount++;
return null;
}
reason = localize({ key: 'reason.step', comment: ['https://github.com/Microsoft/vscode/issues/4568'] }, "step");
}
this._lastStoppedEvent = new StoppedEvent(reason, NodeDebugSession.DUMMY_THREAD_ID, exception_text);
if (!isEntry) {
if (this._smartStepCount > 0) {
this.log('ss', `_handleNodeBreakEvent: ${this._smartStepCount} steps skipped`);
this._smartStepCount = 0;
}
this.sendEvent(this._lastStoppedEvent);
}
}
/**
* Returns true if a source location should be skipped.
*/
private _skipGenerated(event: V8EventBody) : boolean {
if (!this._sourceMaps) {
// proceed as normal
return false;
}
let line = event.sourceLine;
let column = this._adjustColumn(line, event.sourceColumn);
let remotePath = event.script.name;
if (remotePath && PathUtils.isAbsolutePath(remotePath)) {
// if launch.json defines localRoot and remoteRoot try to convert remote path back to a local path
let localPath = this._remoteToLocal(remotePath);
// try to map
let mapresult = this._sourceMaps.MapToSource(localPath, null, line, column, Bias.LEAST_UPPER_BOUND);
if (!mapresult) { // try using the other bias option
mapresult = this._sourceMaps.MapToSource(localPath, null, line, column, Bias.GREATEST_LOWER_BOUND);
}
if (mapresult) {
return false;
}
}
// skip everything
return true;
}
/**
* 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._terminalProcess) {
// if the debug adapter owns a terminal,
// we delay the TerminatedEvent so that the user can see the result of the process in the terminal.
return;
}
if (!this._isTerminated) {
this._isTerminated = true;
if (this._restartMode && !this._inShutdown) {
this.sendEvent(new TerminatedEvent(true));
} else {
this.sendEvent(new TerminatedEvent());
}
}
}
//---- initialize request -------------------------------------------------------------------------------------------------
protected initializeRequest(response: DebugProtocol.InitializeResponse, args: DebugProtocol.InitializeRequestArguments): void {
this.log('la', `initializeRequest: adapterID: ${args.adapterID}`);
this._adapterID = args.adapterID;
//---- Send back feature and their options
// 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
}
];
response.body.supportsSetVariable = true;
this.sendResponse(response);
}
//---- launch request -----------------------------------------------------------------------------------------------------
protected launchRequest(response: DebugProtocol.LaunchResponse, args: LaunchRequestArguments): void {
if (this._processCommonArgs(response, args)) {
return;
}
this._noDebug = (typeof args.noDebug === 'boolean') && args.noDebug;
this._externalConsole = (typeof args.externalConsole === 'boolean') && args.externalConsole;
const port = args.port || random(3000, 50000);
const address = args.address;
const timeout = args.timeout;
let runtimeExecutable = args.runtimeExecutable;
if (runtimeExecutable) {
if (!Path.isAbsolute(runtimeExecutable)) {
this.sendRelativePathErrorResponse(response, 'runtimeExecutable', runtimeExecutable);
return;
}
if (!FS.existsSync(runtimeExecutable)) {
this.sendNotExistErrorResponse(response, 'runtimeExecutable', runtimeExecutable);
return;
}
} else {
if (!Terminal.isOnPath(NodeDebugSession.NODE)) {
this.sendErrorResponse(response, 2001, localize('VSND2001', "Cannot find runtime '{0}' on PATH.", '{_runtime}'), { _runtime: NodeDebugSession.NODE });
return;
}
runtimeExecutable = NodeDebugSession.NODE; // use node from PATH
}
const runtimeArgs = args.runtimeArgs || [];
const programArgs = args.args || [];
// special code for 'extensionHost' debugging
if (this._adapterID === 'extensionHost') {
// we always launch in 'debug-brk' mode, but we only show the break event if 'stopOnEntry' attribute is true.
let launchArgs = [ runtimeExecutable ];
if (!this._noDebug) {
launchArgs.push(`--debugBrkPluginHost=${port}`);
}
launchArgs = launchArgs.concat(runtimeArgs, programArgs);
this._sendLaunchCommandToConsole(launchArgs);
const cmd = CP.spawn(runtimeExecutable, launchArgs.slice(1));
cmd.on('error', (err) => {
this._terminated(`failed to launch extensionHost (${err})`);
});
this._captureOutput(cmd);
// we are done!
this.sendResponse(response);
return;
}
let programPath = args.program;
if (programPath) {
if (!Path.isAbsolute(programPath)) {
this.sendRelativePathErrorResponse(response, 'program', programPath);
return;
}
if (!FS.existsSync(programPath)) {
this.sendNotExistErrorResponse(response, 'program', programPath);
return;
}
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."));
}
} else {
this.sendAttributeMissingErrorResponse(response, 'program');
return;
}
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.
const generatedPath = this._sourceMaps.MapPathFromSource(programPath);
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`);
}
}
} 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;
}
const generatedPath = this._sourceMaps.MapPathFromSource(programPath);
if (!generatedPath) { // cannot find generated file
this.sendErrorResponse(response, 2003, localize('VSND2003', "Cannot launch program '{0}'; setting the '{1}' attribute might help.", '{path}', 'outDir'), { path: programPath });
return;
}
this.log('sm', `launchRequest: program '${programPath}' seems to be the source; launch the generated file '${generatedPath}' instead`);
programPath = generatedPath;
}
let program: string;
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
program = Path.relative(workingDirectory, programPath);
}
else { // should not happen
// if no working dir given, we use the direct folder of the executable
workingDirectory = Path.dirname(programPath);
program = Path.basename(programPath);
}
// we always break on entry (but if user did not request this, we will not stop in the UI).
let launchArgs = [ runtimeExecutable ];
if (! this._noDebug) {
launchArgs.push(`--debug-brk=${port}`);
}
launchArgs = launchArgs.concat(runtimeArgs, [ program ], programArgs);
if (this._externalConsole) {
Terminal.launchInTerminal(workingDirectory, launchArgs, args.env).then(term => {
if (term) {
// if we got a terminal process, we will track it
this._terminalProcess = term;
term.on('exit', () => {
this._terminalProcess = null;
this._terminated('terminal exited');
});
}
// since node starts in a terminal, we cannot track it with an 'exit' handler
// plan for polling after we have gotten the process pid.
this._pollForNodeProcess = true;
if (this._noDebug) {
this.sendResponse(response);
} else {
this._attach(response, port, address, timeout);
}
}).catch((error: TerminalError) => {
this.sendErrorResponseWithInfoLink(response, 2011, localize('VSND2011', "Cannot launch debug target in terminal ({0}).", '{_error}'), { _error: error.message }, error.linkId );
this._terminated('terminal error: ' + error.message);
});
} else {
this._sendLaunchCommandToConsole(launchArgs);
// merge environment variables into a copy of the process.env
const env = extendObject(extendObject( { }, process.env), args.env);
const options = {
cwd: workingDirectory,
env: env
};
const nodeProcess = CP.spawn(runtimeExecutable, launchArgs.slice(1), options);
nodeProcess.on('error', (error) => {
this.sendErrorResponse(response, 2017, localize('VSND2017', "Cannot launch debug target ({0}).", '{_error}'), { _error: error.message }, ErrorDestination.Telemetry | ErrorDestination.User );
this._terminated(`failed to launch target (${error})`);
});
nodeProcess.on('exit', () => {
this._terminated('target exited');
});
nodeProcess.on('close', (code) => {
this._terminated('target closed');
});
this._nodeProcessId = nodeProcess.pid;
this._captureOutput(nodeProcess);
if (this._noDebug) {
this.sendResponse(response);
} else {
this._attach(response, port, address, timeout);
}
}
}
private _sendLaunchCommandToConsole(args: string[]) {
// print the command to launch the target to the debug console
let cli = '';
for (let a of args) {
if (a.indexOf(' ') >= 0) {
cli += '\'' + a + '\'';
} else {
cli += a;
}
cli += ' ';
}
this.outLine(cli);
}
private _captureOutput(process: CP.ChildProcess) {
process.stdout.on('data', (data: string) => {
this.sendEvent(new OutputEvent(data.toString(), 'stdout'));
});
process.stderr.on('data', (data: string) => {
this.sendEvent(new OutputEvent(data.toString(), 'stderr'));
});
}
/**
* returns true on error.
*/
private _processCommonArgs(response: DebugProtocol.Response, args: CommonArguments): boolean {
if (typeof args.trace === 'string') {
this._trace = args.trace.split(',');
this._traceAll = this._trace.indexOf('all') >= 0;
}
this._stepBack = (typeof args.stepBack === 'boolean') && args.stepBack;
this._smartStep = (typeof args.smartStep === 'boolean') && args.smartStep;
this._stopOnEntry = (typeof args.stopOnEntry === 'boolean') && args.stopOnEntry;
if (!this._sourceMaps) {
if (typeof args.sourceMaps === 'boolean' && args.sourceMaps) {
const generatedCodeDirectory = args.outDir;
if (generatedCodeDirectory) {
if (!Path.isAbsolute(generatedCodeDirectory)) {
this.sendRelativePathErrorResponse(response, 'outDir', generatedCodeDirectory);
return true;
}
if (!FS.existsSync(generatedCodeDirectory)) {
this.sendNotExistErrorResponse(response, 'outDir', generatedCodeDirectory);
return true;
}
}
this._sourceMaps = new SourceMaps(this, generatedCodeDirectory);
}
}
return false;
}
//---- attach request -----------------------------------------------------------------------------------------------------
protected attachRequest(response: DebugProtocol.AttachResponse, args: AttachRequestArguments): void {
if (this._processCommonArgs(response, args)) {
return;
}
if (this._adapterID === 'extensionHost') {
// in EH mode 'attach' means 'launch' mode
this._attachMode = false;
} else {
this._attachMode = true;
}
if (typeof args.restart === 'boolean') {
this._restartMode = args.restart;
}
if (args.localRoot) {
const localRoot = args.localRoot;
if (!Path.isAbsolute(localRoot)) {
this.sendRelativePathErrorResponse(response, 'localRoot', localRoot);
return;
}
if (!FS.existsSync(localRoot)) {
this.sendNotExistErrorResponse(response, 'localRoot', localRoot);
return;
}
this._localRoot = localRoot;
}
this._remoteRoot = args.remoteRoot;
// if a processId is specified, try to bring the process into debug mode.
if (typeof args.processId === 'string') {
const pid_string = args.processId.trim();
if (/^([0-9]+)$/.test(pid_string)) {
const pid = Number(pid_string);
try {
if (process.platform === 'win32') {
// regular node has an undocumented API function for forcing another node process into debug mode.
// (<any>process)._debugProcess(pid);
// But since we are running on Electron's node, process._debugProcess doesn't work (for unknown reasons).
// So we use a regular node instead:
const command = `node -e process._debugProcess(${pid})`;
CP.execSync(command);
} else {
process.kill(pid, 'SIGUSR1');
}
} catch (e) {
this.sendErrorResponse(response, 2021, localize('VSND2021', "Attach to process: cannot enable debug mode for process '{0}' ({1}).", pid, e));
return;
}
} else {
this.sendErrorResponse(response, 2006, localize('VSND2006', "Attach to process: '{0}' doesn't look like a process id.", pid_string));
return;
}
}
this._attach(response, args.port, args.address, args.timeout);
}
/*
* shared code used in launchRequest and attachRequest
*/
private _attach(response: DebugProtocol.Response, port: number, address: string, timeout: number): void {
if (!port) {
port = 5858;
}
if (!address || address === 'localhost') {
address = '127.0.0.1';
}
if (!timeout) {
timeout = NodeDebugSession.ATTACH_TIMEOUT;
}
this.log('la', `_attach: address: ${address} port: ${port}`);
let connected = false;
const socket = new Net.Socket();
socket.connect(port, address);
socket.on('connect', err => {
this.log('la', '_attach: connected');
connected = true;
this._node.startDispatch(socket, socket);
this._initialize(response);
});
const endTime = new Date().getTime() + timeout;
socket.on('error', err => {
if (connected) {
// since we are connected this error is fatal
this._terminated('socket error');
} else {
// we are not yet connected so retry a few times
if (err.code === 'ECONNREFUSED' || err.code === 'ECONNRESET') {
const now = new Date().getTime();
if (now < endTime) {
setTimeout(() => {
this.log('la', '_attach: retry socket.connect');
socket.connect(port);
}, 200); // retry after 200 ms
} else {
this.sendErrorResponse(response, 2009, localize('VSND2009', "Cannot connect to runtime process (timeout after {0} ms).", '{_timeout}'), { _timeout: timeout });
}
} else {
this.sendErrorResponse(response, 2010, localize('VSND2010', "Cannot connect to runtime process (reason: {0}).", '{_error}'), { _error: err.message });
}
}
});
socket.on('end', err => {
this._terminated('socket end');
});
}
private _initialize(response: DebugProtocol.Response, retryCount: number = 0) : void {
this._node.command('evaluate', { expression: 'process.pid', global: true }, (resp: V8EvaluateResponse) => {