-
Notifications
You must be signed in to change notification settings - Fork 382
/
Helper.cs
4041 lines (3500 loc) · 134 KB
/
Helper.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
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
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using Microsoft.Windows.PowerShell.ScriptAnalyzer.Generic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Management.Automation;
using System.Management.Automation.Language;
using System.Management.Automation.Runspaces;
namespace Microsoft.Windows.PowerShell.ScriptAnalyzer
{
/// <summary>
/// This Helper class contains utility/helper functions for classes in ScriptAnalyzer.
/// </summary>
public class Helper
{
#region Private members
private CommandInvocationIntrinsics invokeCommand;
private readonly static Version minSupportedPSVersion = new Version(3, 0);
private Dictionary<string, Dictionary<string, object>> ruleArguments;
private PSVersionTable psVersionTable;
private readonly Lazy<CommandInfoCache> _commandInfoCacheLazy;
private readonly object _testModuleManifestLock = new object();
#endregion
#region Singleton
private static object syncRoot = new Object();
private static Helper instance;
/// <summary>
/// The helper instance that handles utility functions
/// </summary>
public static Helper Instance
{
get
{
if (instance == null)
{
Instance = new Helper();
}
return instance;
}
internal set
{
lock (syncRoot)
{
if (instance == null)
{
instance = value;
}
}
}
}
#endregion
#region Properties
/// <summary>
/// Dictionary contains mapping of cmdlet to alias
/// </summary>
private Dictionary<String, List<String>> CmdletToAliasDictionary;
/// <summary>
/// Dictionary contains mapping of alias to cmdlet
/// </summary>
private Dictionary<String, String> AliasToCmdletDictionary;
internal TupleComparer tupleComparer = new TupleComparer();
/// <summary>
/// My Tokens
/// </summary>
public Token[] Tokens { get; set; }
/// <summary>
/// Key of the dictionary is keyword or command like configuration or workflows.
/// Value is a list of integer (in pairs). The first item in a pair is
/// the starting position of the open curly brace and the second item
/// is the closing position of the closing curly brace.
/// </summary>
private Dictionary<String, List<Tuple<int, int>>> KeywordBlockDictionary;
/// <summary>
/// Key of dictionary is ast, value is the corresponding variableanalysis
/// </summary>
private Dictionary<Ast, VariableAnalysis> VariableAnalysisDictionary;
private string[] functionScopes = new string[] { "global:", "local:", "script:", "private:"};
private string[] variableScopes = new string[] { "global:", "local:", "script:", "private:", "variable:", ":"};
/// <summary>
/// Store of command info objects for commands. Memoizes results.
/// </summary>
private CommandInfoCache CommandInfoCache => _commandInfoCacheLazy.Value;
#endregion
/// <summary>
/// Initializes the Helper class.
/// </summary>
private Helper()
{
_commandInfoCacheLazy = new Lazy<CommandInfoCache>(() => new CommandInfoCache());
}
/// <summary>
/// Initializes the Helper class.
/// </summary>
/// <param name="invokeCommand">
/// A CommandInvocationIntrinsics instance for use in gathering
/// information about available commands and aliases.
/// </param>
public Helper(
CommandInvocationIntrinsics invokeCommand
): this()
{
this.invokeCommand = invokeCommand;
}
#region Methods
/// <summary>
/// Initialize : Initializes dictionary of alias.
/// </summary>
public void Initialize()
{
CmdletToAliasDictionary = new Dictionary<String, List<String>>(StringComparer.OrdinalIgnoreCase);
AliasToCmdletDictionary = new Dictionary<String, String>(StringComparer.OrdinalIgnoreCase);
KeywordBlockDictionary = new Dictionary<String, List<Tuple<int, int>>>(StringComparer.OrdinalIgnoreCase);
VariableAnalysisDictionary = new Dictionary<Ast, VariableAnalysis>();
ruleArguments = new Dictionary<string, Dictionary<string, object>>(StringComparer.OrdinalIgnoreCase);
IEnumerable<CommandInfo> aliases = this.invokeCommand.GetCommands("*", CommandTypes.Alias, true);
foreach (AliasInfo aliasInfo in aliases)
{
if (!CmdletToAliasDictionary.ContainsKey(aliasInfo.Definition))
{
CmdletToAliasDictionary.Add(aliasInfo.Definition, new List<String>() { aliasInfo.Name });
}
else
{
CmdletToAliasDictionary[aliasInfo.Definition].Add(aliasInfo.Name);
}
AliasToCmdletDictionary.Add(aliasInfo.Name, aliasInfo.Definition);
}
}
/// <summary>
/// Returns all the rule arguments
/// </summary>
/// <returns>Dictionary that maps between rule name to their named arguments</returns>
public Dictionary<string, Dictionary<string, object>> GetRuleArguments()
{
return ruleArguments;
}
/// <summary>
/// Get the parameters corresponding to the given rule name
/// </summary>
/// <param name="ruleName"></param>
/// <returns>Dictionary of argument names mapped to values. If ruleName is not a valid key, returns null</returns>
public Dictionary<string, object> GetRuleArguments(string ruleName)
{
if (ruleArguments.ContainsKey(ruleName))
{
return ruleArguments[ruleName];
}
return null;
}
/// <summary>
/// Sets the arguments for consumption by rules
/// </summary>
/// <param name="ruleArgs">A hashtable with rule names as keys</param>
public void SetRuleArguments(Dictionary<string, object> ruleArgs)
{
if (ruleArgs == null)
{
return;
}
if (ruleArgs.Comparer != StringComparer.OrdinalIgnoreCase)
{
throw new ArgumentException(
"Input dictionary should have OrdinalIgnoreCase comparer.",
"ruleArgs");
}
var ruleArgsDict = new Dictionary<string, Dictionary<string, object>>();
foreach (var rule in ruleArgs.Keys)
{
var argsDict = ruleArgs[rule] as Dictionary<string, object>;
if (argsDict == null)
{
return;
}
ruleArgsDict[rule] = argsDict;
}
ruleArguments = ruleArgsDict;
}
/// <summary>
/// Given a cmdlet, return the list of all the aliases.
/// Also include the original name in the list.
/// </summary>
/// <param name="Cmdlet">Name of the cmdlet</param>
/// <returns></returns>
public List<String> CmdletNameAndAliases(String Cmdlet)
{
List<String> results = new List<String>();
results.Add(Cmdlet);
if (CmdletToAliasDictionary.ContainsKey(Cmdlet))
{
results.AddRange(CmdletToAliasDictionary[Cmdlet]);
}
return results;
}
/// <summary>
/// Given an alias, returns the cmdlet.
/// </summary>
/// <param name="Alias"></param>
/// <returns></returns>
public string GetCmdletNameFromAlias(String Alias)
{
if (AliasToCmdletDictionary.ContainsKey(Alias))
{
return AliasToCmdletDictionary[Alias];
}
return String.Empty;
}
/// <summary>
/// Given a file path, checks whether the file is part of a dsc resource module
/// </summary>
/// <param name="fileName"></param>
/// <returns></returns>
public bool IsDscResourceModule(string filePath)
{
DirectoryInfo dscResourceParent = Directory.GetParent(filePath);
if (null != dscResourceParent)
{
DirectoryInfo dscResourcesFolder = Directory.GetParent(dscResourceParent.ToString());
if (null != dscResourcesFolder)
{
if (String.Equals(dscResourcesFolder.Name, "dscresources", StringComparison.OrdinalIgnoreCase))
{
// Step 2: Ensure there is a Schema.mof in the same folder as the artifact
string schemaMofParentFolder = Directory.GetParent(filePath).ToString();
string[] schemaMofFile = Directory.GetFiles(schemaMofParentFolder, "*.schema.mof");
// Ensure Schema file exists and is the only one in the DSCResource folder
if (schemaMofFile != null && schemaMofFile.Count() == 1)
{
// Run DSC Rules only on module that matches the schema.mof file name without extension
if (String.Equals(schemaMofFile[0].Replace("schema.mof", "psm1"), filePath, StringComparison.OrdinalIgnoreCase))
{
return true;
}
}
}
}
}
return false;
}
/// <summary>
/// Gets the module manifest
/// </summary>
/// <param name="filePath"></param>
/// <param name="errorRecord"></param>
/// <returns>Returns a object of type PSModuleInfo</returns>
public PSModuleInfo GetModuleManifest(string filePath, out IEnumerable<ErrorRecord> errorRecord)
{
errorRecord = null;
PSModuleInfo psModuleInfo = null;
Collection<PSObject> psObj = null;
// Test-ModuleManifest is not thread safe
lock (_testModuleManifestLock)
{
using (var ps = System.Management.Automation.PowerShell.Create())
{
ps.AddCommand("Test-ModuleManifest")
.AddParameter("Path", filePath)
.AddParameter("WarningAction", ActionPreference.SilentlyContinue);
try
{
psObj = ps.Invoke();
}
catch (CmdletInvocationException e)
{
// Invoking Test-ModuleManifest on a module manifest that doesn't have all the valid keys
// throws a NullReferenceException. This is probably a bug in Test-ModuleManifest and hence
// we consume it to allow execution of the of this method.
if (e.InnerException == null || e.InnerException.GetType() != typeof(System.NullReferenceException))
{
throw;
}
}
if (ps.HadErrors && ps.Streams != null && ps.Streams.Error != null)
{
var errorRecordArr = new ErrorRecord[ps.Streams.Error.Count];
ps.Streams.Error.CopyTo(errorRecordArr, 0);
errorRecord = errorRecordArr;
}
if (psObj != null && psObj.Any() && psObj[0] != null)
{
psModuleInfo = psObj[0].ImmediateBaseObject as PSModuleInfo;
}
}
}
return psModuleInfo;
}
/// <summary>
/// Checks if the error record is MissingMemberException
/// </summary>
/// <param name="errorRecord"></param>
/// <returns>Returns a boolean value indicating the presence of MissingMemberException</returns>
public static bool IsMissingManifestMemberException(ErrorRecord errorRecord)
{
return errorRecord.CategoryInfo != null
&& errorRecord.CategoryInfo.Category == ErrorCategory.ResourceUnavailable
&& string.Equals("MissingMemberException", errorRecord.CategoryInfo.Reason, StringComparison.OrdinalIgnoreCase);
}
public IEnumerable<string> GetStringsFromExpressionAst(ExpressionAst exprAst)
{
if (exprAst == null)
{
throw new ArgumentNullException("exprAst");
}
var result = new List<string>();
if (exprAst is StringConstantExpressionAst)
{
result.Add((exprAst as StringConstantExpressionAst).Value);
}
// Array of the form "v-n", "v-n1"
else if (exprAst is ArrayLiteralAst)
{
result.AddRange(Helper.Instance.GetStringsFromArrayLiteral(exprAst as ArrayLiteralAst));
}
// Array of the form @("v-n", "v-n1")
else if (exprAst is ArrayExpressionAst)
{
ArrayExpressionAst arrExAst = exprAst as ArrayExpressionAst;
if (arrExAst.SubExpression != null && arrExAst.SubExpression.Statements != null)
{
foreach (StatementAst stAst in arrExAst.SubExpression.Statements)
{
if (stAst is PipelineAst)
{
PipelineAst pipeAst = stAst as PipelineAst;
if (pipeAst.PipelineElements != null)
{
foreach (CommandBaseAst cmdBaseAst in pipeAst.PipelineElements)
{
if (cmdBaseAst is CommandExpressionAst)
{
result.AddRange(Helper.Instance.GetStringsFromArrayLiteral((cmdBaseAst as CommandExpressionAst).Expression as ArrayLiteralAst));
}
}
}
}
}
}
}
return result;
}
/// <summary>
/// Get the list of exported function by analyzing the ast
/// </summary>
/// <param name="ast"></param>
/// <returns></returns>
public HashSet<string> GetExportedFunction(Ast ast)
{
HashSet<string> exportedFunctions = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
List<string> exportFunctionsCmdlet = Helper.Instance.CmdletNameAndAliases("export-modulemember");
// find functions exported
IEnumerable<Ast> cmdAsts = ast.FindAll(item => item is CommandAst
&& exportFunctionsCmdlet.Contains((item as CommandAst).GetCommandName(), StringComparer.OrdinalIgnoreCase), true);
CommandInfo exportMM = Helper.Instance.GetCommandInfo("export-modulemember", CommandTypes.Cmdlet);
// switch parameters
IEnumerable<ParameterMetadata> switchParams = (exportMM != null) ? exportMM.Parameters.Values.Where<ParameterMetadata>(pm => pm.SwitchParameter) : Enumerable.Empty<ParameterMetadata>();
if (exportMM == null)
{
return exportedFunctions;
}
foreach (CommandAst cmdAst in cmdAsts)
{
if (cmdAst.CommandElements == null || cmdAst.CommandElements.Count < 2)
{
continue;
}
int i = 1;
while (i < cmdAst.CommandElements.Count)
{
CommandElementAst ceAst = cmdAst.CommandElements[i];
ExpressionAst exprAst = null;
if (ceAst is CommandParameterAst)
{
var paramAst = ceAst as CommandParameterAst;
var param = exportMM.ResolveParameter(paramAst.ParameterName);
if (param == null)
{
i += 1;
continue;
}
if (string.Equals(param.Name, "function", StringComparison.OrdinalIgnoreCase))
{
// checks for the case of -Function:"verb-nouns"
if (paramAst.Argument != null)
{
exprAst = paramAst.Argument;
}
// checks for the case of -Function "verb-nouns"
else if (i < cmdAst.CommandElements.Count - 1)
{
i += 1;
exprAst = cmdAst.CommandElements[i] as ExpressionAst;
}
}
// some other parameter. we just checks whether the one after this is positional
else if (i < cmdAst.CommandElements.Count - 1)
{
// the next element is a parameter like -module so just move to that one
if (cmdAst.CommandElements[i + 1] is CommandParameterAst)
{
i += 1;
continue;
}
// not a switch parameter so the next element is definitely the argument to this parameter
if (paramAst.Argument == null && !switchParams.Contains(param))
{
// skips the next element
i += 1;
}
i += 1;
continue;
}
}
else if (ceAst is ExpressionAst)
{
exprAst = ceAst as ExpressionAst;
}
if (exprAst != null)
{
exportedFunctions.UnionWith(Helper.Instance.GetStringsFromExpressionAst(exprAst));
}
i += 1;
}
}
return exportedFunctions;
}
/// <summary>
/// Given a filePath. Returns true if it is a powershell help file
/// </summary>
/// <param name="filePath"></param>
/// <returns></returns>
public bool IsHelpFile(string filePath)
{
return filePath != null && File.Exists(filePath) && Path.GetFileName(filePath).StartsWith("about_", StringComparison.OrdinalIgnoreCase)
&& Path.GetFileName(filePath).EndsWith(".help.txt", StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Given an AST, checks whether dsc resource is class based or not
/// </summary>
/// <param name="ast"></param>
/// <returns></returns>
public bool IsDscResourceClassBased(ScriptBlockAst ast)
{
if (null == ast)
{
return false;
}
#if !(PSV3||PSV4)
List<string> dscResourceFunctionNames = new List<string>(new string[] { "Test", "Get", "Set" });
IEnumerable<Ast> dscClasses = ast.FindAll(item =>
item is TypeDefinitionAst
&& ((item as TypeDefinitionAst).IsClass)
&& (item as TypeDefinitionAst).Attributes.Any(attr => String.Equals("DSCResource", attr.TypeName.FullName, StringComparison.OrdinalIgnoreCase)), true);
// Found one or more classes marked with DscResource attribute
// So this might be a DscResource. Further validation will be performed by the individual rules
if (null != dscClasses && 0 < dscClasses.Count())
{
return true;
}
#endif
return false;
}
private string NameWithoutScope(string name, string[] scopes)
{
if (String.IsNullOrWhiteSpace(name) || scopes == null)
{
return name;
}
// checks whether function name starts with scope
foreach (string scope in scopes)
{
// trim the scope part
if (name.IndexOf(scope, StringComparison.OrdinalIgnoreCase) == 0)
{
return name.Substring(scope.Length);
}
}
// no scope
return name;
}
/// <summary>
/// Given a function name, strip the scope of the name
/// </summary>
/// <param name="functionName"></param>
/// <returns></returns>
public string FunctionNameWithoutScope(string functionName)
{
return NameWithoutScope(functionName, functionScopes);
}
/// <summary>
/// Given a variable name, strip the scope
/// </summary>
/// <param name="variableName"></param>
/// <returns></returns>
public string VariableNameWithoutScope(VariablePath variablePath)
{
if (variablePath == null || variablePath.UserPath == null)
{
return null;
}
// strip out the drive if there is one
if (!string.IsNullOrWhiteSpace(variablePath.DriveName)
// checks that variable starts with drivename:
&& variablePath.UserPath.IndexOf(string.Concat(variablePath.DriveName, ":")) == 0)
{
return variablePath.UserPath.Substring(variablePath.DriveName.Length + 1);
}
return NameWithoutScope(variablePath.UserPath, variableScopes);
}
/// <summary>
/// Given a commandast, checks whether it uses splatted variable
/// </summary>
/// <param name="cmdAst"></param>
/// <returns></returns>
public bool HasSplattedVariable(CommandAst cmdAst)
{
return cmdAst != null
&& cmdAst.CommandElements != null
&& cmdAst.CommandElements.Any(cmdElem =>
{
var varExprAst = cmdElem as VariableExpressionAst;
return varExprAst != null && varExprAst.Splatted;
});
}
/// <summary>
/// Given a commandast, checks if the command is a known cmdlet, function or ExternalScript.
/// </summary>
/// <param name="cmdAst"></param>
/// <returns></returns>
public bool IsKnownCmdletFunctionOrExternalScript(CommandAst cmdAst)
{
if (cmdAst == null)
{
return false;
}
var commandInfo = GetCommandInfo(cmdAst.GetCommandName());
if (commandInfo == null)
{
return false;
}
return commandInfo.CommandType == CommandTypes.Cmdlet ||
commandInfo.CommandType == CommandTypes.Alias ||
commandInfo.CommandType == CommandTypes.ExternalScript;
}
/// <summary>
/// Given a commandast, checks whether positional parameters are used or not.
/// </summary>
/// <param name="cmdAst"></param>
/// <param name="moreThanTwoPositional">only return true if more than two positional parameters are used</param>
/// <returns></returns>
public bool PositionalParameterUsed(CommandAst cmdAst, bool moreThanTwoPositional = false)
{
if (HasSplattedVariable(cmdAst))
{
return false;
}
// Because of the way we count, we will also count the cmdlet as an argument so we have to -1
int argumentsWithoutProcedingParameters = 0;
var commandElementCollection = cmdAst.CommandElements;
for (int i = 1; i < commandElementCollection.Count(); i++) {
if (!(commandElementCollection[i] is CommandParameterAst) && !(commandElementCollection[i-1] is CommandParameterAst))
{
argumentsWithoutProcedingParameters++;
}
}
// if not the first element in a pipeline, increase the number of arguments by 1
PipelineAst parent = cmdAst.Parent as PipelineAst;
if (parent != null && parent.PipelineElements.Count > 1 && parent.PipelineElements[0] != cmdAst)
{
argumentsWithoutProcedingParameters++;
}
return moreThanTwoPositional ? argumentsWithoutProcedingParameters > 2 : argumentsWithoutProcedingParameters > 0;
}
/// <summary>
/// Given a command's name, checks whether it exists.
/// </summary>
/// <param name="name"></param>
/// <param name="commandType"></param>
/// <param name="bypassCache"></param>
/// <returns></returns>
public CommandInfo GetCommandInfo(string name, CommandTypes? commandType = null, bool bypassCache = false)
{
return CommandInfoCache.GetCommandInfo(name, commandTypes: commandType, bypassCache: bypassCache);
}
/// <summary>
/// Returns the get, set and test targetresource dsc function
/// </summary>
/// <param name="ast"></param>
/// <returns></returns>
public IEnumerable<Ast> DscResourceFunctions(Ast ast)
{
List<string> resourceFunctionNames = new List<string>(new string[] { "Set-TargetResource", "Get-TargetResource", "Test-TargetResource" });
return ast.FindAll(item => item is FunctionDefinitionAst
&& resourceFunctionNames.Contains((item as FunctionDefinitionAst).Name, StringComparer.OrdinalIgnoreCase), true);
}
/// <summary>
/// Gets all the strings contained in an array literal ast
/// </summary>
/// <param name="alAst"></param>
/// <returns></returns>
public List<string> GetStringsFromArrayLiteral(ArrayLiteralAst alAst)
{
List<string> result = new List<string>();
if (alAst != null && alAst.Elements != null)
{
foreach (ExpressionAst eAst in alAst.Elements)
{
if (eAst is StringConstantExpressionAst)
{
result.Add((eAst as StringConstantExpressionAst).Value);
}
}
}
return result;
}
/// <summary>
/// Returns true if the block should be skipped as it has a name
/// that matches keyword
/// </summary>
/// <param name="keyword"></param>
/// <param name="namedBlockAst"></param>
/// <returns></returns>
public bool SkipBlock(string keyword, Ast namedBlockAst)
{
if (namedBlockAst == null)
{
return false;
}
FindClosingParenthesis(keyword);
List<Tuple<int, int>> listTuples = KeywordBlockDictionary[keyword];
if (listTuples == null || listTuples.Count == 0)
{
return false;
}
int index = listTuples.BinarySearch(Tuple.Create(namedBlockAst.Extent.StartOffset, namedBlockAst.Extent.EndOffset), tupleComparer);
if (index < 0 || index >= Tokens.Length)
{
return false;
}
Tuple<int, int> braces = listTuples[index];
if (braces.Item2 == namedBlockAst.Extent.EndOffset)
{
return true;
}
return false;
}
// Obtain script extent for the function - just around the function name
public IScriptExtent GetScriptExtentForFunctionName(FunctionDefinitionAst functionDefinitionAst)
{
if (null == functionDefinitionAst)
{
return null;
}
var funcNameTokens = Tokens.Where(
token =>
ContainsExtent(functionDefinitionAst.Extent, token.Extent)
&& token.Text.Equals(functionDefinitionAst.Name));
var funcNameToken = funcNameTokens.FirstOrDefault();
return funcNameToken == null ? null : funcNameToken.Extent;
}
/// <summary>
/// Return true if subset is contained in set
/// </summary>
/// <param name="set"></param>
/// <param name="subset"></param>
/// <returns>True or False</returns>
public static bool ContainsExtent(IScriptExtent set, IScriptExtent subset)
{
if (set == null || subset == null)
{
return false;
}
return set.StartOffset <= subset.StartOffset
&& set.EndOffset >= subset.EndOffset;
}
private void FindClosingParenthesis(string keyword)
{
if (Tokens == null || Tokens.Length == 0)
{
return;
}
// Only do this one time per script. The keywordblockdictionary is cleared everytime we run a new script
if (KeywordBlockDictionary.ContainsKey(keyword))
{
return;
}
KeywordBlockDictionary[keyword] = new List<Tuple<int, int>>();
int[] tokenIndices = Tokens
.Select((token, index) =>
String.Equals(token.Text, keyword, StringComparison.OrdinalIgnoreCase) && (token.TokenFlags == TokenFlags.Keyword || token.TokenFlags == TokenFlags.CommandName)
? index : -1)
.Where(index => index != -1).ToArray();
foreach (int tokenIndex in tokenIndices)
{
int openCurly = -1;
for (int i = tokenIndex; i < Tokens.Length; i += 1)
{
if (Tokens[i] != null && Tokens[i].Kind == TokenKind.LCurly)
{
openCurly = i;
break;
}
}
if (openCurly == -1)
{
continue;
}
int closeCurly = -1;
int count = 1;
for (int i = openCurly + 1; i < Tokens.Length; i += 1)
{
if (Tokens[i] != null)
{
if (Tokens[i].Kind == TokenKind.LCurly)
{
count += 1;
}
else if (Tokens[i].Kind == TokenKind.RCurly)
{
count -= 1;
}
}
if (count == 0)
{
closeCurly = i;
break;
}
}
if (closeCurly == -1)
{
continue;
}
KeywordBlockDictionary[keyword].Add(Tuple.Create(Tokens[openCurly].Extent.StartOffset,
Tokens[closeCurly].Extent.EndOffset));
}
}
/// <summary>
/// Checks whether the variable VarAst is uninitialized.
/// </summary>
/// <param name="varAst"></param>
/// <param name="ast"></param>
/// <returns></returns>
public bool IsUninitialized(VariableExpressionAst varAst, Ast ast)
{
if (!VariableAnalysisDictionary.ContainsKey(ast) || VariableAnalysisDictionary[ast] == null)
{
return false;
}
return VariableAnalysisDictionary[ast].IsUninitialized(varAst);
}
/// <summary>
/// Returns true if varaible is either a global variable or an environment variable
/// </summary>
/// <param name="varAst"></param>
/// <param name="ast"></param>
/// <returns></returns>
public bool IsVariableGlobalOrEnvironment(VariableExpressionAst varAst, Ast ast)
{
if (!VariableAnalysisDictionary.ContainsKey(ast) || VariableAnalysisDictionary[ast] == null)
{
return false;
}
return VariableAnalysisDictionary[ast].IsGlobalOrEnvironment(varAst);
}
/// <summary>
/// Checks whether a variable is a global variable.
/// </summary>
/// <param name="ast"></param>
/// <returns></returns>
public bool IsVariableGlobal(VariableExpressionAst varAst)
{
//We ignore the use of built-in variable as global variable
if (varAst.VariablePath.IsGlobal)
{
string varName = varAst.VariablePath.UserPath.Remove(varAst.VariablePath.UserPath.IndexOf("global:", StringComparison.OrdinalIgnoreCase), "global:".Length);
return !SpecialVars.InitializedVariables.Contains(varName, StringComparer.OrdinalIgnoreCase);
}
return false;
}
/// <summary>
/// Checks whether all the code path of ast returns.
/// Runs InitializeVariableAnalysis before calling this method
/// </summary>
/// <param name="ast"></param>
/// <returns></returns>
public bool AllCodePathReturns(Ast ast)
{
if (!VariableAnalysisDictionary.ContainsKey(ast))
{
return true;
}
var analysis = VariableAnalysisDictionary[ast];
return analysis.Exit._predecessors.All(block => block._returns || block._unreachable || block._throws);
}
/// <summary>
/// Initialize variable analysis on the script ast
/// </summary>
/// <param name="ast"></param>
public void InitializeVariableAnalysis(Ast ast)
{
(new ScriptAnalysis()).AnalyzeScript(ast);
}
/// <summary>
/// Initialize Variable Analysis on Ast ast with variables outside in outerAnalysis
/// </summary>
/// <param name="ast"></param>
internal VariableAnalysis InitializeVariableAnalysisHelper(Ast ast, VariableAnalysis outerAnalysis)
{
var VarAnalysis = new VariableAnalysis(new FlowGraph());
VarAnalysis.AnalyzeImpl(ast, outerAnalysis);
VariableAnalysisDictionary[ast] = VarAnalysis;
return VarAnalysis;
}
/// <summary>
/// Get the return type of ret, which is used in function funcAst in scriptAst ast
/// This function assumes that initialize variable analysis is already run on funcast
/// It also assumes that the pipeline of ret is not null
/// </summary>
/// <param name="funcAst"></param>
/// <param name="ret"></param>
/// <param name="classes"></param>
/// <param name="scriptAst"></param>
/// <returns></returns>
#if (PSV3||PSV4)
public string GetTypeFromReturnStatementAst(Ast funcAst, ReturnStatementAst ret)
#else
public string GetTypeFromReturnStatementAst(Ast funcAst, ReturnStatementAst ret, IEnumerable<TypeDefinitionAst> classes)
#endif
{
if (ret == null || funcAst == null)
{
return String.Empty;
}
PipelineAst pipe = ret.Pipeline as PipelineAst;
String result = String.Empty;
// Handle the case with 1 pipeline element first
if (pipe != null && pipe.PipelineElements.Count == 1)
{
CommandExpressionAst cmAst = pipe.PipelineElements[0] as CommandExpressionAst;
if (cmAst != null)
{
if (cmAst.Expression.StaticType != typeof(object))
{
result = cmAst.Expression.StaticType.FullName;
}
else
{
VariableExpressionAst varAst = cmAst.Expression as VariableExpressionAst;
if (varAst != null)
{
result = GetVariableTypeFromAnalysis(varAst, funcAst);
}
else if (cmAst.Expression is MemberExpressionAst)
{
#if PSV3
result = GetTypeFromMemberExpressionAst(cmAst.Expression as MemberExpressionAst, funcAst);
#else
result = GetTypeFromMemberExpressionAst(cmAst.Expression as MemberExpressionAst, funcAst, classes);