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
2037 lines (1733 loc) · 62.9 KB
/
Copy pathnodeDebug.ts
File metadata and controls
2037 lines (1733 loc) · 62.9 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, ErrorDestination} from '../common/debugSession';
import {NodeV8Protocol, NodeV8Event, NodeV8Response} from './nodeV8Protocol';
import {Handles} from '../common/handles';
import {ISourceMaps, SourceMaps} from './sourceMaps';
import {Terminal} 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';
const RANGESIZE = 1000;
export interface Expandable {
Expand(session: NodeDebugSession, results: Array<Variable>, done: () => void): void;
}
export class PropertyExpander implements Expandable {
private _object: any;
private _this: any;
protected _mode: string;
protected _start: number;
protected _end: number;
public constructor(obj: any, ths?: any) {
this._object = obj;
this._this = ths;
this._mode = 'all';
this._start = 0;
this._end = -1;
}
public Expand(session: NodeDebugSession, variables: Array<Variable>, done: () => void): void {
session._addProperties(variables, this._object, this._mode, this._start, this._end, () => {
if (this._this) {
session._addVariable(variables, 'this', this._this, done);
} else {
done();
}
});
}
}
export class PropertyRangeExpander extends PropertyExpander {
public constructor(obj: any, start: number, end: number) {
super(obj, null);
this._mode = 'range';
this._start = start;
this._end = end;
}
}
export class ArrayExpander implements Expandable {
private _object: any;
private _size: number;
public constructor(obj: any, size: number) {
this._object = obj;
this._size = size;
}
public Expand(session: NodeDebugSession, variables: Array<Variable>, done: () => void): void {
// first add named properties
session._addProperties(variables, this._object, 'named', 0, -1, () => {
// then add indexed properties as ranges
for (let start = 0; start < this._size; start += RANGESIZE) {
let end = Math.min(start + RANGESIZE, this._size)-1;
variables.push(new Variable(`[${start}..${end}]`, ' ', session._variableHandles.create(new PropertyRangeExpander(this._object, start, end))));
}
done();
});
}
}
/**
* This interface should always match the schema found in the node-debug extension manifest.
*/
export interface SourceMapsArguments {
/** 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;
}
/**
* This interface should always match the schema found in the node-debug extension manifest.
*/
export interface LaunchRequestArguments extends SourceMapsArguments {
/** An absolute path to the program to debug. */
program: string;
/** Automatically stop target after launch. If not specified, target does not stop. */
stopOnEntry?: boolean;
/** 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.
*/
export interface AttachRequestArguments extends SourceMapsArguments {
/** The local port to attach to */
port: number;
}
export class NodeDebugSession extends DebugSession {
private static TRACE = false;
private static TRACE_INITIALISATION = false;
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_EXTENSION = 'debugExtension.js';
private static NODE_TERMINATION_POLL_INTERVAL = 3000;
private static NODE_SHEBANG_MATCHER = new RegExp('#! */usr/bin/env +node');
// stop reasons
private static ENTRY_REASON = "entry";
private static STEP_REASON = "step";
private static BREAKPOINT_REASON = "breakpoint";
private static EXCEPTION_REASON = "exception";
private static DEBUGGER_REASON = "debugger statement";
private static USER_REQUEST_REASON = "user request";
private static ANON_FUNCTION = "(anonymous function)";
private static SCOPE_NAMES = [ "Global", "Local", "With", "Closure", "Catch", "Block", "Script" ];
private static LARGE_DATASTRUCTURE_TIMEOUT = "<...>"; // "<large data structure timeout>";
private _adapterID: string;
public _variableHandles = new Handles<Expandable>();
public _frameHandles = new Handles<any>();
private _refCache = new Map<number, any>();
private _externalConsole: boolean;
private _isTerminated: boolean;
private _inShutdown: boolean;
private _terminalProcess: CP.ChildProcess; // the terminal process or undefined
private _nodeProcessId: number = -1; // pid of the node runtime
private _node: NodeV8Protocol;
private _exception;
private _lastStoppedEvent;
private _nodeExtensionsAvailable: boolean = false;
private _tryToExtendNode: boolean = true;
private _attachMode: boolean = false;
private _sourceMaps: ISourceMaps;
private _stopOnEntry: boolean;
private _needContinue: boolean;
private _needBreakpointEvent: boolean;
private _lazy: boolean; // whether node is in 'lazy' mode
private _gotEntryEvent: boolean;
private _entryPath: string;
private _entryLine: number;
private _entryColumn: number;
public constructor(debuggerLinesStartAt1: boolean, isServer: boolean = false) {
super(debuggerLinesStartAt1, isServer);
this._node = new NodeV8Protocol();
this._node.on('break', (event: NodeV8Event) => {
if (NodeDebugSession.TRACE_INITIALISATION) console.error('_init: got break event from node');
this._stopped();
this._lastStoppedEvent = this.createStoppedEvent(event.body);
if (this._lastStoppedEvent.body.reason === NodeDebugSession.ENTRY_REASON) {
if (NodeDebugSession.TRACE_INITIALISATION) console.error('_init: supressed stop-on-entry event');
} else {
this.sendEvent(this._lastStoppedEvent);
}
});
this._node.on('exception', (event: NodeV8Event) => {
this._stopped();
this._lastStoppedEvent = this.createStoppedEvent(event.body);
this.sendEvent(this._lastStoppedEvent);
});
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) => {
// console.error('diagnostic event: ' + event.body.reason);
});
}
/**
* clear everything that is no longer valid after a new stopped event.
*/
private _stopped(): void {
this._exception = undefined;
this._variableHandles.reset();
this._frameHandles.reset();
this._refCache = new Map<number, any>();
}
/**
* The debug session has terminated.
* If a port is given, this data is added to the event so that a client can try to reconnect.
*/
private _terminated(reason: string, reattachPort?: number): void {
if (NodeDebugSession.TRACE) console.error('_terminate: ' + reason);
if (this._terminalProcess) {
// delay the TerminatedEvent so that the user can see the result of the process in the terminal
return;
}
if (!this._isTerminated) {
this._isTerminated = true;
const e = new TerminatedEvent();
// piggyback the port to re-attach
if (reattachPort) {
if (!(<any>e).body) {
(<any>e).body = {};
}
(<any>e).body.extensionHost = {
reattachPort: reattachPort
};
}
this.sendEvent(e);
}
}
//---- initialize request -------------------------------------------------------------------------------------------------
protected initializeRequest(response: DebugProtocol.InitializeResponse, args: DebugProtocol.InitializeRequestArguments): void {
this._adapterID = args.adapterID;
this.sendResponse(response);
}
//---- launch request -----------------------------------------------------------------------------------------------------
protected launchRequest(response: DebugProtocol.LaunchResponse, args: LaunchRequestArguments): void {
this._externalConsole = (typeof args.externalConsole === 'boolean') && args.externalConsole;
this._stopOnEntry = (typeof args.externalConsole === 'boolean') && args.stopOnEntry;
this._initializeSourceMaps(args);
var port = random(3000, 50000);
let runtimeExecutable = this.convertClientPathToDebugger(args.runtimeExecutable);
if (runtimeExecutable) {
if (!FS.existsSync(runtimeExecutable)) {
this.sendErrorResponse(response, 2006, "runtime executable '{path}' does not exist", { path: runtimeExecutable });
return;
}
} else {
if (!Terminal.isOnPath(NodeDebugSession.NODE)) {
this.sendErrorResponse(response, 2001, "cannot find runtime '{_runtime}' on PATH", { _runtime: NodeDebugSession.NODE });
return;
}
runtimeExecutable = NodeDebugSession.NODE; // use node from PATH
}
const runtimeArgs = args.runtimeArgs || [];
const programArgs = args.args || [];
this._lazy = true; // node by default starts in '--lazy' mode
// special code for 'extensionHost' debugging
if (this._adapterID === 'extensionHost') {
let extensionHostData = (<any>args).extensionHostData;
if (extensionHostData) {
// re-attach to the received port
port = extensionHostData.reattachPort;
} else {
// make sure that we launch VSCode and not just electron pretending to be node
delete process.env['ATOM_SHELL_INTERNAL_RUN_AS_NODE'];
// we know that extensionHost is always launched with --nolazy
this._lazy = false;
// we always launch in 'debug-brk' mode, but we only show the break event if 'stopOnEntry' attribute is true.
const launchArgs = [ runtimeExecutable, `--debugBrkPluginHost=${port}` ].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);
}
// try to attach
setTimeout(() => {
this._attach(response, port, 3000);
}, 2000);
// we are done!
return;
}
let programPath = args.program;
if (programPath) {
programPath = this.convertClientPathToDebugger(programPath);
if (!FS.existsSync(programPath)) {
this.sendErrorResponse(response, 2007, "program '{path}' does not exist", { path: programPath });
return;
}
} else {
this.sendErrorResponse(response, 2005, "property 'program' is missing or empty");
return;
}
if (NodeDebugSession.isJavaScript(programPath)) {
if (this._sourceMaps) {
// source maps enabled indicates that a tool like Babel is used to transpile js to js
const generatedPath = this._sourceMaps.MapPathFromSource(programPath);
if (generatedPath) {
// there seems to be a generated file, so use that
programPath = generatedPath;
}
}
} else {
// node cannot execute the program directly
if (!this._sourceMaps) {
this.sendErrorResponse(response, 2002, "cannot launch program '{path}'; enabling source maps might help", { path: programPath });
return;
}
const generatedPath = this._sourceMaps.MapPathFromSource(programPath);
if (!generatedPath) { // cannot find generated file
this.sendErrorResponse(response, 2003, "cannot launch program '{path}'; setting the 'outDir' attribute might help", { path: programPath });
return;
}
programPath = generatedPath;
}
let program: string;
let workingDirectory = this.convertClientPathToDebugger(args.cwd);
if (workingDirectory) {
if (!FS.existsSync(workingDirectory)) {
this.sendErrorResponse(response, 2004, "working directory '{path}' does not exist", { path: 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);
}
if (runtimeArgs.indexOf('--nolazy') >= 0) {
this._lazy = false;
} else {
if (runtimeArgs.indexOf('--lazy') < 0) { // if user does not force 'lazy' mode
runtimeArgs.push('--nolazy'); // we force node to compile everything so that breakpoints work immediately
this._lazy = false;
}
}
// we always break on entry (but if user did not request this, we will not stop in the UI).
const launchArgs = [ runtimeExecutable, `--debug-brk=${port}` ].concat(runtimeArgs, [ program ], programArgs);
if (this._externalConsole) {
Terminal.launchInTerminal(workingDirectory, launchArgs, args.env).then((term: CP.ChildProcess) => {
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');
});
}
this._attach(response, port);
}).catch((error) => {
this.sendErrorResponse(response, 2011, "cannot launch target in terminal (reason: {_error})", { _error: error.message }, ErrorDestination.Telemetry | ErrorDestination.User );
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 cmd = CP.spawn(runtimeExecutable, launchArgs.slice(1), options);
cmd.on('error', (error) => {
this.sendErrorResponse(response, 2017, "cannot launch target (reason: {_error})", { _error: error.message }, ErrorDestination.Telemetry | ErrorDestination.User );
this._terminated(`failed to launch target (${error})`);
});
cmd.on('exit', () => {
this._terminated('target exited');
});
cmd.on('close', (code) => {
this._terminated('target closed');
});
this._captureOutput(cmd);
//cmd.stdin.end(); // close stdin because we do not support input for a target
this._attach(response, port);
}
}
private _sendLaunchCommandToConsole(args: string[]) {
// print the command to launch tghe target to the debug console
let cli = '';
for (var a of args) {
if (a.indexOf(' ') >= 0) {
cli += '\'' + a + '\'';
} else {
cli += a;
}
cli += ' ';
}
this.sendEvent(new OutputEvent(cli, 'console'));
}
private _captureOutput(process: CP.ChildProcess) {
var sanitize = (s: string) => s.toString().replace(/\r\n$/mg, '\n');
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'));
});
}
private _initializeSourceMaps(args: SourceMapsArguments) {
if (typeof args.sourceMaps === 'boolean' && args.sourceMaps) {
const generatedCodeDirectory = args.outDir;
this._sourceMaps = new SourceMaps(generatedCodeDirectory);
}
}
//---- attach request -----------------------------------------------------------------------------------------------------
protected attachRequest(response: DebugProtocol.AttachResponse, args: AttachRequestArguments): void {
this._initializeSourceMaps(args);
if (!args.port) {
this.sendErrorResponse(response, 2008, "property 'port' is missing");
return;
}
const port = args.port;
this._attachMode = true;
this._attach(response, port);
}
/*
* shared code used in launchRequest and attachRequest
*/
private _attach(response: DebugProtocol.Response, port: number, timeout: number = 5000): void {
let connected = false;
const socket = new Net.Socket();
socket.connect(port);
socket.on('connect', (err: any) => {
if (NodeDebugSession.TRACE_INITIALISATION) console.error('_init: connect event in _attach');
connected = true;
this._node.startDispatch(socket, socket);
if (this._adapterID === 'extensionHost' /* && this._node.embeddedHostVersion === 4 */) {
// for some reason we need a 'continue' request to make node send the stop-on-entry event in node versions 4.x
this._node.command('continue', null, (resp: NodeV8Response) => {
this._initialize(response);
});
} else {
this._initialize(response);
}
return;
});
const endTime = new Date().getTime() + timeout;
socket.on('error', (err: any) => {
if (connected) {
// since we are connected this error is fatal
this._terminateAndRetry('socket error', port);
} 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(() => {
if (NodeDebugSession.TRACE_INITIALISATION) console.error('_init: retry socket.connect');
socket.connect(port);
}, 200); // retry after 200 ms
} else {
this.sendErrorResponse(response, 2009, "cannot connect to runtime process (timeout after {_timeout}ms)", { _timeout: timeout });
}
} else {
this.sendErrorResponse(response, 2010, "cannot connect to runtime process (reason: {_error})", { _error: err });
}
}
});
socket.on('end', (err: any) => {
this._terminateAndRetry('socket end', port);
});
}
private _terminateAndRetry(reason: string, port: number): void {
if (this._adapterID === 'extensionHost' && !this._inShutdown) {
this._terminated(reason, port);
} else {
this._terminated(reason);
}
}
private _initialize(response: DebugProtocol.Response, retryCount: number = 0) : void {
this._node.command('evaluate', { expression: 'process.pid', global: true }, (resp: NodeV8Response) => {
let ok = resp.success;
if (resp.success) {
if (NodeDebugSession.TRACE_INITIALISATION) console.error('_init: retrieve node pid: OK');
this._nodeProcessId = parseInt(resp.body.value);
} else {
if (resp.message.indexOf('process is not defined') >= 0) {
if (NodeDebugSession.TRACE_INITIALISATION) console.error('_init: process not defined error; got no pid');
ok = true; // continue and try to get process.pid later
}
}
if (ok) {
this._pollForNodeTermination();
const runtimeSupportsExtension = this._node.embeddedHostVersion === 0; // node version 0.x.x (io.js has version >= 1)
if (this._tryToExtendNode && runtimeSupportsExtension) {
this._extendDebugger((success: boolean) => {
this.sendResponse(response);
this._startInitialize(!resp.running);
return;
});
} else {
this.sendResponse(response);
this._startInitialize(!resp.running);
return;
}
} else {
if (NodeDebugSession.TRACE_INITIALISATION) console.error('_init: retrieve node pid: failed');
if (retryCount < 10) {
setTimeout(() => {
// recurse
this._initialize(response, retryCount+1);
}, 50);
return;
} else {
this.sendNodeResponse(response, resp);
}
}
});
}
private _pollForNodeTermination() : void {
const id = setInterval(() => {
try {
if (this._nodeProcessId > 0) {
(<any>process).kill(this._nodeProcessId, 0); // node.d.ts doesn't like number argumnent
} else {
clearInterval(id);
}
} catch(e) {
clearInterval(id);
this._terminated('node process kill exception');
}
}, NodeDebugSession.NODE_TERMINATION_POLL_INTERVAL);
}
/*
* Inject code into node.js to fix timeout issues with large data structures.
*/
private _extendDebugger(done: (success: boolean) => void) : void {
try {
const contents = FS.readFileSync(Path.join(__dirname, NodeDebugSession.DEBUG_EXTENSION), 'utf8');
this._repeater(4, done, (callback: (again: boolean) => void) => {
this._node.command('evaluate', { expression: contents }, (resp: NodeV8Response) => {
if (resp.success) {
if (NodeDebugSession.TRACE_INITIALISATION) console.error('_init: node code inject: OK');
this._nodeExtensionsAvailable = true;
callback(false);
} else {
if (NodeDebugSession.TRACE_INITIALISATION) console.error('_init: node code inject: failed, try again...');
callback(true);
}
});
});
} catch(e) {
done(false);
}
}
/*
* start the initialization sequence:
* 1. wait for "break-on-entry" (with timeout)
* 2. send "inititialized" event in order to trigger setBreakpointEvents request from client
* 3. prepare for sending "break-on-entry" or "continue" later in _finishInitialize()
*/
private _startInitialize(stopped: boolean, n: number = 0): void {
if (NodeDebugSession.TRACE_INITIALISATION) console.error(`_init: _startInitialize(${stopped})`);
// wait at most 500ms for receiving the break on entry event
// (since in attach mode we cannot enforce that node is started with --debug-brk, we cannot assume that we receive this event)
if (!this._gotEntryEvent && n < 10) {
setTimeout(() => {
// recurse
this._startInitialize(stopped, n+1);
}, 50);
return;
}
if (this._gotEntryEvent) {
if (NodeDebugSession.TRACE_INITIALISATION) console.error(`_init: got break on entry event after ${n} retries`);
if (this._nodeProcessId <= 0) {
// if we haven't gotten a process pid so far, we try it again
this._node.command('evaluate', { expression: 'process.pid', global: true }, (resp: NodeV8Response) => {
if (resp.success) {
if (NodeDebugSession.TRACE_INITIALISATION) console.error('_init: 2nd retrieve node pid: OK');
this._nodeProcessId = parseInt(resp.body.value);
}
this._middleInitialize(stopped);
});
} else {
this._middleInitialize(stopped);
}
} else {
if (NodeDebugSession.TRACE_INITIALISATION) console.error(`_init: no entry event after ${n} retries; give up`);
this._gotEntryEvent = true; // we pretend to got one so that no ENTRY_REASON event will show up later...
this._node.command('frame', null, (resp: NodeV8Response) => {
if (resp.success) {
this.cacheRefs(resp);
let s = this.getValueFromCache(resp.body.script);
this.rememberEntryLocation(s.name, resp.body.line, resp.body.column);
}
this._middleInitialize(stopped);
});
}
}
private _middleInitialize(stopped: boolean): void {
// request UI to send breakpoints
if (NodeDebugSession.TRACE_INITIALISATION) console.error('_init: -> fire initialize event');
this.sendEvent(new InitializedEvent());
// in attach-mode we don't know whether the debuggee has been launched in 'stop on entry' mode
// so we use the stopped state of the VM
if (this._attachMode) {
if (NodeDebugSession.TRACE_INITIALISATION) console.error(`_init: in attach mode we guess stopOnEntry flag to be "${stopped}"`);
this._stopOnEntry = stopped;
}
if (this._stopOnEntry) {
// user has requested 'stop on entry' so send out a stop-on-entry
if (NodeDebugSession.TRACE_INITIALISATION) console.error('_init: -> fire stop-on-entry event');
this.sendEvent(new StoppedEvent(NodeDebugSession.ENTRY_REASON, NodeDebugSession.DUMMY_THREAD_ID));
}
else {
// since we are stopped but UI doesn't know about this, remember that we continue later in finishInitialize()
if (NodeDebugSession.TRACE_INITIALISATION) console.error('_init: remember to do a "Continue" later');
this._needContinue = true;
}
}
private _finishInitialize(): void {
if (this._needContinue) {
this._needContinue = false;
if (NodeDebugSession.TRACE_INITIALISATION) console.error('_init: do a "Continue"');
this._node.command('continue', null, (nodeResponse) => { });
}
if (this._needBreakpointEvent) {
this._needBreakpointEvent = false;
if (NodeDebugSession.TRACE_INITIALISATION) console.error('_init: fire a breakpoint event');
this.sendEvent(new StoppedEvent(NodeDebugSession.BREAKPOINT_REASON, NodeDebugSession.DUMMY_THREAD_ID));
}
}
//---- disconnect request -------------------------------------------------------------------------------------------------
protected disconnectRequest(response: DebugProtocol.DisconnectResponse, args: DebugProtocol.DisconnectArguments): void {
// special code for 'extensionHost' debugging
if (this._adapterID === 'extensionHost') {
// detect whether this disconnect request is part of a restart session
if (args && (<any>args).extensionHostData && (<any>args).extensionHostData.restart && this._nodeProcessId > 0) {
this._nodeProcessId = 0;
}
}
super.disconnectRequest(response, args);
}
/**
* we rely on the generic implementation from debugSession but we override 'v8Protocol.shutdown'
* to disconnect from node and kill node & subprocesses
*/
public shutdown(): void {
if (!this._inShutdown) {
this._inShutdown = true;
this._node.command('disconnect'); // we don't wait for reponse
this._node.stop(); // stop socket connection (otherwise node.js dies with ECONNRESET on Windows)
if (!this._attachMode) {
// kill the whole process tree either starting with the terminal or with the node process
let pid = this._terminalProcess ? this._terminalProcess.pid : this._nodeProcessId;
if (pid > 0) {
Terminal.killTree(pid).then(() => {
this._terminalProcess = null;
this._nodeProcessId = -1;
super.shutdown();
}).catch((error) => {
this._terminalProcess = null;
this._nodeProcessId = -1;
super.shutdown();
});
return;
}
}
super.shutdown();
}
}
//--- set breakpoints request ---------------------------------------------------------------------------------------------
protected setBreakPointsRequest(response: DebugProtocol.SetBreakpointsResponse, args: DebugProtocol.SetBreakpointsArguments): void {
let sourcemap = false;
const source = args.source;
const clientLines = args.lines;
// convert line numbers from client
const lines = new Array<number>(clientLines.length);
const columns = new Array<number>(clientLines.length);
for (let i = 0; i < clientLines.length; i++) {
lines[i] = this.convertClientLineToDebugger(clientLines[i]);
columns[i] = 0;
}
let scriptId = -1;
let path: string = null;
// we assume that only one of the source attributes is specified.
if (source.path) {
path = this.convertClientPathToDebugger(source.path);
// resolve the path to a real path (resolve symbolic links)
//path = PathUtilities.RealPath(path, _realPathMap);
let p: string = null;
if (this._sourceMaps) {
p = this._sourceMaps.MapPathFromSource(path);
}
if (p) {
sourcemap = true;
// source map line numbers
for (let i = 0; i < lines.length; i++) {
let pp = path;
const mr = this._sourceMaps.MapFromSource(pp, lines[i], columns[i]);
if (mr) {
pp = mr.path;
lines[i] = mr.line;
columns[i] = mr.column;
}
if (pp !== p) {
// console.error(`setBreakPointsRequest: sourceMap limitation ${pp}`);
}
}
path = p;
}
else if (!NodeDebugSession.isJavaScript(path)) {
// return these breakpoints as unverified
const bpts = new Array<Breakpoint>();
for (let l of clientLines) {
bpts.push(new Breakpoint(false, l));
}
response.body = {
breakpoints: bpts
};
this.sendResponse(response);
return;
}
this._clearAllBreakpoints(response, path, -1, lines, columns, sourcemap, clientLines);
return;
}
if (source.name) {
this.findModule(source.name, (id: number) => {
scriptId = id;
this._clearAllBreakpoints(response, null, scriptId, lines, columns, sourcemap, clientLines);
return;
});
}
if (source.sourceReference > 0) {
scriptId = source.sourceReference - 1000;
this._clearAllBreakpoints(response, null, scriptId, lines, columns, sourcemap, clientLines);
return;
}
this.sendErrorResponse(response, 2012, "no source specified", null, ErrorDestination.Telemetry);
}
/*
* Phase 2 of setBreakpointsRequest: clear all breakpoints of a given file
*/
private _clearAllBreakpoints(response: DebugProtocol.SetBreakpointsResponse, path: string, scriptId: number, lines: number[], columns: number[], sourcemap: boolean, clientLines: number[]): void {
// clear all existing breakpoints for the given path or script ID
this._node.command('listbreakpoints', null, (nodeResponse: NodeV8Response) => {
if (nodeResponse.success) {
const toClear = new Array<number>();
// try to match breakpoints
for (let breakpoint of nodeResponse.body.breakpoints) {
const type: string = breakpoint.type;
switch (type) {
case 'scriptId':
const script_id: number = breakpoint.script_id;
if (script_id === scriptId) {
toClear.push(breakpoint.number);
}
break;
case 'scriptName':
const script_name: string = breakpoint.script_name;
if (script_name === path) {
toClear.push(breakpoint.number);
}
break;
}
}
this._clearBreakpoints(toClear, 0, () => {
this._finishSetBreakpoints(response, path, scriptId, lines, columns, sourcemap, clientLines);
});
} else {
this.sendNodeResponse(response, nodeResponse);
}
});
}
/**
* Recursive function for deleting node breakpoints.
*/
private _clearBreakpoints(ids: Array<number>, ix: number, done: () => void) : void {
if (ids.length == 0) {
done();
return;
}
this._node.command('clearbreakpoint', { breakpoint: ids[ix] }, (nodeResponse: NodeV8Response) => {
if (!nodeResponse.success) {
// we ignore errors for now
// console.error('clearbreakpoint error: ' + rr.message);
}
if (ix+1 < ids.length) {
setImmediate(() => {
// recurse
this._clearBreakpoints(ids, ix+1, done);
});
} else {
done();
}
});
}
/*
* Finish the setBreakpointsRequest: set the breakpooints and send the verification response back to client
*/
private _finishSetBreakpoints(response: DebugProtocol.SetBreakpointsResponse, path: string, scriptId: number, lines: number[], columns: number[], sourcemap: boolean, clientLines: number[]): void {
const breakpoints = new Array<Breakpoint>();
this._setBreakpoints(breakpoints, 0, path, scriptId, lines, columns, sourcemap, clientLines, () => {
response.body = {
breakpoints: breakpoints
};
this.sendResponse(response);
});
}
/**
* Recursive function for setting node breakpoints.
*/
private _setBreakpoints(breakpoints: Array<Breakpoint>, ix: number, path: string, scriptId: number, lines: number[], columns: number[], sourcemap: boolean, clientLines: number[], done: () => void) : void {
if (lines.length == 0) { // nothing to do
done();
return;
}
this._robustSetBreakPoint(scriptId, path, lines[ix], columns[ix], (verified: boolean, actualLine, actualColumn) => {
// prepare sending breakpoint locations back to client
let sourceLine = clientLines[ix]; // we start with the original lines from the client
if (verified) {
if (sourcemap) {
if (!this._lazy) { // only if not in lazy mode we try to map actual Positions back
// map adjusted js breakpoints back to source language
if (path && this._sourceMaps) {
const p = path;
const mr = this._sourceMaps.MapToSource(p, actualLine, actualColumn);
if (mr) {
actualLine = mr.line;
actualColumn = mr.column;
}
}
sourceLine = this.convertDebuggerLineToClient(actualLine);
}
} else {
sourceLine = this.convertDebuggerLineToClient(actualLine);
}
}
breakpoints[ix] = new Breakpoint(verified, sourceLine);
// nasty corner case: since we ignore the break-on-entry event we have to make sure that we
// stop in the entry point line if the user has an explicit breakpoint there.
// For this we check here whether a breakpoint is at the same location as the "break-on-entry" location.
// If yes, then we plan for hitting the breakpoint instead of "continue" over it!
if (!this._stopOnEntry) { // only relevant if we do not stop on entry
const li = verified ? actualLine : lines[ix];
const co = columns[ix]; // verified ? actualColumn : columns[ix];
if (this._entryPath === path && this._entryLine === li && this._entryColumn === co) {
// if yes, we do not have to "continue" but we have to generate a stopped event instead
this._needContinue = false;
this._needBreakpointEvent = true;
if (NodeDebugSession.TRACE_INITIALISATION) console.error('_init: remember to fire a breakpoint event later');
}
}
if (ix+1 < lines.length) {
setImmediate(() => {
// recurse
this._setBreakpoints(breakpoints, ix+1, path, scriptId, lines, columns, sourcemap, clientLines, done);
});
} else {
done();
}
});
}
/*
* register a single breakpoint with node and retry if it fails due to drive letter casing (on Windows)
*/
private _robustSetBreakPoint(scriptId: number, path: string, l: number, c: number, done: (success: boolean, actualLine?: number, actualColumn?: number) => void): void {
this._setBreakpoint(scriptId, path, l, c, (verified: boolean, actualLine, actualColumn) => {
if (verified) {
done(true, actualLine, actualColumn);
return;