forked from PowerShell/PowerShellEditorServices
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathStart-DebugAttachSession.ps1
More file actions
183 lines (158 loc) · 6.04 KB
/
Start-DebugAttachSession.ps1
File metadata and controls
183 lines (158 loc) · 6.04 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
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
using namespace System.Collections
using namespace System.Management.Automation
using namespace System.Reflection
using namespace System.Threading
using namespace System.Threading.Tasks
function Start-DebugAttachSession {
<#
.EXTERNALHELP ..\PowerShellEditorServices.Commands-help.xml
#>
[OutputType([System.Management.Automation.Job2])]
[CmdletBinding(DefaultParameterSetName = 'ProcessId')]
param(
[Parameter()]
[string]
$Name,
[Parameter(ParameterSetName = 'ProcessId')]
[int]
$ProcessId,
[Parameter(ParameterSetName = 'CustomPipeName')]
[string]
$CustomPipeName,
[Parameter()]
[string]
$RunspaceName,
[Parameter()]
[int]
$RunspaceId,
[Parameter()]
[string]
$ComputerName,
[Parameter()]
[ValidateSet('Close', 'Hide', 'Keep')]
[string]
$WindowActionOnEnd,
[Parameter()]
[switch]
$AsJob
)
$ErrorActionPreference = 'Stop'
try {
if ($PSBoundParameters.ContainsKey('RunspaceId') -and $RunspaceName) {
$err = [ErrorRecord]::new(
[ArgumentException]::new("Cannot specify both RunspaceId and RunspaceName parameters"),
"InvalidRunspaceParameters",
[ErrorCategory]::InvalidArgument,
$null)
$err.ErrorDetails = [ErrorDetails]::new("")
$err.ErrorDetails.RecommendedAction = 'Specify only one of RunspaceId or RunspaceName.'
$PSCmdlet.WriteError($err)
return
}
# Var will be set by PSES in configurationDone before launching script
$debugServer = Get-Variable -Name __psEditorServices_DebugServer -ValueOnly -ErrorAction Ignore
if (-not $debugServer) {
$err = [ErrorRecord]::new(
[Exception]::new("Cannot start a new attach debug session unless running in an existing launch debug session not in a temporary console"),
"NoDebugSession",
[ErrorCategory]::InvalidOperation,
$null)
$err.ErrorDetails = [ErrorDetails]::new("")
$err.ErrorDetails.RecommendedAction = 'Launch script with debugging to ensure the debug session is available.'
$PSCmdlet.WriteError($err)
return
}
if ($AsJob -and -not (Get-Command -Name Start-ThreadJob -ErrorAction Ignore)) {
$err = [ErrorRecord]::new(
[Exception]::new("Cannot use the -AsJob parameter unless running on PowerShell 7+ or the ThreadJob module is present"),
"NoThreadJob",
[ErrorCategory]::InvalidArgument,
$null)
$err.ErrorDetails = [ErrorDetails]::new("")
$err.ErrorDetails.RecommendedAction = 'Install the ThreadJob module or run on PowerShell 7+.'
$PSCmdlet.WriteError($err)
return
}
$configuration = @{
type = 'PowerShell'
request = 'attach'
# A temp console is also needed as the current one is busy running
# this code. Failing to set this will cause a deadlock.
createTemporaryIntegratedConsole = $true
}
if ($ProcessId) {
if ($ProcessId -eq $PID) {
$err = [ErrorRecord]::new(
[ArgumentException]::new("PSES does not support attaching to the current editor process"),
"AttachToCurrentProcess",
[ErrorCategory]::InvalidArgument,
$PID)
$err.ErrorDetails = [ErrorDetails]::new("")
$err.ErrorDetails.RecommendedAction = 'Specify a different process id.'
$PSCmdlet.WriteError($err)
return
}
$configuration.name = "Attach Process $ProcessId"
$configuration.processId = $ProcessId
}
elseif ($CustomPipeName) {
$configuration.name = "Attach Pipe $CustomPipeName"
$configuration.customPipeName = $CustomPipeName
}
else {
$configuration.name = 'Attach Session'
}
if ($ComputerName) {
$configuration.computerName = $ComputerName
}
if ($PSBoundParameters.ContainsKey('RunspaceId')) {
$configuration.runspaceId = $RunspaceId
}
elseif ($RunspaceName) {
$configuration.runspaceName = $RunspaceName
}
if ($WindowActionOnEnd) {
$configuration.temporaryConsoleWindowActionOnDebugEnd = $WindowActionOnEnd.ToLowerInvariant()
}
# https://microsoft.github.io/debug-adapter-protocol/specification#Reverse_Requests_StartDebugging
$resp = $debugServer.SendRequest(
'startDebugging',
@{
configuration = $configuration
request = 'attach'
}
)
# PipelineStopToken added in pwsh 7.6
$cancelToken = if ($PSCmdlet.PipelineStopToken) {
$PSCmdlet.PipelineStopToken
}
else {
[CancellationToken]::new($false)
}
# There is no response for a startDebugging request
$task = $resp.ReturningVoid($cancelToken)
$waitTask = {
[CmdletBinding()]
param ([Parameter(Mandatory)][Task]$Task)
while (-not $Task.AsyncWaitHandle.WaitOne(300)) {}
$null = $Task.GetAwaiter().GetResult()
}
if ($AsJob) {
# Using the Ast to build the scriptblock allows the job to inherit
# the using namespace entries and include the proper line/script
# paths in any error traces that are emitted.
Start-ThreadJob -ScriptBlock {
& ($args[0]).Ast.GetScriptBlock() $args[1]
} -ArgumentList $waitTask, $task
}
else {
& $waitTask $task
}
}
catch {
$PSCmdlet.WriteError($_)
return
}
}