-
Notifications
You must be signed in to change notification settings - Fork 511
/
Copy pathDebugSession.ts
601 lines (512 loc) · 23.7 KB
/
DebugSession.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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
import vscode = require("vscode");
import { CancellationToken, DebugConfiguration, DebugConfigurationProvider,
ExtensionContext, WorkspaceFolder } from "vscode";
import { NotificationType, RequestType } from "vscode-languageclient";
import { LanguageClient } from "vscode-languageclient/node";
import { getPlatformDetails, OperatingSystem } from "../platform";
import { PowerShellProcess} from "../process";
import { IEditorServicesSessionDetails, SessionManager, SessionStatus } from "../session";
import Settings = require("../settings");
import { Logger } from "../logging";
import { LanguageClientConsumer } from "../languageClientConsumer";
export const StartDebuggerNotificationType =
new NotificationType<void>("powerShell/startDebugger");
export const StopDebuggerNotificationType =
new NotificationType<void>("powerShell/stopDebugger");
export class DebugSessionFeature extends LanguageClientConsumer
implements DebugConfigurationProvider, vscode.DebugAdapterDescriptorFactory {
private sessionCount: number = 1;
private tempDebugProcess: PowerShellProcess;
private tempSessionDetails: IEditorServicesSessionDetails;
constructor(context: ExtensionContext, private sessionManager: SessionManager, private logger: Logger) {
super();
// Register a debug configuration provider
context.subscriptions.push(vscode.debug.registerDebugConfigurationProvider("PowerShell", this));
context.subscriptions.push(vscode.debug.registerDebugAdapterDescriptorFactory("PowerShell", this))
}
createDebugAdapterDescriptor(
session: vscode.DebugSession,
_executable: vscode.DebugAdapterExecutable | undefined): vscode.ProviderResult<vscode.DebugAdapterDescriptor> {
const sessionDetails = session.configuration.createTemporaryIntegratedConsole
? this.tempSessionDetails
: this.sessionManager.getSessionDetails();
this.logger.writeVerbose(`Connecting to pipe: ${sessionDetails.debugServicePipeName}`);
this.logger.writeVerbose(`Debug configuration: ${JSON.stringify(session.configuration)}`);
return new vscode.DebugAdapterNamedPipeServer(sessionDetails.debugServicePipeName);
}
// tslint:disable-next-line:no-empty
public dispose() {
}
public setLanguageClient(languageClient: LanguageClient) {
languageClient.onNotification(
StartDebuggerNotificationType,
// TODO: Use a named debug configuration.
() => vscode.debug.startDebugging(undefined, {
request: "launch",
type: "PowerShell",
name: "PowerShell: Interactive Session"
}));
languageClient.onNotification(
StopDebuggerNotificationType,
() => vscode.debug.stopDebugging(undefined));
}
public async provideDebugConfigurations(
folder: WorkspaceFolder | undefined,
token?: CancellationToken): Promise<DebugConfiguration[]> {
enum DebugConfig {
LaunchCurrentFile,
LaunchScript,
InteractiveSession,
AttachHostProcess,
}
const debugConfigPickItems = [
{
id: DebugConfig.LaunchCurrentFile,
label: "Launch Current File",
description: "Launch and debug the file in the currently active editor window",
},
{
id: DebugConfig.LaunchScript,
label: "Launch Script",
description: "Launch and debug the specified file or command",
},
{
id: DebugConfig.InteractiveSession,
label: "Interactive Session",
description: "Debug commands executed from the Integrated Console",
},
{
id: DebugConfig.AttachHostProcess,
label: "Attach",
description: "Attach the debugger to a running PowerShell Host Process",
},
];
const launchSelection =
await vscode.window.showQuickPick(
debugConfigPickItems,
{ placeHolder: "Select a PowerShell debug configuration" });
// TODO: Make these available in a dictionary and share them.
switch (launchSelection.id) {
case DebugConfig.LaunchCurrentFile:
return [
{
name: "PowerShell: Launch Current File",
type: "PowerShell",
request: "launch",
script: "${file}",
cwd: "${file}",
},
];
case DebugConfig.LaunchScript:
return [
{
name: "PowerShell: Launch Script",
type: "PowerShell",
request: "launch",
script: "enter path or command to execute e.g.: ${workspaceFolder}/src/foo.ps1 or Invoke-Pester",
cwd: "${workspaceFolder}",
},
];
case DebugConfig.InteractiveSession:
return [
{
name: "PowerShell: Interactive Session",
type: "PowerShell",
request: "launch",
cwd: "",
},
];
case DebugConfig.AttachHostProcess:
return [
{
name: "PowerShell: Attach to PowerShell Host Process",
type: "PowerShell",
request: "attach",
runspaceId: 1,
},
];
}
}
// DebugConfigurationProvider method
public async resolveDebugConfiguration(
_folder: WorkspaceFolder | undefined,
config: DebugConfiguration,
_token?: CancellationToken): Promise<DebugConfiguration> {
// Make sure there is a session running before attempting to debug/run a program
// TODO: Perhaps this should just wait until it's running or aborted.
if (this.sessionManager.getSessionStatus() !== SessionStatus.Running) {
const msg = "Cannot debug or run a PowerShell script until the PowerShell session has started. " +
"Wait for the PowerShell session to finish starting and try again.";
vscode.window.showWarningMessage(msg);
return undefined;
}
// Starting a debug session can be done when there is no document open e.g. attach to PS host process
const currentDocument = vscode.window.activeTextEditor ? vscode.window.activeTextEditor.document : undefined;
const debugCurrentScript = (config.script === "${file}") || !config.request;
const generateLaunchConfig = !config.request;
const settings = Settings.load();
// If the createTemporaryIntegratedConsole field is not specified in the launch config, set the field using
// the value from the corresponding setting. Otherwise, the launch config value overrides the setting.
config.createTemporaryIntegratedConsole =
config.createTemporaryIntegratedConsole ??
settings.debugging.createTemporaryIntegratedConsole;
if (config.request === "attach") {
const platformDetails = getPlatformDetails();
const versionDetails = this.sessionManager.getPowerShellVersionDetails();
// Cross-platform attach to process was added in 6.2.0-preview.4
if (versionDetails.version < "6.2.0" && platformDetails.operatingSystem !== OperatingSystem.Windows) {
const msg = `Attaching to a PowerShell Host Process on ${
OperatingSystem[platformDetails.operatingSystem] } requires PowerShell 6.2 or higher.`;
return vscode.window.showErrorMessage(msg).then((_) => {
return undefined;
});
}
// if nothing is set, prompt for the processId
if (!config.customPipeName && !config.processId) {
config.processId = await vscode.commands.executeCommand("PowerShell.PickPSHostProcess");
// No process selected. Cancel attach.
if (!config.processId) {
return null;
}
}
if (!config.runspaceId && !config.runspaceName) {
config.runspaceId = await vscode.commands.executeCommand("PowerShell.PickRunspace", config.processId);
// No runspace selected. Cancel attach.
if (!config.runspaceId) {
return null;
}
}
}
// TODO: Use a named debug configuration.
if (generateLaunchConfig) {
// No launch.json, create the default configuration for both unsaved (Untitled) and saved documents.
config.type = "PowerShell";
config.name = "PowerShell: Launch Current File";
config.request = "launch";
config.args = [];
config.script =
currentDocument.isUntitled
? currentDocument.uri.toString()
: currentDocument.fileName;
if (config.createTemporaryIntegratedConsole) {
// For a folder-less workspace, vscode.workspace.rootPath will be undefined.
// PSES will convert that undefined to a reasonable working dir.
config.cwd =
currentDocument.isUntitled
? vscode.workspace.rootPath
: currentDocument.fileName;
} else {
// If the non-temp integrated console is being used, default to the current working dir.
config.cwd = "";
}
}
if (config.request === "launch") {
// For debug launch of "current script" (saved or unsaved), warn before starting the debugger if either
// A) there is not an active document
// B) the unsaved document's language type is not PowerShell
// C) the saved document's extension is a type that PowerShell can't debug.
if (debugCurrentScript) {
if (currentDocument === undefined) {
const msg = "To debug the \"Current File\", you must first open a " +
"PowerShell script file in the editor.";
vscode.window.showErrorMessage(msg);
return;
}
if (currentDocument.isUntitled) {
if (config.createTemporaryIntegratedConsole) {
const msg = "Debugging Untitled files in a temporary console is currently not supported.";
vscode.window.showErrorMessage(msg);
return;
}
if (currentDocument.languageId === "powershell") {
if (!generateLaunchConfig) {
// Cover the case of existing launch.json but unsaved (Untitled) document.
// In this case, vscode.workspace.rootPath will not be undefined.
config.script = currentDocument.uri.toString();
config.cwd = vscode.workspace.rootPath;
}
} else {
const msg = "To debug '" + currentDocument.fileName + "', change the document's " +
"language mode to PowerShell or save the file with a PowerShell extension.";
vscode.window.showErrorMessage(msg);
return;
}
} else {
let isValidExtension = false;
const extIndex = currentDocument.fileName.lastIndexOf(".");
if (extIndex !== -1) {
const ext = currentDocument.fileName.substr(extIndex + 1).toUpperCase();
isValidExtension = (ext === "PS1" || ext === "PSM1");
}
if ((currentDocument.languageId !== "powershell") || !isValidExtension) {
let docPath = currentDocument.fileName;
const workspaceRootPath = vscode.workspace.rootPath;
if (currentDocument.fileName.startsWith(workspaceRootPath)) {
docPath = currentDocument.fileName.substring(vscode.workspace.rootPath.length + 1);
}
const msg = "PowerShell does not support debugging this file type: '" + docPath + "'.";
vscode.window.showErrorMessage(msg);
return;
}
if (config.script === "${file}") {
config.script = currentDocument.fileName;
}
}
}
// NOTE: There is a tight coupling to a weird setting in
// `package.json` for the Launch Current File configuration where
// the default cwd is set to ${file}.
if ((currentDocument !== undefined) && (config.cwd === "${file}")) {
config.cwd = currentDocument.fileName;
}
}
// Prevent the Debug Console from opening
config.internalConsoleOptions = "neverOpen";
// Create or show the interactive console
vscode.commands.executeCommand("PowerShell.ShowSessionConsole", true);
if (config.createTemporaryIntegratedConsole) {
this.tempDebugProcess = this.sessionManager.createDebugSessionProcess(settings);
this.tempSessionDetails = await this.tempDebugProcess.start(`DebugSession-${this.sessionCount++}`);
}
return config;
}
}
export class SpecifyScriptArgsFeature implements vscode.Disposable {
private command: vscode.Disposable;
private context: vscode.ExtensionContext;
constructor(context: vscode.ExtensionContext) {
this.context = context;
this.command =
vscode.commands.registerCommand("PowerShell.SpecifyScriptArgs", () => {
return this.specifyScriptArguments();
});
}
public dispose() {
this.command.dispose();
}
private async specifyScriptArguments(): Promise<string> {
const powerShellDbgScriptArgsKey = "powerShellDebugScriptArgs";
const options: vscode.InputBoxOptions = {
ignoreFocusOut: true,
placeHolder: "Enter script arguments or leave empty to pass no args",
};
const prevArgs = this.context.workspaceState.get(powerShellDbgScriptArgsKey, "");
if (prevArgs.length > 0) {
options.value = prevArgs;
}
const text = await vscode.window.showInputBox(options);
// When user cancel's the input box (by pressing Esc), the text value is undefined.
// Let's not blow away the previous setting.
if (text !== undefined) {
this.context.workspaceState.update(powerShellDbgScriptArgsKey, text);
}
return text;
}
}
interface IProcessItem extends vscode.QuickPickItem {
pid: string; // payload for the QuickPick UI
}
interface IPSHostProcessInfo {
processName: string;
processId: string;
appDomainName: string;
mainWindowTitle: string;
}
export const GetPSHostProcessesRequestType =
new RequestType<any, IGetPSHostProcessesResponseBody, string>("powerShell/getPSHostProcesses");
interface IGetPSHostProcessesResponseBody {
hostProcesses: IPSHostProcessInfo[];
}
export class PickPSHostProcessFeature extends LanguageClientConsumer {
private command: vscode.Disposable;
private waitingForClientToken: vscode.CancellationTokenSource;
private getLanguageClientResolve: (value?: LanguageClient | Promise<LanguageClient>) => void;
constructor() {
super();
this.command =
vscode.commands.registerCommand("PowerShell.PickPSHostProcess", () => {
return this.getLanguageClient()
.then((_) => this.pickPSHostProcess(), (_) => undefined);
});
}
public setLanguageClient(languageClient: LanguageClient) {
this.languageClient = languageClient;
if (this.waitingForClientToken) {
this.getLanguageClientResolve(this.languageClient);
this.clearWaitingToken();
}
}
public dispose() {
this.command.dispose();
}
private getLanguageClient(): Promise<LanguageClient> {
if (this.languageClient) {
return Promise.resolve(this.languageClient);
} else {
// If PowerShell isn't finished loading yet, show a loading message
// until the LanguageClient is passed on to us
this.waitingForClientToken = new vscode.CancellationTokenSource();
return new Promise<LanguageClient>(
(resolve, reject) => {
this.getLanguageClientResolve = resolve;
vscode.window
.showQuickPick(
["Cancel"],
{ placeHolder: "Attach to PowerShell host process: Please wait, starting PowerShell..." },
this.waitingForClientToken.token)
.then((response) => {
if (response === "Cancel") {
this.clearWaitingToken();
reject();
}
});
// Cancel the loading prompt after 60 seconds
setTimeout(() => {
if (this.waitingForClientToken) {
this.clearWaitingToken();
reject();
vscode.window.showErrorMessage(
"Attach to PowerShell host process: PowerShell session took too long to start.");
}
}, 60000);
},
);
}
}
private async pickPSHostProcess(): Promise<string> {
const hostProcesses = await this.languageClient.sendRequest(GetPSHostProcessesRequestType, {});
// Start with the current PowerShell process in the list.
const items: IProcessItem[] = [{
label: "Current",
description: "The current PowerShell Integrated Console process.",
pid: "current",
}];
for (const p in hostProcesses) {
if (hostProcesses.hasOwnProperty(p)) {
let windowTitle = "";
if (hostProcesses[p].mainWindowTitle) {
windowTitle = `, Title: ${hostProcesses[p].mainWindowTitle}`;
}
items.push({
label: hostProcesses[p].processName,
description: `PID: ${hostProcesses[p].processId.toString()}${windowTitle}`,
pid: hostProcesses[p].processId,
});
}
}
if (items.length === 0) {
return Promise.reject("There are no PowerShell host processes to attach to.");
}
const options: vscode.QuickPickOptions = {
placeHolder: "Select a PowerShell host process to attach to",
matchOnDescription: true,
matchOnDetail: true,
};
const item = await vscode.window.showQuickPick(items, options);
return item ? `${item.pid}` : undefined;
}
private clearWaitingToken() {
if (this.waitingForClientToken) {
this.waitingForClientToken.dispose();
this.waitingForClientToken = undefined;
}
}
}
interface IRunspaceItem extends vscode.QuickPickItem {
id: string; // payload for the QuickPick UI
}
interface IRunspace {
id: number;
name: string;
availability: string;
}
export const GetRunspaceRequestType =
new RequestType<any, IRunspace[], string>("powerShell/getRunspace");
export class PickRunspaceFeature extends LanguageClientConsumer {
private command: vscode.Disposable;
private waitingForClientToken: vscode.CancellationTokenSource;
private getLanguageClientResolve: (value?: LanguageClient | Promise<LanguageClient>) => void;
constructor() {
super();
this.command =
vscode.commands.registerCommand("PowerShell.PickRunspace", (processId) => {
return this.getLanguageClient()
.then((_) => this.pickRunspace(processId), (_) => undefined);
}, this);
}
public setLanguageClient(languageClient: LanguageClient) {
this.languageClient = languageClient;
if (this.waitingForClientToken) {
this.getLanguageClientResolve(this.languageClient);
this.clearWaitingToken();
}
}
public dispose() {
this.command.dispose();
}
private getLanguageClient(): Promise<LanguageClient> {
if (this.languageClient) {
return Promise.resolve(this.languageClient);
} else {
// If PowerShell isn't finished loading yet, show a loading message
// until the LanguageClient is passed on to us
this.waitingForClientToken = new vscode.CancellationTokenSource();
return new Promise<LanguageClient>(
(resolve, reject) => {
this.getLanguageClientResolve = resolve;
vscode.window
.showQuickPick(
["Cancel"],
{ placeHolder: "Attach to PowerShell host process: Please wait, starting PowerShell..." },
this.waitingForClientToken.token)
.then((response) => {
if (response === "Cancel") {
this.clearWaitingToken();
reject();
}
});
// Cancel the loading prompt after 60 seconds
setTimeout(() => {
if (this.waitingForClientToken) {
this.clearWaitingToken();
reject();
vscode.window.showErrorMessage(
"Attach to PowerShell host process: PowerShell session took too long to start.");
}
}, 60000);
},
);
}
}
private async pickRunspace(processId: string): Promise<string> {
const response = await this.languageClient.sendRequest(GetRunspaceRequestType, { processId });
const items: IRunspaceItem[] = [];
for (const runspace of response) {
// Skip default runspace
if ((runspace.id === 1 || runspace.name === "PSAttachRunspace")
&& processId === "current") {
continue;
}
items.push({
label: runspace.name,
description: `ID: ${runspace.id} - ${runspace.availability}`,
id: runspace.id.toString(),
});
}
const options: vscode.QuickPickOptions = {
placeHolder: "Select PowerShell runspace to debug",
matchOnDescription: true,
matchOnDetail: true,
};
const item = await vscode.window.showQuickPick(items, options);
return item ? `${item.id}` : undefined;
}
private clearWaitingToken() {
if (this.waitingForClientToken) {
this.waitingForClientToken.dispose();
this.waitingForClientToken = undefined;
}
}
}