forked from PowerShell/PSScriptAnalyzer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUseUsingScopeModifierInNewRunspaces.cs
521 lines (458 loc) · 24 KB
/
UseUsingScopeModifierInNewRunspaces.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
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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
#if !CORECLR
using System.ComponentModel.Composition;
#endif
using System.Globalization;
using System.Linq;
using System.Management.Automation.Language;
using Microsoft.Windows.PowerShell.ScriptAnalyzer.Generic;
namespace Microsoft.Windows.PowerShell.ScriptAnalyzer.BuiltinRules
{
/// <summary>
/// UseUsingScopeModifierInNewRunspaces: Analyzes the ast to check that variables in script blocks that run in new run spaces are properly initialized or passed in with '$using:(varName)'.
/// </summary>
#if !CORECLR
[Export(typeof(IScriptRule))]
#endif
public class UseUsingScopeModifierInNewRunspaces : IScriptRule
{
/// <summary>
/// AnalyzeScript: Analyzes the ast to check variables in script blocks that will run in new runspaces are properly initialized or passed in with $using:
/// </summary>
/// <param name="ast">The script's ast</param>
/// <param name="fileName">The script's file name</param>
/// <returns>A List of results from this rule</returns>
public IEnumerable<DiagnosticRecord> AnalyzeScript(Ast ast, string fileName)
{
var visitor = new SyntaxCompatibilityVisitor(this, fileName);
ast.Visit(visitor);
return visitor.GetDiagnosticRecords();
}
/// <summary>
/// GetName: Retrieves the name of this rule.
/// </summary>
/// <returns>The name of this rule</returns>
public string GetName()
{
return string.Format(
CultureInfo.CurrentCulture,
Strings.NameSpaceFormat,
GetSourceName(),
Strings.UseUsingScopeModifierInNewRunspacesName);
}
/// <summary>
/// GetCommonName: Retrieves the common name of this rule.
/// </summary>
/// <returns>The common name of this rule</returns>
public string GetCommonName()
{
return string.Format(CultureInfo.CurrentCulture, Strings.UseUsingScopeModifierInNewRunspacesCommonName);
}
/// <summary>
/// GetDescription: Retrieves the description of this rule.
/// </summary>
/// <returns>The description of this rule</returns>
public string GetDescription()
{
return string.Format(CultureInfo.CurrentCulture, Strings.UseUsingScopeModifierInNewRunspacesDescription);
}
/// <summary>
/// GetSourceType: Retrieves the type of the rule: builtin, managed or module.
/// </summary>
public SourceType GetSourceType()
{
return SourceType.Builtin;
}
/// <summary>
/// GetSeverity: Retrieves the severity of the rule: error, warning of information.
/// </summary>
/// <returns></returns>
public RuleSeverity GetSeverity()
{
return RuleSeverity.Warning;
}
/// <summary>
/// GetSourceName: Retrieves the module/assembly name the rule is from.
/// </summary>
public string GetSourceName()
{
return string.Format(CultureInfo.CurrentCulture, Strings.SourceName);
}
#if !(PSV3 || PSV4)
private class SyntaxCompatibilityVisitor : AstVisitor2
#else
private class SyntaxCompatibilityVisitor : AstVisitor
#endif
{
private const DiagnosticSeverity Severity = DiagnosticSeverity.Warning;
private static readonly string[] s_dscScriptResourceCommandNames = {"GetScript", "TestScript", "SetScript"};
private static readonly IEnumerable<string> s_jobCmdletNamesAndAliases =
Helper.Instance.CmdletNameAndAliases("Start-Job");
private static readonly IEnumerable<string> s_threadJobCmdletNamesAndAliases =
Helper.Instance.CmdletNameAndAliases("Start-ThreadJob");
private static readonly IEnumerable<string> s_inlineScriptCmdletNamesAndAliases =
Helper.Instance.CmdletNameAndAliases("InlineScript");
private static readonly IEnumerable<string> s_foreachObjectCmdletNamesAndAliases =
Helper.Instance.CmdletNameAndAliases("Foreach-Object");
private static readonly IEnumerable<string> s_invokeCommandCmdletNamesAndAliases =
Helper.Instance.CmdletNameAndAliases("Invoke-Command");
private readonly Dictionary<string, HashSet<string>> _varsDeclaredPerSession;
private readonly List<DiagnosticRecord> _diagnosticAccumulator;
private readonly UseUsingScopeModifierInNewRunspaces _rule;
private readonly string _analyzedFilePath;
public SyntaxCompatibilityVisitor(UseUsingScopeModifierInNewRunspaces rule, string analyzedScriptPath)
{
_diagnosticAccumulator = new List<DiagnosticRecord>();
_varsDeclaredPerSession = new Dictionary<string, HashSet<string>>();
_rule = rule;
_analyzedFilePath = analyzedScriptPath;
}
/// <summary>
/// GetDiagnosticRecords: Retrieves all Diagnostic Records that were generated during visiting
/// </summary>
public IEnumerable<DiagnosticRecord> GetDiagnosticRecords()
{
return _diagnosticAccumulator;
}
/// <summary>
/// VisitScriptBlockExpression: When a ScriptBlockExpression is visited, see if it belongs to a command that needs its variables
/// prefixed with the 'Using' scope modifier. If so, analyze the block and generate diagnostic records for variables where it is missing.
/// </summary>
/// <param name="scriptBlockExpressionAst"></param>
/// <returns>
/// AstVisitAction.Continue or AstVisitAction.SkipChildren, depending on what we found. Diagnostic records are saved in `_diagnosticAccumulator`.
/// </returns>
public override AstVisitAction VisitScriptBlockExpression(ScriptBlockExpressionAst scriptBlockExpressionAst)
{
if (!(scriptBlockExpressionAst.Parent is CommandAst commandAst))
{
return AstVisitAction.Continue;
}
string cmdName = commandAst.GetCommandName();
if (cmdName == null)
{
// Skip for situations where command name cannot be resolved like `& $commandName -ComputerName -ScriptBlock { $foo }`
return AstVisitAction.SkipChildren;
}
// We need this information, because some cmdlets can have more than one ScriptBlock parameter
var scriptBlockParameterAst = commandAst.CommandElements[
commandAst.CommandElements.IndexOf(scriptBlockExpressionAst) - 1] as CommandParameterAst;
if (IsInlineScriptBlock(cmdName) ||
IsJobScriptBlock(cmdName, scriptBlockParameterAst) ||
IsForeachScriptBlock(cmdName, scriptBlockParameterAst) ||
IsInvokeCommandComputerScriptBlock(cmdName, commandAst) ||
IsDSCScriptResource(cmdName, commandAst))
{
AnalyzeScriptBlock(scriptBlockExpressionAst);
return AstVisitAction.SkipChildren;
}
if (IsInvokeCommandSessionScriptBlock(cmdName, commandAst))
{
if (!TryGetSessionNameFromInvokeCommand(commandAst, out var sessionName))
{
return AstVisitAction.Continue;
}
IReadOnlyCollection<string> varsInLocalAssignments = FindVarsInAssignmentAsts(scriptBlockExpressionAst);
if (varsInLocalAssignments != null)
{
AddAssignedVarsToSession(sessionName, varsInLocalAssignments);
}
GenerateDiagnosticRecords(
FindNonAssignedNonUsingVarAsts(
scriptBlockExpressionAst,
GetAssignedVarsInSession(sessionName)));
return AstVisitAction.SkipChildren;
}
return AstVisitAction.Continue;
}
/// <summary>
/// FindVarsInAssignmentAsts: Retrieves all assigned variables from an Ast:
/// Example: `$foo = "foo"` ==> the VariableExpressionAst for $foo is returned
/// </summary>
/// <param name="ast"></param>
private static IReadOnlyCollection<string> FindVarsInAssignmentAsts(Ast ast)
{
HashSet<string> variableDictionary =
new HashSet<string>();
// Find all variables that are assigned within this ast
foreach (AssignmentStatementAst statementAst in ast.FindAll(IsAssignmentStatementAst, true))
{
if (TryGetVariableFromExpression(statementAst.Left, out VariableExpressionAst variable))
{
string variableName = string.Format(variable.VariablePath.UserPath,
StringComparer.OrdinalIgnoreCase);
variableDictionary.Add(variableName);
}
};
return variableDictionary;
}
/// <summary>
/// TryGetVariableFromExpression: extracts the variable from an expression like an assignment
/// </summary>
/// <param name="expression"></param>
/// <param name="variableExpressionAst"></param>
private static bool TryGetVariableFromExpression(ExpressionAst expression, out VariableExpressionAst variableExpressionAst)
{
switch (expression)
{
case VariableExpressionAst variable:
variableExpressionAst = variable;
return true;
case AttributedExpressionAst attributedAst:
return TryGetVariableFromExpression(attributedAst.Child, out variableExpressionAst);
default:
variableExpressionAst = null;
return false;
}
}
/// <summary>
/// IsAssignmentStatementAst: helper function to prevent allocation of closures for FindAll predicate.
/// </summary>
/// <param name="ast"></param>
private static bool IsAssignmentStatementAst(Ast ast)
{
return ast is AssignmentStatementAst;
}
/// <summary>
/// FindNonAssignedNonUsingVarAsts: Retrieve variables that are:
/// - not assigned before
/// - not prefixed with the 'Using' scope modifier
/// - not a PowerShell special variable
/// </summary>
/// <param name="ast"></param>
/// <param name="varsInAssignments"></param>
private static IEnumerable<VariableExpressionAst> FindNonAssignedNonUsingVarAsts(
Ast ast, IReadOnlyCollection<string> varsInAssignments)
{
// Find all variables that are not locally assigned, and don't have $using: scope modifier
foreach (VariableExpressionAst variable in ast.FindAll(IsNonUsingNonSpecialVariableExpressionAst, true))
{
var varName = string.Format(variable.VariablePath.UserPath, StringComparer.OrdinalIgnoreCase);
if (varsInAssignments.Contains(varName))
{
yield break;
}
yield return variable;
}
}
/// <summary>
/// IsNonUsingNonSpecialVariableExpressionAst: helper function to prevent allocation of closures for FindAll predicate.
/// </summary>
/// <param name="ast"></param>
private static bool IsNonUsingNonSpecialVariableExpressionAst(Ast ast)
{
return ast is VariableExpressionAst variable &&
!(variable.Parent is UsingExpressionAst) &&
!Helper.Instance.HasSpecialVars(variable.VariablePath.UserPath);
}
/// <summary>
/// GetSuggestedCorrections: Retrieves a CorrectionExtent for a given variable
/// </summary>
/// <param name="ast"></param>
private static IEnumerable<CorrectionExtent> GetSuggestedCorrections(VariableExpressionAst ast)
{
string varWithUsing = $"$using:{ast.VariablePath.UserPath}";
var description = string.Format(
CultureInfo.CurrentCulture,
Strings.UseUsingScopeModifierInNewRunspacesCorrectionDescription,
ast.Extent.Text,
varWithUsing);
return new[]
{
new CorrectionExtent(
startLineNumber: ast.Extent.StartLineNumber,
endLineNumber: ast.Extent.EndLineNumber,
startColumnNumber: ast.Extent.StartColumnNumber,
endColumnNumber: ast.Extent.EndColumnNumber,
text: varWithUsing,
file: ast.Extent.File,
description: description
)
};
}
/// <summary>
/// TryGetSessionNameFromInvokeCommand: Retrieves the name of the session (that Invoke-Command is run with).
/// </summary>
/// <param name="invokeCommandAst"></param>
/// <param name="sessionName"></param>
/// <returns></returns>
private static bool TryGetSessionNameFromInvokeCommand(CommandAst invokeCommandAst, out string sessionName)
{
// Sift through Invoke-Command parameters to find the value of the -Session parameter
// Start at 1 to skip the command name
for (int i = 1; i < invokeCommandAst.CommandElements.Count; i++)
{
// We need a parameter
if (!(invokeCommandAst.CommandElements[i] is CommandParameterAst parameterAst))
{
continue;
}
// The parameter must be called "Session"
if (!parameterAst.ParameterName.Equals("Session", StringComparison.OrdinalIgnoreCase))
{
continue;
}
// If we have a partial AST, ensure we don't crash
if (i + 1 >= invokeCommandAst.CommandElements.Count)
{
break;
}
// The -Session parameter expects an argument of type [System.Management.Automation.Runspaces.PSSession].
// It will typically be provided in the form of a variable. We do not support other scenarios at this time.
if (!(invokeCommandAst.CommandElements[i + 1] is VariableExpressionAst variableAst))
{
break;
}
sessionName = variableAst.VariablePath.UserPath;
return true;
}
sessionName = null;
return false;
}
/// <summary>
/// GetAssignedVarsInSession: Retrieves all previously declared vars for a given session (as in Invoke-Command -Session $session).
/// </summary>
/// <param name="sessionName"></param>
private IReadOnlyCollection<string> GetAssignedVarsInSession(string sessionName)
{
return _varsDeclaredPerSession[sessionName];
}
/// <summary>
/// AddAssignedVarsToSession: Adds variables to the list of assigned variables for a given Invoke-Command session.
/// </summary>
/// <param name="sessionName"></param>
/// <param name="variablesToAdd"></param>
private void AddAssignedVarsToSession(string sessionName, IReadOnlyCollection<string> variablesToAdd)
{
if (!_varsDeclaredPerSession.ContainsKey(sessionName))
{
_varsDeclaredPerSession.Add(sessionName, new HashSet<string>());
}
foreach (var item in variablesToAdd)
{
if (!_varsDeclaredPerSession[sessionName].Contains(item))
{
_varsDeclaredPerSession[sessionName].Add(item);
}
}
}
/// <summary>
/// AnalyzeScriptBlock: Generate a Diagnostic Record for each incorrectly used variable inside a given ScriptBlock.
/// </summary>
/// <param name="scriptBlockExpressionAst"></param>
private void AnalyzeScriptBlock(ScriptBlockExpressionAst scriptBlockExpressionAst)
{
IEnumerable<VariableExpressionAst> nonAssignedNonUsingVarAsts = FindNonAssignedNonUsingVarAsts(
scriptBlockExpressionAst,
FindVarsInAssignmentAsts(scriptBlockExpressionAst));
GenerateDiagnosticRecords(nonAssignedNonUsingVarAsts);
}
/// <summary>
/// GenerateDiagnosticRecords: Add Diagnostic Records to the internal list for each given variable
/// </summary>
/// <param name="nonAssignedNonUsingVarAsts"></param>
private void GenerateDiagnosticRecords(IEnumerable<VariableExpressionAst> nonAssignedNonUsingVarAsts)
{
foreach (VariableExpressionAst variableExpression in nonAssignedNonUsingVarAsts)
{
string diagnosticMessage = string.Format(
CultureInfo.CurrentCulture,
Strings.UseUsingScopeModifierInNewRunspacesError,
variableExpression.ToString());
_diagnosticAccumulator.Add(
new DiagnosticRecord(
diagnosticMessage,
variableExpression.Extent,
_rule.GetName(),
Severity,
_analyzedFilePath,
ruleId: _rule.GetName(),
GetSuggestedCorrections(ast: variableExpression)));
}
}
/// <summary>
/// IsInvokeCommandSessionScriptBlock: Returns true if:
/// - command is 'Invoke-Command' (or alias)
/// - parameter '-Session' is present
/// </summary>
/// <param name="cmdName"></param>
/// <param name="commandAst"></param>
private bool IsInvokeCommandSessionScriptBlock(string cmdName, CommandAst commandAst)
{
return s_invokeCommandCmdletNamesAndAliases.Contains(cmdName, StringComparer.OrdinalIgnoreCase) &&
commandAst.CommandElements.Any(
e => e is CommandParameterAst parameterAst &&
parameterAst.ParameterName.Equals("session", StringComparison.OrdinalIgnoreCase));
}
/// <summary>
/// IsInvokeCommandComputerScriptBlock: Returns true if:
/// - command is 'Invoke-Command' (or alias)
/// - parameter '-Computer' is present
/// </summary>
/// <param name="cmdName"></param>
/// <param name="commandAst"></param>
private bool IsInvokeCommandComputerScriptBlock(string cmdName, CommandAst commandAst)
{
// 'com' is the shortest unambiguous form for the '-Computer' parameter
return s_invokeCommandCmdletNamesAndAliases.Contains(cmdName, StringComparer.OrdinalIgnoreCase) &&
commandAst.CommandElements.Any(
e => e is CommandParameterAst parameterAst &&
parameterAst.ParameterName.StartsWith("com", StringComparison.OrdinalIgnoreCase));
}
/// <summary>
/// IsForeachScriptBlock: Returns true if:
/// - command is 'Foreach-Object' (or alias)
/// - parameter '-Parallel' is present
/// </summary>
/// <param name="cmdName"></param>
/// <param name="scriptBlockParameterAst"></param>
private bool IsForeachScriptBlock(string cmdName, CommandParameterAst scriptBlockParameterAst)
{
// 'pa' is the shortest unambiguous form for the '-Parallel' parameter
return s_foreachObjectCmdletNamesAndAliases.Contains(cmdName, StringComparer.OrdinalIgnoreCase) &&
(scriptBlockParameterAst != null &&
scriptBlockParameterAst.ParameterName.StartsWith("pa", StringComparison.OrdinalIgnoreCase));
}
/// <summary>
/// IsJobScriptBlock: Returns true if:
/// - command is 'Start-Job' or 'Start-ThreadJob' (or alias)
/// - parameter name for this ScriptBlock not '-InitializationScript'
/// </summary>
/// <param name="cmdName"></param>
/// <param name="scriptBlockParameterAst"></param>
private bool IsJobScriptBlock(string cmdName, CommandParameterAst scriptBlockParameterAst)
{
// 'ini' is the shortest unambiguous form for the '-InitializationScript' parameter
return (s_jobCmdletNamesAndAliases.Contains(cmdName, StringComparer.OrdinalIgnoreCase) ||
s_threadJobCmdletNamesAndAliases.Contains(cmdName, StringComparer.OrdinalIgnoreCase)) &&
!(scriptBlockParameterAst != null &&
scriptBlockParameterAst.ParameterName.StartsWith("ini", StringComparison.OrdinalIgnoreCase));
}
/// <summary>
/// IsInlineScriptBlock: Returns true if:
/// - command is 'InlineScript' (or alias)
/// </summary>
/// <param name="cmdName"></param>
private bool IsInlineScriptBlock(string cmdName)
{
return s_inlineScriptCmdletNamesAndAliases.Contains(cmdName, StringComparer.OrdinalIgnoreCase);
}
/// <summary>
/// IsDSCScriptResource: Returns true if:
/// - command is 'GetScript', 'TestScript' or 'SetScript'
/// </summary>
/// <param name="commandAst"></param>
private bool IsDSCScriptResource(string cmdName, CommandAst commandAst)
{
// Inside DSC Script resource, GetScript is of the form 'Script foo { GetScript = {} }'
// If we reach this point in the code, we are sure there are at least two CommandElements, so the index of [1] will not fail.
return s_dscScriptResourceCommandNames.Contains(cmdName, StringComparer.OrdinalIgnoreCase) &&
commandAst.CommandElements[1].ToString() == "=";
}
}
}
}