-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
Main.ts
755 lines (713 loc) · 37.1 KB
/
Main.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
// tslint:disable:quotemark ordered-imports promise-must-complete member-ordering no-any prefer-template cyclomatic-complexity no-empty no-multiline-string one-line no-invalid-template-strings no-suspicious-comment no-var-self no-duplicate-imports
"use strict";
// This line should always be right on top.
// tslint:disable:no-any no-floating-promises
if ((Reflect as any).metadata === undefined) {
// tslint:disable-next-line:no-require-imports no-var-requires
require('reflect-metadata');
}
import * as fs from "fs";
import * as path from "path";
import { Handles, InitializedEvent, OutputEvent, Scope, Source, StackFrame, StoppedEvent, TerminatedEvent, Thread, Variable, LoggingDebugSession, logger, BreakpointEvent, Breakpoint, ThreadEvent } from "vscode-debugadapter";
import { DebugProtocol } from "vscode-debugprotocol";
import { DEBUGGER } from '../../client/telemetry/constants';
import { DebuggerTelemetry } from '../../client/telemetry/types';
import { isNotInstalledError } from '../common/helpers';
import { enum_EXCEPTION_STATE, IPythonBreakpoint, IPythonException, PythonBreakpointConditionKind, PythonBreakpointPassCountKind, PythonEvaluationResultReprKind, LaunchRequestArgumentsV1, AttachRequestArgumentsV1 } from "./Common/Contracts";
import { IDebugServer, IPythonEvaluationResult, IPythonModule, IPythonStackFrame, IPythonThread } from "./Common/Contracts";
import { DebugOptions, LaunchRequestArguments, PythonEvaluationResultFlags, TelemetryEvent } from "./Common/Contracts";
import { getPythonExecutable, validatePath } from './Common/Utils';
import { DebugClient } from "./DebugClients/DebugClient";
import { CreateAttachDebugClient, CreateLaunchDebugClient } from "./DebugClients/DebugFactory";
import { BaseDebugServer } from "./DebugServers/BaseDebugServer";
import { PythonProcess } from "./PythonProcess";
import { sendPerformanceTelemetry, capturePerformanceTelemetry, PerformanceTelemetryCondition } from "./Common/telemetry";
import { LogLevel } from "vscode-debugadapter/lib/logger";
const CHILD_ENUMEARATION_TIMEOUT = 5000;
interface IDebugVariable {
variables: IPythonEvaluationResult[];
evaluateChildren?: Boolean;
}
export class PythonDebugger extends LoggingDebugSession {
private _variableHandles: Handles<IDebugVariable>;
private _pythonStackFrames: Handles<IPythonStackFrame>;
private breakPointCounter: number = 0;
private registeredBreakpoints: Map<number, IPythonBreakpoint>;
private registeredBreakpointsByFileName: Map<string, IPythonBreakpoint[]>;
private debuggerLoaded: Promise<any>;
private debuggerLoadedPromiseResolve!: () => void;
private debugClient?: DebugClient<{}>;
private configurationDone!: Promise<any>;
private configurationDonePromiseResolve?: () => void;
private lastException?: IPythonException;
private _supportsRunInTerminalRequest: boolean = false;
private terminateEventSent: boolean = false;
public constructor(debuggerLinesStartAt1: boolean, isServer: boolean) {
super(path.join(__dirname, '..', '..', '..', 'debug.log'), debuggerLinesStartAt1, isServer === true);
this._variableHandles = new Handles<IDebugVariable>();
this._pythonStackFrames = new Handles<IPythonStackFrame>();
this.registeredBreakpoints = new Map<number, IPythonBreakpoint>();
this.registeredBreakpointsByFileName = new Map<string, IPythonBreakpoint[]>();
this.debuggerLoaded = new Promise(resolve => {
this.debuggerLoadedPromiseResolve = resolve;
});
}
// tslint:disable-next-line:no-unnecessary-override
@sendPerformanceTelemetry(PerformanceTelemetryCondition.stoppedEvent)
public sendEvent(event: DebugProtocol.Event): void {
super.sendEvent(event);
}
protected initializeRequest(response: DebugProtocol.InitializeResponse, args: DebugProtocol.InitializeRequestArguments): void {
response.body!.supportsEvaluateForHovers = true;
response.body!.supportsConditionalBreakpoints = true;
response.body!.supportsConfigurationDoneRequest = true;
response.body!.supportsEvaluateForHovers = false;
response.body!.supportsFunctionBreakpoints = false;
response.body!.supportsSetVariable = true;
response.body!.exceptionBreakpointFilters = [
{
label: "All Exceptions",
filter: "all"
},
{
label: "Uncaught Exceptions",
filter: "uncaught"
}
];
if (typeof args.supportsRunInTerminalRequest === 'boolean') {
this._supportsRunInTerminalRequest = args.supportsRunInTerminalRequest;
}
this.sendResponse(response);
// now we are ready to accept breakpoints -> fire the initialized event to give UI a chance to set breakpoints
this.sendEvent(new InitializedEvent());
}
private pythonProcess?: PythonProcess;
private debugServer!: BaseDebugServer;
private startDebugServer(): Promise<IDebugServer> {
let programDirectory = '';
if ((this.launchArgs && this.launchArgs.program) || (this.attachArgs && this.attachArgs.localRoot)) {
programDirectory = (this.launchArgs && this.launchArgs.program) ? path.dirname(this.launchArgs.program) : this.attachArgs.localRoot;
}
if (this.launchArgs && typeof this.launchArgs.cwd === 'string' && this.launchArgs.cwd.length > 0 && this.launchArgs.cwd !== 'null') {
programDirectory = this.launchArgs.cwd;
}
this.pythonProcess = new PythonProcess(0, "", programDirectory);
this.debugServer = this.debugClient!.CreateDebugServer(this.pythonProcess!);
this.InitializeEventHandlers();
return this.debugServer.Start();
}
private stopDebugServer() {
if (this.debugClient) {
this.debugClient!.Stop();
this.debugClient = undefined;
}
if (this.pythonProcess) {
this.pythonProcess!.Kill();
this.pythonProcess = undefined;
}
this.terminateEventSent = true;
this.sendEvent(new TerminatedEvent());
}
private InitializeEventHandlers() {
const pythonProcess = this.pythonProcess!;
pythonProcess.on("last", arg => this.onLastCommand());
pythonProcess.on("threadExited", arg => this.onPythonThreadExited(arg));
pythonProcess.on("moduleLoaded", arg => this.onPythonModuleLoaded(arg));
pythonProcess.on("threadCreated", arg => this.onPythonThreadCreated(arg));
pythonProcess.on("processLoaded", arg => this.onPythonProcessLoaded(arg));
pythonProcess.on("output", (pyThread, output) => this.onDebuggerOutput(pyThread, output, 'stdout'));
pythonProcess.on("exceptionRaised", (pyThread, ex) => this.onPythonException(pyThread, ex));
pythonProcess.on("breakpointHit", (pyThread, breakpointId) => this.onBreakpointHit(pyThread, breakpointId));
pythonProcess.on("breakpointChanged", (breakpointId: number, verified: boolean) => this.onBreakpointChanged(breakpointId, verified));
pythonProcess.on("stepCompleted", (pyThread) => this.onStepCompleted(pyThread));
pythonProcess.on("detach", () => this.onDetachDebugger());
pythonProcess.on("error", ex => this.onDebuggerOutput(undefined, ex, 'stderr'));
pythonProcess.on("asyncBreakCompleted", arg => this.onPythonProcessPaused(arg));
this.debugServer.on("detach", () => this.onDetachDebugger());
}
private onLastCommand() {
this.terminateEventSent = true;
// When running in terminals, and if there are any errors, the PTVSD library
// first sends the LAST command (meaning everything has ended) and then sends the stderr and stdout messages.
// I.e. to us, it looks as though everything is done and completed, when it isn't.
// A simple solution is to tell vscode that it has ended 500ms later (giving us time to receive any messages from stderr/stdout from ptvsd).
setTimeout(() => this.sendEvent(new TerminatedEvent()), 500);
}
private onDetachDebugger() {
this.stopDebugServer();
}
private onPythonThreadCreated(pyThread: IPythonThread) {
this.sendEvent(new ThreadEvent("started", pyThread.Int32Id));
}
private onStepCompleted(pyThread: IPythonThread) {
this.sendEvent(new StoppedEvent("step", pyThread.Int32Id));
}
private onPythonException(pyThread: IPythonThread, ex: IPythonException) {
this.lastException = ex;
this.sendEvent(new StoppedEvent("exception", pyThread.Int32Id, `${ex.TypeName}, ${ex.Description}`));
this.sendEvent(new OutputEvent(`${ex.TypeName}, ${ex.Description}\n`, "stderr"));
}
private onPythonThreadExited(pyThread: IPythonThread) {
this.sendEvent(new ThreadEvent("exited", pyThread.Int32Id));
}
private onPythonProcessPaused(pyThread: IPythonThread) {
this.sendEvent(new StoppedEvent("pause", pyThread.Int32Id));
}
private onPythonModuleLoaded(module: IPythonModule) {
}
@sendPerformanceTelemetry(PerformanceTelemetryCondition.always)
private onPythonProcessLoaded(pyThread?: IPythonThread) {
if (this.entryResponse) {
this.sendResponse(this.entryResponse);
}
this.debuggerLoadedPromiseResolve();
if (this.launchArgs && !this.launchArgs.console) {
this.launchArgs.console = 'none';
}
// If launching the integrated terminal is not supported, then defer to external terminal
// that will be displayed by our own code.
if (!this._supportsRunInTerminalRequest && this.launchArgs && this.launchArgs.console === 'integratedTerminal') {
this.launchArgs.console = 'externalTerminal';
}
if (!this.launchArgs || this.launchArgs.noDebug !== true) {
// tslint:disable-next-line:no-non-null-assertion
const thread = pyThread!;
if (this.launchArgs && this.launchArgs.stopOnEntry === true) {
this.sendEvent(new StoppedEvent("entry", thread.Int32Id));
} else if (this.launchArgs && this.launchArgs.stopOnEntry === false) {
this.configurationDone.then(() => {
this.pythonProcess!.SendResumeThread(thread.Id);
});
} else {
this.pythonProcess!.SendResumeThread(thread.Id);
}
}
}
private onDebuggerOutput(pyThread: IPythonThread | undefined, output: string, outputChannel: 'stdout' | 'stderr') {
if (this.entryResponse) {
// Sometimes we can get output from PTVSD even before things load.
// E.g. if the program didn't even run (e.g. simple one liner with invalid syntax).
// But we need to tell vscode that the debugging has started, so we can send error messages.
this.sendResponse(this.entryResponse);
this.debuggerLoadedPromiseResolve();
this.entryResponse = undefined;
}
this.sendEvent(new OutputEvent(output, outputChannel));
}
private entryResponse?: DebugProtocol.LaunchResponse;
private launchArgs!: LaunchRequestArgumentsV1;
private attachArgs!: AttachRequestArgumentsV1;
private canStartDebugger(): Promise<boolean> {
return Promise.resolve(true);
}
@capturePerformanceTelemetry('launch')
protected launchRequest(response: DebugProtocol.LaunchResponse, args: LaunchRequestArguments): void {
if (args.logToFile === true) {
logger.setup(LogLevel.Verbose, true);
}
// Some versions may still exist with incorrect launch.json values
const setting = '${config.python.pythonPath}';
if (args.pythonPath === setting) {
return this.sendErrorResponse(response, 2001, `Invalid launch.json (re-create it or replace 'config.python.pythonPath' with 'config:python.pythonPath')`);
}
// Add support for specifying just the directory where the python executable will be located
// E.g. virtual directory name
try {
args.pythonPath = getPythonExecutable(args.pythonPath);
}
catch (ex) {
}
// Confirm the file exists
if (typeof args.module !== 'string' || args.module.length === 0) {
if (!args.program || !fs.existsSync(args.program)) {
return this.sendErrorResponse(response, 2001, `File does not exist. "${args.program}"`);
}
}
else {
// When using modules ensure the cwd has been provided
if (typeof args.cwd !== 'string' || args.cwd.length === 0 || (this.launchArgs && this.launchArgs.cwd === 'null')) {
return this.sendErrorResponse(response, 2001, `'cwd' in 'launch.json' needs to point to the working directory`);
}
}
let programDirectory = '';
if (args && args.program) {
programDirectory = path.dirname(args.program);
}
if (args && typeof args.cwd === 'string' && args.cwd.length > 0 && args.cwd !== 'null') {
programDirectory = args.cwd;
}
if (programDirectory.length > 0 && fs.existsSync(path.join(programDirectory, 'pyenv.cfg'))) {
this.sendEvent(new OutputEvent(`Warning 'pyenv.cfg' can interfere with the debugger. Please rename or delete this file (temporary solution)`));
}
const telemetryProps: DebuggerTelemetry = {
trigger: 'launch',
console: args.console,
debugOptions: (Array.isArray(args.debugOptions) ? args.debugOptions : []).join(","),
pyspark: typeof args.pythonPath === 'string' && args.pythonPath.indexOf('spark-submit') > 0,
hasEnvVars: args.env && typeof args.env === "object" && Object.keys(args.env).length > 0
};
this.sendEvent(new TelemetryEvent(DEBUGGER, telemetryProps));
this.launchArgs = args;
this.debugClient = CreateLaunchDebugClient(args, this, this._supportsRunInTerminalRequest);
this.configurationDone = new Promise(resolve => {
this.configurationDonePromiseResolve = resolve;
});
this.entryResponse = response;
// tslint:disable-next-line:no-this-assignment
const that = this;
this.startDebugServer().then(dbgServer => {
return that.debugClient!.LaunchApplicationToDebug(dbgServer);
}).catch(error => {
this.sendEvent(new OutputEvent(`${error}${'\n'}`, "stderr"));
response.success = false;
let errorMsg = typeof error === "string" ? error : ((error.message && error.message.length > 0) ? error.message : error);
if (isNotInstalledError(error)) {
errorMsg = `Failed to launch the Python Process, please validate the path '${this.launchArgs.pythonPath}'`;
}
this.sendErrorResponse(response, 200, errorMsg);
});
}
protected attachRequest(response: DebugProtocol.AttachResponse, args: AttachRequestArgumentsV1) {
if (args.logToFile === true) {
logger.setup(LogLevel.Verbose, true);
}
this.sendEvent(new TelemetryEvent(DEBUGGER, { trigger: 'attach' }));
this.attachArgs = args;
this.debugClient = CreateAttachDebugClient(args, this);
this.entryResponse = response;
// tslint:disable-next-line:no-this-assignment
const that = this;
this.canStartDebugger().then(() => {
return this.startDebugServer();
}).then(dbgServer => {
return that.debugClient!.LaunchApplicationToDebug(dbgServer);
}).catch(error => {
this.sendEvent(new OutputEvent(`${error}${'\n'}`, "stderr"));
this.sendErrorResponse(that.entryResponse!, 2000, error);
});
}
protected configurationDoneRequest(response: DebugProtocol.ConfigurationDoneResponse, args: DebugProtocol.ConfigurationDoneArguments): void {
// Tell debugger we have loaded the breakpoints
if (this.configurationDonePromiseResolve) {
this.configurationDonePromiseResolve!();
this.configurationDonePromiseResolve = undefined;
}
this.sendResponse(response);
}
private onBreakpointHit(pyThread: IPythonThread, breakpointId: number) {
// Break only if the breakpoint exists and it is enabled
if (this.registeredBreakpoints.has(breakpointId) && this.registeredBreakpoints.get(breakpointId)!.Enabled === true) {
this.sendEvent(new StoppedEvent("breakpoint", pyThread.Int32Id));
}
else {
this.pythonProcess!.SendResumeThread(pyThread.Id);
}
}
private onBreakpointChanged(breakpointId: number, verified: boolean) {
if (!this.registeredBreakpoints.has(breakpointId)) {
return;
}
const pythonBkpoint = this.registeredBreakpoints.get(breakpointId)!;
const breakpoint = new Breakpoint(verified, pythonBkpoint.LineNo, undefined, new Source(path.basename(pythonBkpoint.Filename), pythonBkpoint.Filename));
// VSC needs `id` to uniquely identify each breakpoint (part of the protocol spec).
(breakpoint as any).id = pythonBkpoint.Id;
this.sendEvent(new BreakpointEvent('changed', breakpoint));
}
private buildBreakpointDetails(filePath: string, line: number, condition: string): IPythonBreakpoint {
let isDjangoFile = false;
if (this.launchArgs &&
Array.isArray(this.launchArgs.debugOptions) &&
this.launchArgs.debugOptions.indexOf(DebugOptions.Django) >= 0) {
isDjangoFile = filePath.toUpperCase().endsWith(".HTML");
}
condition = typeof condition === "string" ? condition : "";
return {
Condition: condition,
ConditionKind: condition.length === 0 ? PythonBreakpointConditionKind.Always : PythonBreakpointConditionKind.WhenTrue,
Filename: filePath,
Id: this.breakPointCounter += 1,
LineNo: line,
PassCount: 0,
PassCountKind: PythonBreakpointPassCountKind.Always,
IsDjangoBreakpoint: isDjangoFile,
Enabled: true
};
}
protected setBreakPointsRequest(response: DebugProtocol.SetBreakpointsResponse, args: DebugProtocol.SetBreakpointsArguments): void {
this.debuggerLoaded.then(() => {
if (this.terminateEventSent) {
response.body = {
breakpoints: []
};
return this.sendResponse(response);
}
if (!this.registeredBreakpointsByFileName.has(args.source.path!)) {
this.registeredBreakpointsByFileName.set(args.source.path!, []);
}
// VSC needs `id` to uniquely identify each breakpoint (part of the protocol spec).
const breakpoints: { verified: boolean; line: number; id: number }[] = [];
const linesToAdd = args.breakpoints!.map(b => b.line);
const registeredBks = this.registeredBreakpointsByFileName.get(args.source.path!)!;
const linesToRemove = registeredBks.map(b => b.LineNo).filter(oldLine => linesToAdd.indexOf(oldLine) === -1);
// Always add new breakpoints, don't re-enable previous breakpoints,
// Cuz sometimes some breakpoints get added too early (e.g. in django) and don't get registeredBks
// and the response comes back indicating it wasn't set properly.
// However, at a later point in time, the program breaks at that point!!!
const linesToAddPromises = args.breakpoints!.map(bk => {
return new Promise(resolve => {
let breakpoint: IPythonBreakpoint;
const existingBreakpointsForThisLine = registeredBks.filter(registeredBk => registeredBk.LineNo === bk.line);
if (existingBreakpointsForThisLine.length > 0) {
// We have an existing breakpoint for this line
// just enable that
breakpoint = existingBreakpointsForThisLine[0];
breakpoint.Enabled = true;
}
else {
breakpoint = this.buildBreakpointDetails(this.convertClientPathToDebugger(args.source.path!), bk.line, bk.condition!);
}
this.pythonProcess!.BindBreakpoint(breakpoint).then(() => {
this.registeredBreakpoints.set(breakpoint.Id, breakpoint);
breakpoints.push({ verified: true, line: bk.line, id: breakpoint.Id });
registeredBks.push(breakpoint);
resolve();
}).catch(reason => {
this.registeredBreakpoints.set(breakpoint.Id, breakpoint);
breakpoints.push({ verified: false, line: bk.line, id: breakpoint.Id });
registeredBks.push(breakpoint);
resolve();
});
});
});
const linesToRemovePromises = linesToRemove.map(line => {
return new Promise(resolve => {
const bookmarks = this.registeredBreakpointsByFileName.get(args.source.path!)!;
const bk = bookmarks.filter(b => b.LineNo === line)[0];
// Ok, we won't get a response back, so update the breakpoints list indicating this has been disabled
bk.Enabled = false;
this.pythonProcess!.DisableBreakPoint(bk);
resolve();
});
});
const promises = linesToAddPromises.concat(linesToRemovePromises);
Promise.all(promises).then(() => {
response.body = {
breakpoints: breakpoints
};
this.sendResponse(response);
// Tell debugger we have loaded the breakpoints
if (this.configurationDonePromiseResolve) {
this.configurationDonePromiseResolve!();
this.configurationDonePromiseResolve = undefined;
}
}).catch(error => this.sendErrorResponse(response, 2000, error));
});
}
protected threadsRequest(response: DebugProtocol.ThreadsResponse): void {
const threads: Thread[] = [];
if (this.pythonProcess) {
this.pythonProcess!.Threads.forEach(t => {
threads.push(new Thread(t.Int32Id, t.Name));
});
}
response.body = {
threads: threads
};
this.sendResponse(response);
}
protected convertDebuggerPathToClient(remotePath: string): string {
if (this.attachArgs && this.attachArgs.localRoot && this.attachArgs.remoteRoot) {
let path2 = path.win32;
if (this.attachArgs.remoteRoot.indexOf('/') !== -1) {
path2 = path.posix;
}
const pathRelativeToSourceRoot = path2.relative(this.attachArgs.remoteRoot, remotePath);
return path.resolve(this.attachArgs.localRoot, pathRelativeToSourceRoot);
} else {
return remotePath;
}
}
protected convertClientPathToDebugger(clientPath: string): string {
if (this.attachArgs && this.attachArgs.localRoot && this.attachArgs.remoteRoot) {
// get the part of the path that is relative to the client root
const pathRelativeToClientRoot = path.relative(this.attachArgs.localRoot, clientPath);
// resolve from the remote source root
let path2 = path.win32;
if (this.attachArgs.remoteRoot.indexOf('/') !== -1) {
path2 = path.posix;
}
return path2.resolve(this.attachArgs.remoteRoot, pathRelativeToClientRoot);
} else {
return clientPath;
}
}
protected stackTraceRequest(response: DebugProtocol.StackTraceResponse, args: DebugProtocol.StackTraceArguments): void {
this.debuggerLoaded.then(() => {
if (this.terminateEventSent || !this.pythonProcess || Array.from(this.pythonProcess!.Threads.values()).findIndex(t => t.Int32Id === args.threadId) === -1) {
response.body = {
stackFrames: []
};
return this.sendResponse(response);
}
const pyThread = Array.from(this.pythonProcess!.Threads.values()).find(t => t.Int32Id === args.threadId)!;
let maxFrames = typeof args.levels === "number" && args.levels > 0 ? args.levels : pyThread.Frames.length - 1;
maxFrames = maxFrames < pyThread.Frames.length ? maxFrames : pyThread.Frames.length;
const frames = pyThread.Frames.map(frame => {
return validatePath(this.convertDebuggerPathToClient(frame.FileName)).then(fileName => {
const frameId = this._pythonStackFrames.create(frame);
if (fileName.length === 0) {
return new StackFrame(frameId, frame.FunctionName);
}
else {
return new StackFrame(frameId, frame.FunctionName,
new Source(path.basename(frame.FileName), fileName),
this.convertDebuggerLineToClient(frame.LineNo - 1),
1);
}
});
});
Promise.all<StackFrame>(frames).then(resolvedFrames => {
response.body = {
stackFrames: resolvedFrames
};
this.sendResponse(response);
});
});
}
@capturePerformanceTelemetry('stepIn')
protected stepInRequest(response: DebugProtocol.StepInResponse): void {
this.sendResponse(response);
this.pythonProcess!.SendStepInto(this.pythonProcess!.LastExecutedThread.Id);
}
@capturePerformanceTelemetry('stepOut')
protected stepOutRequest(response: DebugProtocol.StepInResponse): void {
this.sendResponse(response);
this.pythonProcess!.SendStepOut(this.pythonProcess!.LastExecutedThread.Id);
}
@capturePerformanceTelemetry('continue')
protected continueRequest(response: DebugProtocol.ContinueResponse, args: DebugProtocol.ContinueArguments): void {
this.pythonProcess!.SendContinue().then(() => {
this.sendResponse(response);
}).catch(error => this.sendErrorResponse(response, 2000, error));
}
@capturePerformanceTelemetry('next')
protected nextRequest(response: DebugProtocol.NextResponse, args: DebugProtocol.NextArguments): void {
this.sendResponse(response);
this.pythonProcess!.SendStepOver(this.pythonProcess!.LastExecutedThread.Id);
}
protected evaluateRequest(response: DebugProtocol.EvaluateResponse, args: DebugProtocol.EvaluateArguments): void {
this.debuggerLoaded.then(() => {
const frame = this._pythonStackFrames.get(args.frameId!)!;
if (this.terminateEventSent || !frame || !this.pythonProcess) {
response.body = {
result: '',
variablesReference: 0
};
return this.sendResponse(response);
}
this.pythonProcess!.ExecuteText(args.expression, PythonEvaluationResultReprKind.Normal, frame).then(result => {
let variablesReference = 0;
// If this value can be expanded, then create a vars ref for user to expand it
if (result.IsExpandable) {
const parentVariable: IDebugVariable = {
variables: [result],
evaluateChildren: true
};
variablesReference = this._variableHandles.create(parentVariable);
}
response.body = {
result: result.StringRepr,
variablesReference: variablesReference
};
this.sendResponse(response);
}).catch(error => this.sendErrorResponse(response, 2000, error));
});
}
protected scopesRequest(response: DebugProtocol.ScopesResponse, args: DebugProtocol.ScopesArguments): void {
this.debuggerLoaded.then(() => {
const frame = this._pythonStackFrames.get(args.frameId)!;
if (this.terminateEventSent || !frame || !this.pythonProcess) {
response.body = {
scopes: []
};
return this.sendResponse(response);
}
const scopes: Scope[] = [];
if (this.lastException && this.lastException!.Description.length > 0) {
const values: IDebugVariable = {
variables: [{
Frame: frame, Expression: 'Type',
Flags: PythonEvaluationResultFlags.Raw,
StringRepr: this.lastException!.TypeName,
TypeName: 'string', IsExpandable: false, HexRepr: '',
ChildName: '', ExceptionText: '', Length: 0, Process: undefined
},
{
Frame: frame, Expression: 'Description',
Flags: PythonEvaluationResultFlags.Raw,
StringRepr: this.lastException!.Description,
TypeName: 'string', IsExpandable: false, HexRepr: '',
ChildName: '', ExceptionText: '', Length: 0, Process: undefined
}],
evaluateChildren: false
};
scopes.push(new Scope("Exception", this._variableHandles.create(values), false));
this.lastException = undefined;
}
if (Array.isArray(frame.Locals) && frame.Locals.length > 0) {
const values: IDebugVariable = { variables: frame.Locals };
scopes.push(new Scope("Local", this._variableHandles.create(values), false));
}
if (Array.isArray(frame.Parameters) && frame.Parameters.length > 0) {
const values: IDebugVariable = { variables: frame.Parameters };
scopes.push(new Scope("Arguments", this._variableHandles.create(values), false));
}
response.body = { scopes };
this.sendResponse(response);
});
}
protected variablesRequest(response: DebugProtocol.VariablesResponse, args: DebugProtocol.VariablesArguments): void {
const varRef = this._variableHandles.get(args.variablesReference)!;
if (varRef.evaluateChildren !== true) {
const variables: Variable[] = [];
varRef.variables.forEach(variable => {
let variablesReference = 0;
// If this value can be expanded, then create a vars ref for user to expand it
if (variable.IsExpandable) {
const parentVariable: IDebugVariable = {
variables: [variable],
evaluateChildren: true
};
variablesReference = this._variableHandles.create(parentVariable);
}
variables.push({
name: variable.Expression,
value: variable.StringRepr,
variablesReference: variablesReference
});
});
response.body = {
variables: variables
};
return this.sendResponse(response);
}
else {
// Ok, we need to evaluate the children of the current variable.
const variables: Variable[] = [];
const promises = varRef.variables.map(variable => {
return variable.Process!.EnumChildren(variable.Expression, variable.Frame, CHILD_ENUMEARATION_TIMEOUT).then(children => {
children.forEach(child => {
let variablesReference = 0;
// If this value can be expanded, then create a vars ref for user to expand it
if (child.IsExpandable) {
const childVariable: IDebugVariable = {
variables: [child],
evaluateChildren: true
};
variablesReference = this._variableHandles.create(childVariable);
}
variables.push({
name: child.ChildName,
value: child.StringRepr,
variablesReference: variablesReference
});
});
});
});
Promise.all(promises).then(() => {
response.body = {
variables: variables
};
return this.sendResponse(response);
}).catch(error => this.sendErrorResponse(response, 2001, error));
}
}
protected pauseRequest(response: DebugProtocol.PauseResponse): void {
this.pythonProcess!.Break();
this.sendResponse(response);
}
protected setExceptionBreakPointsRequest(response: DebugProtocol.SetExceptionBreakpointsResponse, args: DebugProtocol.SetExceptionBreakpointsArguments): void {
this.debuggerLoaded.then(() => {
if (this.terminateEventSent) {
return this.sendResponse(response);
}
let mode = enum_EXCEPTION_STATE.BREAK_MODE_NEVER;
if (args.filters.indexOf("uncaught") >= 0) {
mode = enum_EXCEPTION_STATE.BREAK_MODE_UNHANDLED;
}
if (args.filters.indexOf("all") >= 0) {
mode = enum_EXCEPTION_STATE.BREAK_MODE_ALWAYS;
}
const exToIgnore = new Map<string, enum_EXCEPTION_STATE>();
const exceptionHandling = this.launchArgs ? this.launchArgs.exceptionHandling : null;
if (exceptionHandling) {
if (Array.isArray(exceptionHandling.ignore)) {
exceptionHandling.ignore.forEach(exType => {
exToIgnore.set(exType, enum_EXCEPTION_STATE.BREAK_MODE_NEVER);
});
}
if (Array.isArray(exceptionHandling.always)) {
exceptionHandling.always.forEach(exType => {
exToIgnore.set(exType, enum_EXCEPTION_STATE.BREAK_MODE_ALWAYS);
});
}
if (Array.isArray(exceptionHandling.unhandled)) {
exceptionHandling.unhandled.forEach(exType => {
exToIgnore.set(exType, enum_EXCEPTION_STATE.BREAK_MODE_UNHANDLED);
});
}
}
// Ignore StopIteration and GeneratorExit as they are used for
// control flow and not error conditions.
if (!exToIgnore.has('StopIteration')) {
exToIgnore.set('StopIteration', enum_EXCEPTION_STATE.BREAK_MODE_NEVER);
}
if (!exToIgnore.has('GeneratorExit')) {
exToIgnore.set('GeneratorExit', enum_EXCEPTION_STATE.BREAK_MODE_NEVER);
}
if (this.pythonProcess) {
this.pythonProcess!.SendExceptionInfo(mode, exToIgnore);
}
this.sendResponse(response);
});
}
protected disconnectRequest(response: DebugProtocol.DisconnectResponse, args: DebugProtocol.DisconnectArguments) {
this.stopDebugServer();
this.sendResponse(response);
}
protected setVariableRequest(response: DebugProtocol.SetVariableResponse, args: DebugProtocol.SetVariableArguments) {
const variable = this._variableHandles.get(args.variablesReference)!.variables.find(v => v.ChildName === args.name);
if (!variable) {
return this.sendErrorResponse(response, 2000, 'Variable reference not found');
}
this.pythonProcess!.ExecuteText(`${args.name} = ${args.value}`, PythonEvaluationResultReprKind.Normal, variable.Frame).then(() => {
return this.pythonProcess!.ExecuteText(args.name, PythonEvaluationResultReprKind.Normal, variable.Frame).then(result => {
// If this value can be expanded, then create a vars ref for user to expand it
if (result.IsExpandable) {
const parentVariable: IDebugVariable = {
variables: [result],
evaluateChildren: true
};
this._variableHandles.create(parentVariable);
}
response.body = {
value: result.StringRepr
};
this.sendResponse(response);
});
}).catch(error => this.sendErrorResponse(response, 2000, error));
}
}
process.stdin.on('error', () => { });
process.stdout.on('error', () => { });
process.stderr.on('error', () => { });
process.on('uncaughtException', (err: Error) => {
logger.error(`Uncaught Exception: ${err && err.message ? err.message : ''}`);
logger.error(err && err.name ? err.name : '');
logger.error(err && err.stack ? err.stack : '');
// Catch all, incase we have string exceptions being raised.
logger.error(err ? err.toString() : '');
// Wait for 1 second before we die, we need to ensure errors are written to the log file.
setTimeout(() => process.exit(-1), 1000);
});
LoggingDebugSession.run(PythonDebugger);