forked from PowerShell/PowerShellEditorServices
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBreakpointApiUtils.cs
325 lines (263 loc) · 14.2 KB
/
BreakpointApiUtils.cs
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
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using System;
using System.Collections.Generic;
using System.Management.Automation;
using System.Management.Automation.Language;
using System.Reflection;
using System.Text;
using System.Threading;
using Microsoft.PowerShell.EditorServices.Utility;
namespace Microsoft.PowerShell.EditorServices.Services.DebugAdapter
{
internal static class BreakpointApiUtils
{
#region Private Static Fields
private const string s_psesGlobalVariableNamePrefix = "__psEditorServices_";
private static readonly Lazy<Func<Debugger, string, int, int, ScriptBlock, int?, LineBreakpoint>> s_setLineBreakpointLazy;
private static readonly Lazy<Func<Debugger, string, ScriptBlock, string, int?, CommandBreakpoint>> s_setCommandBreakpointLazy;
private static readonly Lazy<Func<Debugger, int?, List<Breakpoint>>> s_getBreakpointsLazy;
private static readonly Lazy<Func<Debugger, Breakpoint, int?, bool>> s_removeBreakpointLazy;
private static int breakpointHitCounter;
#endregion
#region Static Constructor
static BreakpointApiUtils()
{
// If this version of PowerShell does not support the new Breakpoint APIs introduced in PowerShell 7.0.0,
// do nothing as this class will not get used.
if (!SupportsBreakpointApis)
{
return;
}
s_setLineBreakpointLazy = new Lazy<Func<Debugger, string, int, int, ScriptBlock, int?, LineBreakpoint>>(() =>
{
Type[] setLineBreakpointParameters = new[] { typeof(string), typeof(int), typeof(int), typeof(ScriptBlock), typeof(int?) };
MethodInfo setLineBreakpointMethod = typeof(Debugger).GetMethod("SetLineBreakpoint", setLineBreakpointParameters);
return (Func<Debugger, string, int, int, ScriptBlock, int?, LineBreakpoint>)Delegate.CreateDelegate(
typeof(Func<Debugger, string, int, int, ScriptBlock, int?, LineBreakpoint>),
firstArgument: null,
setLineBreakpointMethod);
});
s_setCommandBreakpointLazy = new Lazy<Func<Debugger, string, ScriptBlock, string, int?, CommandBreakpoint>>(() =>
{
Type[] setCommandBreakpointParameters = new[] { typeof(string), typeof(ScriptBlock), typeof(string), typeof(int?) };
MethodInfo setCommandBreakpointMethod = typeof(Debugger).GetMethod("SetCommandBreakpoint", setCommandBreakpointParameters);
return (Func<Debugger, string, ScriptBlock, string, int?, CommandBreakpoint>)Delegate.CreateDelegate(
typeof(Func<Debugger, string, ScriptBlock, string, int?, CommandBreakpoint>),
firstArgument: null,
setCommandBreakpointMethod);
});
s_getBreakpointsLazy = new Lazy<Func<Debugger, int?, List<Breakpoint>>>(() =>
{
Type[] getBreakpointsParameters = new[] { typeof(int?) };
MethodInfo getBreakpointsMethod = typeof(Debugger).GetMethod("GetBreakpoints", getBreakpointsParameters);
return (Func<Debugger, int?, List<Breakpoint>>)Delegate.CreateDelegate(
typeof(Func<Debugger, int?, List<Breakpoint>>),
firstArgument: null,
getBreakpointsMethod);
});
s_removeBreakpointLazy = new Lazy<Func<Debugger, Breakpoint, int?, bool>>(() =>
{
Type[] removeBreakpointParameters = new[] { typeof(Breakpoint), typeof(int?) };
MethodInfo removeBreakpointMethod = typeof(Debugger).GetMethod("RemoveBreakpoint", removeBreakpointParameters);
return (Func<Debugger, Breakpoint, int?, bool>)Delegate.CreateDelegate(
typeof(Func<Debugger, Breakpoint, int?, bool>),
firstArgument: null,
removeBreakpointMethod);
});
}
#endregion
#region Public Static Properties
private static Func<Debugger, string, int, int, ScriptBlock, int?, LineBreakpoint> SetLineBreakpointDelegate => s_setLineBreakpointLazy.Value;
private static Func<Debugger, string, ScriptBlock, string, int?, CommandBreakpoint> SetCommandBreakpointDelegate => s_setCommandBreakpointLazy.Value;
private static Func<Debugger, int?, List<Breakpoint>> GetBreakpointsDelegate => s_getBreakpointsLazy.Value;
private static Func<Debugger, Breakpoint, int?, bool> RemoveBreakpointDelegate => s_removeBreakpointLazy.Value;
#endregion
#region Public Static Properties
// TODO: Try to compute this more dynamically. If we're launching a script in the PSIC, there are APIs are available in PS 5.1 and up.
// For now, only PS7 or greater gets this feature.
public static bool SupportsBreakpointApis => VersionUtils.IsPS7OrGreater;
#endregion
#region Public Static Methods
public static Breakpoint SetBreakpoint(Debugger debugger, BreakpointDetailsBase breakpoint, int? runspaceId = null)
{
ScriptBlock actionScriptBlock = null;
string logMessage = breakpoint is BreakpointDetails bd ? bd.LogMessage : null;
// Check if this is a "conditional" line breakpoint.
if (!string.IsNullOrWhiteSpace(breakpoint.Condition) ||
!string.IsNullOrWhiteSpace(breakpoint.HitCondition) ||
!string.IsNullOrWhiteSpace(logMessage))
{
actionScriptBlock = GetBreakpointActionScriptBlock(
breakpoint.Condition,
breakpoint.HitCondition,
logMessage,
out string errorMessage);
if (!string.IsNullOrEmpty(errorMessage))
{
// This is handled by the caller where it will set the 'Message' and 'Verified' on the BreakpointDetails
throw new InvalidOperationException(errorMessage);
}
}
switch (breakpoint)
{
case BreakpointDetails lineBreakpoint:
return SetLineBreakpointDelegate(debugger, lineBreakpoint.Source, lineBreakpoint.LineNumber, lineBreakpoint.ColumnNumber ?? 0, actionScriptBlock, runspaceId);
case CommandBreakpointDetails commandBreakpoint:
return SetCommandBreakpointDelegate(debugger, commandBreakpoint.Name, null, null, runspaceId);
default:
throw new NotImplementedException("Other breakpoints not supported yet");
}
}
public static List<Breakpoint> GetBreakpoints(Debugger debugger, int? runspaceId = null)
{
return GetBreakpointsDelegate(debugger, runspaceId);
}
public static bool RemoveBreakpoint(Debugger debugger, Breakpoint breakpoint, int? runspaceId = null)
{
return RemoveBreakpointDelegate(debugger, breakpoint, runspaceId);
}
/// <summary>
/// Inspects the condition, putting in the appropriate scriptblock template
/// "if (expression) { break }". If errors are found in the condition, the
/// breakpoint passed in is updated to set Verified to false and an error
/// message is put into the breakpoint.Message property.
/// </summary>
/// <param name="condition">The expression that needs to be true for the breakpoint to be triggered.</param>
/// <param name="hitCondition">The amount of times this line should be hit til the breakpoint is triggered.</param>
/// <param name="logMessage">The log message to write instead of calling 'break'. In VS Code, this is called a 'logPoint'.</param>
/// <returns>ScriptBlock</returns>
public static ScriptBlock GetBreakpointActionScriptBlock(string condition, string hitCondition, string logMessage, out string errorMessage)
{
errorMessage = null;
try
{
StringBuilder builder = new StringBuilder(
string.IsNullOrEmpty(logMessage)
? "break"
: $"Microsoft.PowerShell.Utility\\Write-Host \"{logMessage.Replace("\"","`\"")}\"");
// If HitCondition specified, parse and verify it.
if (!(string.IsNullOrWhiteSpace(hitCondition)))
{
if (!int.TryParse(hitCondition, out int parsedHitCount))
{
throw new InvalidOperationException("Hit Count was not a valid integer.");
}
if(string.IsNullOrWhiteSpace(condition))
{
// In the HitCount only case, this is simple as we can just use the HitCount
// property on the breakpoint object which is represented by $_.
builder.Insert(0, $"if ($_.HitCount -eq {parsedHitCount}) {{ ")
.Append(" }");
}
int incrementResult = Interlocked.Increment(ref breakpointHitCounter);
string globalHitCountVarName =
$"$global:{s_psesGlobalVariableNamePrefix}BreakHitCounter_{incrementResult}";
builder.Insert(0, $"if (++{globalHitCountVarName} -eq {parsedHitCount}) {{ ")
.Append(" }");
}
if (!string.IsNullOrWhiteSpace(condition))
{
ScriptBlock parsed = ScriptBlock.Create(condition);
// Check for simple, common errors that ScriptBlock parsing will not catch
// e.g. $i == 3 and $i > 3
if (!ValidateBreakpointConditionAst(parsed.Ast, out string message))
{
throw new InvalidOperationException(message);
}
// Check for "advanced" condition syntax i.e. if the user has specified
// a "break" or "continue" statement anywhere in their scriptblock,
// pass their scriptblock through to the Action parameter as-is.
if (parsed.Ast.Find(ast =>
(ast is BreakStatementAst || ast is ContinueStatementAst), true) != null)
{
return parsed;
}
builder.Insert(0, $"if ({condition}) {{ ")
.Append(" }");
}
return ScriptBlock.Create(builder.ToString());
}
catch (ParseException e)
{
errorMessage = ExtractAndScrubParseExceptionMessage(e, condition);
return null;
}
catch (InvalidOperationException e)
{
errorMessage = e.Message;
return null;
}
}
private static bool ValidateBreakpointConditionAst(Ast conditionAst, out string message)
{
message = string.Empty;
// We are only inspecting a few simple scenarios in the EndBlock only.
if (conditionAst is ScriptBlockAst scriptBlockAst &&
scriptBlockAst.BeginBlock == null &&
scriptBlockAst.ProcessBlock == null &&
scriptBlockAst.EndBlock != null &&
scriptBlockAst.EndBlock.Statements.Count == 1)
{
StatementAst statementAst = scriptBlockAst.EndBlock.Statements[0];
string condition = statementAst.Extent.Text;
if (statementAst is AssignmentStatementAst)
{
message = FormatInvalidBreakpointConditionMessage(condition, "Use '-eq' instead of '=='.");
return false;
}
if (statementAst is PipelineAst pipelineAst
&& pipelineAst.PipelineElements.Count == 1
&& pipelineAst.PipelineElements[0].Redirections.Count > 0)
{
message = FormatInvalidBreakpointConditionMessage(condition, "Use '-gt' instead of '>'.");
return false;
}
}
return true;
}
private static string ExtractAndScrubParseExceptionMessage(ParseException parseException, string condition)
{
string[] messageLines = parseException.Message.Split('\n');
// Skip first line - it is a location indicator "At line:1 char: 4"
for (int i = 1; i < messageLines.Length; i++)
{
string line = messageLines[i];
if (line.StartsWith("+"))
{
continue;
}
if (!string.IsNullOrWhiteSpace(line))
{
// Note '==' and '>" do not generate parse errors
if (line.Contains("'!='"))
{
line += " Use operator '-ne' instead of '!='.";
}
else if (line.Contains("'<'") && condition.Contains("<="))
{
line += " Use operator '-le' instead of '<='.";
}
else if (line.Contains("'<'"))
{
line += " Use operator '-lt' instead of '<'.";
}
else if (condition.Contains(">="))
{
line += " Use operator '-ge' instead of '>='.";
}
return FormatInvalidBreakpointConditionMessage(condition, line);
}
}
// If the message format isn't in a form we expect, just return the whole message.
return FormatInvalidBreakpointConditionMessage(condition, parseException.Message);
}
private static string FormatInvalidBreakpointConditionMessage(string condition, string message)
{
return $"'{condition}' is not a valid PowerShell expression. {message}";
}
#endregion
}
}