forked from nightroman/PowerShelf
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Add-Debugger.ps1
342 lines (297 loc) · 9.15 KB
/
Add-Debugger.ps1
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
<#
.Synopsis
Adds a script debugger to PowerShell.
Author: Roman Kuzmin
.Description
This script is designed for PowerShell runspaces which do not have their
own debuggers, e.g. Visual Studio NuGet console ("Package Manager Host"),
the default runspace host ("Default Host"), and etc. But it can be used
instead of build-in debuggers as well.
The script should be called once at any moment when debugging is needed.
In order to restore the original debugger invoke Restore-Debugger.
The GUI input box is used for typing of PowerShell and debugger commands.
For output of these commands the script uses Out-Host or a file with a
separate console started for watching the data.
.Parameter Path
Specifies the output file used instead of Out-Host.
A separate console is opened for watching the data.
.Inputs
None
.Outputs
None
.Example
>
How to debug terminating errors in a bare runspace. Use cases:
- In .NET the similar code is typical for invoking PowerShell.
- In PowerShell BeginInvoke() makes sense for background jobs.
$ps = [PowerShell]::Create()
$null = $ps.AddScript({
# add debugger with file output
Add-Debugger.ps1 $env:TEMP\debug.log
# enable debugging on terminating errors
$null = Set-PSBreakpoint -Variable StackTrace -Mode Write
# from now on the debugger dialog is shown on failures
# and a separate PowerShell output console is started
...
})
$ps.Invoke() # or BeginInvoke()
.Link
https://github.com/nightroman/PowerShelf
#>
param(
[Parameter()]
[string]$Path
)
# Restore another debugger by its Restore-Debugger.
if ((Test-Path Variable:\_Debugger) -and (Get-Variable _Debugger).Description -ne 'Add-Debugger.ps1') {
Restore-Debugger
}
# Removes and gets debugger handlers.
function global:Remove-Debugger {
$instance = [System.Management.Automation.Runspaces.Runspace]::DefaultRunspace.Debugger
$type = $instance.GetType()
$e = $type.GetEvent('DebuggerStop')
$v = $type.GetField('DebuggerStop', ([System.Reflection.BindingFlags]'NonPublic, Instance')).GetValue($instance)
if ($v) {
$handlers = $v.GetInvocationList()
foreach($handler in $handlers) {
$e.RemoveEventHandler($instance, $handler)
}
$handlers
}
}
# Restores original debugger handlers.
function global:Restore-Debugger {
if (!(Test-Path Variable:\_Debugger)) {return}
$null = Remove-Debugger
if ($_Debugger.Handlers) {
foreach($handler in $_Debugger.Handlers) {
[System.Management.Automation.Runspaces.Runspace]::DefaultRunspace.Debugger.add_DebuggerStop($handler)
}
}
Remove-Variable _Debugger -Scope Global -Force
}
# Add the debugger and data once
if (!(Test-Path Variable:\_Debugger)) {
$null = New-Variable -Name _Debugger -Scope Global -Description Add-Debugger.ps1 -Option ReadOnly -Value @{
History = [System.Collections.ArrayList]@()
Handlers = Remove-Debugger
DefaultContext = 0
Context = [ref]0
Action = '?'
}
[System.Management.Automation.Runspaces.Runspace]::DefaultRunspace.Debugger.add_DebuggerStop({. Invoke-DebuggerStop})
}
# Writes debugger output.
if ($Path) {
$_Debugger.Path = $PSCmdlet.GetUnresolvedProviderPathFromPSPath($Path)
$_Debugger.Watch = $true
function global:Write-Debugger($Data)
{
[System.IO.File]::AppendAllText($_Debugger.Path, ($Data | Out-String), [System.Text.Encoding]::Unicode)
if ($_Debugger.Watch) {
$_Debugger.Watch = $false
Watch-Debugger $_Debugger.Path
}
}
}
else {
$_Debugger.Path = $null
function global:Write-Debugger($Data)
{
$Data | Out-Host
}
}
# Reads debugger input.
function global:Read-Debugger(
$Prompt,
$Title,
$Default
)
{
Add-Type -AssemblyName Microsoft.VisualBasic
[Microsoft.VisualBasic.Interaction]::InputBox($Prompt, $Title, $Default)
}
# Starts an external file viewer.
function global:Watch-Debugger($Path)
{
$Path = $Path.Replace("'", "''")
Start-Process PowerShell.exe "-NoProfile Get-Content -LiteralPath '$Path' -Wait -ErrorAction 0"
}
# Writes the current invocation info.
function global:Write-DebuggerInfo(
$InvocationInfo,
$Context
)
{
# write position message
Write-Debugger ($InvocationInfo.PositionMessage.Trim())
# done?
$file = $InvocationInfo.ScriptName
if ($Context -le 0 -or !$file -or !(Test-Path -LiteralPath $file)) {return}
# write file lines
$markIndex = $InvocationInfo.ScriptLineNumber - 1
Write-DebuggerFile $file ($markIndex - $Context) (2 * $Context + 1) $markIndex
}
# Writes the specified file lines.
function global:Write-DebuggerFile(
$Path,
$LineIndex,
$LineCount,
$MarkIndex
)
{
# amend negative start
if ($LineIndex -lt 0) {
$LineCount += $lineIndex
$LineIndex = 0
}
# content lines
$lines = @(Get-Content -LiteralPath $Path -TotalCount ($LineIndex + $LineCount) -Force -ErrorAction 0)
# leading spaces
$space = ($lines[$LineIndex .. -1] | .{process{
if ($_ -match '^(\s*)\S') {
($matches[1] -replace "`t", ' ').Length
}
}} | Measure-Object -Minimum).Minimum
# write lines with a mark
Write-Debugger ''
do {
if (($line = $lines[$LineIndex]) -match '^(\s*)(\S.*)') {
$line = ($matches[1] -replace "`t", ' ').Substring($space) + $matches[2]
}
$mark = if ($LineIndex -eq $MarkIndex) {'=>'} else {' '}
Write-Debugger ('{0,4} {1} {2}' -f ($LineIndex + 1), $mark, $line)
}
while(++$LineIndex -lt $lines.Length)
Write-Debugger ''
}
# Processes DebuggerStop events.
function global:Invoke-DebuggerStop
{
# write breakpoints
if ($_.Breakpoints) {&{
Write-Debugger ''
foreach($b in $_.Breakpoints) {
if ($b -is [System.Management.Automation.VariableBreakpoint] -and $b.Variable -eq 'StackTrace') {
Write-Debugger 'TERMINATING ERROR BREAKPOINT'
}
else {
Write-Debugger "Hit $b"
}
}
}}
# write debug location
Write-DebuggerInfo $_.InvocationInfo $_Debugger.DefaultContext
Write-Debugger ''
# REPL
$_Debugger.e = $_
for() {
### prompt
$_Debugger.Action = (Read-Debugger "Enter PowerShell and debug commands.`nUse h or ? for help." Debugger $_Debugger.Action).Trim()
Write-Debugger "DBG> $($_Debugger.Action)"
### Continue
if (!$_Debugger.Action -or $_Debugger.Action -eq 'c' -or $_Debugger.Action -eq 'Continue') {
$_Debugger.e.ResumeAction = 'Continue'
return
}
### StepInto
if ($_Debugger.Action -eq 's' -or $_Debugger.Action -eq 'StepInto') {
$_Debugger.e.ResumeAction = 'StepInto'
return
}
### StepOver
if ($_Debugger.Action -eq 'v' -or $_Debugger.Action -eq 'StepOver') {
$_Debugger.e.ResumeAction = 'StepOver'
return
}
### StepOut
if ($_Debugger.Action -eq 'o' -or $_Debugger.Action -eq 'StepOut') {
$_Debugger.e.ResumeAction = 'StepOut'
return
}
### Quit
if ($_Debugger.Action -eq 'q' -or $_Debugger.Action -eq 'Quit') {
$_Debugger.e.ResumeAction = 'Stop'
return
}
### history
if ($_Debugger.Action -eq 'r') {
Write-Debugger $_Debugger.History
continue
}
### stack
if ($_Debugger.Action -ceq 'k') {
Write-Debugger (Get-PSCallStack | Format-Table Command, Location, Arguments -AutoSize)
continue
}
if ($_Debugger.Action -ceq 'K') {
Write-Debugger (Get-PSCallStack | Format-List)
continue
}
### <number>
if ([int]::TryParse($_Debugger.Action, $_Debugger.Context)) {
Write-DebuggerInfo $_Debugger.e.InvocationInfo $_Debugger.Context.Value
if ($_Debugger.Action[0] -eq "+") {
$_Debugger.DefaultContext = $_Debugger.Context.Value
}
continue
}
### watch
if ($_Debugger.Action -eq 'w') {
if ($_Debugger.Path) {
Watch-Debugger $_Debugger.Path
}
else {
Write-Debugger 'Debugger output file is not used.'
}
continue
}
### help
if ($_Debugger.Action -eq '?' -or $_Debugger.Action -eq 'h') {
Write-Debugger @'
s, StepInto Step to the next statement into functions, scripts, etc.
v, StepOver Step to the next statement over functions, scripts, etc.
o, StepOut Step out of the current function, script, etc.
c, Continue Continue operation (also on Cancel or empty).
q, Quit Stop operation and exit the debugger.
?, h Write this help message.
k Write call stack (Get-PSCallStack).
K Write detailed call stack using Format-List.
<n> Write debug location in context of <n> lines.
+<n> Set location context preference to <n> lines.
k <s> <n> Write source at stack <s> in context of <n> lines.
w Restart watching the debugger output file.
r Write last PowerShell commands invoked on debugging.
<command> Invoke any PowerShell <command> and write its output.
'@
continue
}
### stack <s> <n>
function k([Parameter()][int]$s, [int]$n) {
$stack = @(Get-PSCallStack)
if ($s -ge $stack.Count) {
Write-Debugger 'Out of range of the call stack.'
return
}
$1 = $stack[$s]
if (!($file = $1.ScriptName)) {
Write-Debugger 'The caller has no script file.'
return
}
if ($n -le 0) {$n = 5}
$markIndex = $1.ScriptLineNumber - 1
Write-Debugger $file
Write-DebuggerFile $file ($markIndex - $n) (2 * $n + 1) $markIndex
}
### invoke command
try {
$_Debugger.History.Remove($_Debugger.Action)
$null = $_Debugger.History.Add($_Debugger.Action)
Write-Debugger (.([scriptblock]::Create($_Debugger.Action)))
}
catch {
Write-Debugger $(if ($_.InvocationInfo.ScriptName -like '*\Add-Debugger.ps1') {$_.ToString()} else {$_})
}
}
}