From 256edd72d97c58bd8953b348d4708031f5e7e153 Mon Sep 17 00:00:00 2001 From: vexx32 <32407840+vexx32@users.noreply.github.com> Date: Sun, 26 May 2019 13:54:18 -0400 Subject: [PATCH 1/6] :recycle: Cleanup CompiledScriptBlock.cs --- .../engine/runtime/CompiledScriptBlock.cs | 656 +++++++++++------- 1 file changed, 386 insertions(+), 270 deletions(-) diff --git a/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs b/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs index 36f91298300..339b017b047 100644 --- a/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs +++ b/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs @@ -103,9 +103,9 @@ private void InitializeMetadata() attributes = Ast.GetScriptBlockAttributes().ToArray(); foreach (var attribute in attributes) { - if (attribute is CmdletBindingAttribute) + if (attribute is CmdletBindingAttribute c) { - cmdletBindingAttribute = cmdletBindingAttribute ?? (CmdletBindingAttribute)attribute; + cmdletBindingAttribute = cmdletBindingAttribute ?? c; } else if (attribute is DebuggerHiddenAttribute) { @@ -121,7 +121,8 @@ private void InitializeMetadata() } bool automaticPosition = cmdletBindingAttribute == null || cmdletBindingAttribute.PositionalBinding; - var runtimeDefinedParameterDictionary = Ast.GetParameterMetadata(automaticPosition, ref _usesCmdletBinding); + var runtimeDefinedParameterDictionary = + Ast.GetParameterMetadata(automaticPosition, ref _usesCmdletBinding); // Initialize these fields last - if there were any exceptions, we don't want the partial results cached. _attributes = attributes; @@ -170,7 +171,10 @@ private void ReallyCompile(bool optimize) { var extent = _ast.Body.Extent; var text = extent.Text; - ParserEventSource.Log.CompileStart(ParserEventSource.GetFileOrScript(extent.File, text), text.Length, optimize); + ParserEventSource.Log.CompileStart( + FileName: ParserEventSource.GetFileOrScript(extent.File, text), + text.Length, + optimize); } PerformSecurityChecks(); @@ -199,8 +203,8 @@ private void PerformSecurityChecks() var scriptExtent = scriptBlockAst.Extent; var scriptFile = scriptExtent.File; - if (scriptFile != null && - scriptFile.EndsWith(StringLiterals.PowerShellDataFileExtension, StringComparison.OrdinalIgnoreCase) + if (scriptFile != null + && scriptFile.EndsWith(StringLiterals.PowerShellDataFileExtension, StringComparison.OrdinalIgnoreCase) && IsScriptBlockInFactASafeHashtable()) { // Skip the scan for .psd1 files if their content is in fact a safe HashtableAst. @@ -212,14 +216,19 @@ private void PerformSecurityChecks() if (amsiResult == AmsiUtils.AmsiNativeMethods.AMSI_RESULT.AMSI_RESULT_DETECTED) { - var parseError = new ParseError(scriptExtent, "ScriptContainedMaliciousContent", ParserStrings.ScriptContainedMaliciousContent); + var parseError = new ParseError( + scriptExtent, + "ScriptContainedMaliciousContent", + ParserStrings.ScriptContainedMaliciousContent); throw new ParseException(new[] { parseError }); } - else if ((amsiResult >= AmsiUtils.AmsiNativeMethods.AMSI_RESULT.AMSI_RESULT_BLOCKED_BY_ADMIN_BEGIN) && - (amsiResult <= AmsiUtils.AmsiNativeMethods.AMSI_RESULT.AMSI_RESULT_BLOCKED_BY_ADMIN_END)) + else if (amsiResult >= AmsiUtils.AmsiNativeMethods.AMSI_RESULT.AMSI_RESULT_BLOCKED_BY_ADMIN_BEGIN + && amsiResult <= AmsiUtils.AmsiNativeMethods.AMSI_RESULT.AMSI_RESULT_BLOCKED_BY_ADMIN_END) { // Certain policies set by an administrator blocked this content on this machine - var parseError = new ParseError(scriptExtent, "ScriptHasAdminBlockedContent", + var parseError = new ParseError( + scriptExtent, + "ScriptHasAdminBlockedContent", StringUtil.Format(ParserStrings.ScriptHasAdminBlockedContent, amsiResult)); throw new ParseException(new[] { parseError }); } @@ -237,10 +246,13 @@ bool IsScriptBlockInFactASafeHashtable() // are enhanced, such as new members added to 'ScriptBlockAst', the code here needs // to be reviewed and changed accordingly. - if (scriptBlockAst.BeginBlock != null || scriptBlockAst.ProcessBlock != null || - scriptBlockAst.ParamBlock != null || scriptBlockAst.DynamicParamBlock != null || - scriptBlockAst.ScriptRequirements != null || scriptBlockAst.UsingStatements.Count > 0 || - scriptBlockAst.Attributes.Count > 0) + if (scriptBlockAst.BeginBlock != null + || scriptBlockAst.ProcessBlock != null + || scriptBlockAst.ParamBlock != null + || scriptBlockAst.DynamicParamBlock != null + || scriptBlockAst.ScriptRequirements != null + || scriptBlockAst.UsingStatements.Count > 0 + || scriptBlockAst.Attributes.Count > 0) { return false; } @@ -271,7 +283,7 @@ bool IsScriptBlockInFactASafeHashtable() // We delay parsing scripts loaded on startup, so we save the text. private string _scriptText; - internal IParameterMetadataProvider Ast { get { return _ast ?? DelayParseScriptText(); } } + internal IParameterMetadataProvider Ast { get => _ast ?? DelayParseScriptText(); } private IParameterMetadataProvider _ast; @@ -280,7 +292,9 @@ private IParameterMetadataProvider DelayParseScriptText() lock (this) { if (_ast != null) + { return _ast; + } ParseError[] errors; _ast = (new Parser()).Parse(null, _scriptText, null, out errors, ParseMode.Default); @@ -351,11 +365,13 @@ internal bool HasSuspiciousContent { get { - Diagnostics.Assert(_compiledOptimized || _compiledUnoptimized, "HasSuspiciousContent is not set correctly before being compiled"); + Diagnostics.Assert( + _compiledOptimized || _compiledUnoptimized, + "HasSuspiciousContent is not set correctly before being compiled"); return _hasSuspiciousContent; } - set { _hasSuspiciousContent = value; } + set => _hasSuspiciousContent = value; } private MergedCommandParameterMetadata _parameterMetadata; @@ -367,7 +383,9 @@ internal List GetAttributes() InitializeMetadata(); } - Diagnostics.Assert(_attributes != null, "after initialization, attributes is never null, must be an empty list if no attributes."); + Diagnostics.Assert( + _attributes != null, + "after initialization, attributes is never null, must be an empty list if no attributes."); return _attributes.ToList(); } @@ -406,7 +424,9 @@ internal CmdletBindingAttribute CmdletBindingAttribute InitializeMetadata(); } - return _usesCmdletBinding ? (CmdletBindingAttribute)_attributes.FirstOrDefault(attr => attr is CmdletBindingAttribute) : null; + return _usesCmdletBinding + ? (CmdletBindingAttribute)_attributes.FirstOrDefault(attr => attr is CmdletBindingAttribute) + : null; } } @@ -452,7 +472,10 @@ public MergedCommandParameterMetadata GetParameterMetadata(ScriptBlock scriptBlo { if (_parameterMetadata == null) { - CommandMetadata metadata = new CommandMetadata(scriptBlock, string.Empty, LocalPipeline.GetExecutionContextFromTLS()); + CommandMetadata metadata = new CommandMetadata( + scriptBlock, + string.Empty, + LocalPipeline.GetExecutionContextFromTLS()); _parameterMetadata = metadata.StaticCommandParameterMetadata; } } @@ -468,8 +491,7 @@ public override string ToString() return _scriptText; } - var sbAst = _ast as ScriptBlockAst; - if (sbAst != null) + if (_ast is ScriptBlockAst sbAst) { return sbAst.ToStringForSerialization(); } @@ -544,8 +566,9 @@ internal static ScriptBlock TryGetCachedScriptBlock(string fileName, string file var key = Tuple.Create(fileName, fileContents); if (s_cachedScripts.TryGetValue(key, out scriptBlock)) { - Diagnostics.Assert(scriptBlock.SessionStateInternal == null, - "A cached scriptblock should not have it's session state bound, that causes a memory leak."); + Diagnostics.Assert( + scriptBlock.SessionStateInternal == null, + "A cached scriptblock should not have it's session state bound, that causes a memory leak."); return scriptBlock.Clone(); } @@ -555,13 +578,13 @@ internal static ScriptBlock TryGetCachedScriptBlock(string fileName, string file private static bool IsDynamicKeyword(Ast ast) { var cmdAst = ast as CommandAst; - return (cmdAst != null && cmdAst.DefiningKeyword != null); + return cmdAst?.DefiningKeyword != null; } private static bool IsUsingTypes(Ast ast) { var cmdAst = ast as UsingStatementAst; - return (cmdAst != null && cmdAst.IsUsingModuleOrAssembly()); + return cmdAst?.IsUsingModuleOrAssembly() == true; } internal static void CacheScriptBlock(ScriptBlock scriptBlock, string fileName, string fileContents) @@ -571,25 +594,23 @@ internal static void CacheScriptBlock(ScriptBlock scriptBlock, string fileName, return; } - // // Don't cache scriptblocks that have // a) dynamic keywords // b) 'using module' or 'using assembly' // The definition of the dynamic keyword could change, consequently changing how the source text should be parsed. // Exported types definitions from 'using module' could change, we need to do all parse-time checks again. // TODO(sevoroby): we can optimize it to ignore 'using' if there are no actual type usage in locally defined types. - // // using is always a top-level statements in scriptBlock, we don't need to search in child blocks. - if (scriptBlock.Ast.Find(ast => IsUsingTypes(ast), false) != null || - scriptBlock.Ast.Find(ast => IsDynamicKeyword(ast), true) != null) + if (scriptBlock.Ast.Find(ast => IsUsingTypes(ast), false) != null + || scriptBlock.Ast.Find(ast => IsDynamicKeyword(ast), true) != null) { return; } if (s_cachedScripts.Count > 1024) { - s_cachedScripts.Clear(); + ClearScriptBlockCache(); } var key = Tuple.Create(fileName, fileContents); @@ -604,7 +625,8 @@ internal static void ClearScriptBlockCache() s_cachedScripts.Clear(); } - internal static ScriptBlock EmptyScriptBlock = ScriptBlock.CreateDelayParsedScriptBlock(string.Empty, isProductCode: true); + internal static ScriptBlock EmptyScriptBlock = + ScriptBlock.CreateDelayParsedScriptBlock(string.Empty, isProductCode: true); internal static ScriptBlock Create(Parser parser, string fileName, string fileContents) { @@ -630,18 +652,12 @@ internal static ScriptBlock Create(Parser parser, string fileName, string fileCo return result.Clone(); } - internal ScriptBlock Clone() - { - return new ScriptBlock(_scriptBlockData); - } + internal ScriptBlock Clone() => new ScriptBlock(_scriptBlockData); /// /// Returns the text of the script block. The return value might not match the original text exactly. /// - public override string ToString() - { - return _scriptBlockData.ToString(); - } + public override string ToString() => _scriptBlockData.ToString(); /// /// Returns the text of the script block with the handling of $using expressions. @@ -685,7 +701,7 @@ public virtual void GetObjectData(SerializationInfo info, StreamingContext conte { if (info == null) { - throw PSTraceSource.NewArgumentNullException("info"); + throw PSTraceSource.NewArgumentNullException(nameof(info)); } string serializedContent = this.ToString(); @@ -693,21 +709,31 @@ public virtual void GetObjectData(SerializationInfo info, StreamingContext conte info.SetType(typeof(ScriptBlockSerializationHelper)); } - internal PowerShell GetPowerShellImpl(ExecutionContext context, Dictionary variables, bool isTrustedInput, - bool filterNonUsingVariables, bool? createLocalScope, params object[] args) - { - return AstInternal.GetPowerShell(context, variables, isTrustedInput, filterNonUsingVariables, createLocalScope, args); - } + internal PowerShell GetPowerShellImpl( + ExecutionContext context, + Dictionary variables, + bool isTrustedInput, + bool filterNonUsingVariables, + bool? createLocalScope, + params object[] args) + => AstInternal.GetPowerShell( + context, + variables, + isTrustedInput, + filterNonUsingVariables, + createLocalScope, + args); + internal SteppablePipeline GetSteppablePipelineImpl(CommandOrigin commandOrigin, object[] args) { - var pipelineAst = GetSimplePipeline(resourceString => { throw PSTraceSource.NewInvalidOperationException(resourceString); }); + var pipelineAst = GetSimplePipeline( + resourceString => { throw PSTraceSource.NewInvalidOperationException(resourceString); }); Diagnostics.Assert(pipelineAst != null, "This should be checked by GetSimplePipeline"); if (!(pipelineAst.PipelineElements[0] is CommandAst)) { - throw PSTraceSource.NewInvalidOperationException( - AutomationExceptions.CantConvertEmptyPipeline); + throw PSTraceSource.NewInvalidOperationException(AutomationExceptions.CantConvertEmptyPipeline); } return PipelineOps.GetSteppablePipeline(pipelineAst, commandOrigin, this, args); @@ -752,59 +778,37 @@ private PipelineAst GetSimplePipeline(Func errorHandler) return pipeAst; } - internal List GetAttributes() - { - return _scriptBlockData.GetAttributes(); - } + internal List GetAttributes() => _scriptBlockData.GetAttributes(); - internal string GetFileName() - { - return AstInternal.Body.Extent.File; - } + internal string GetFileName() => AstInternal.Body.Extent.File; - internal bool IsMetaConfiguration() - { - // GetAttributes() is asserted never return null - return GetAttributes().OfType().Any(); - } + // GetAttributes() is asserted never return null + internal bool IsMetaConfiguration() => GetAttributes().OfType().Any(); - internal PSToken GetStartPosition() - { - return new PSToken(Ast.Extent); - } + internal PSToken GetStartPosition() => new PSToken(Ast.Extent); internal MergedCommandParameterMetadata ParameterMetadata { - get { return _scriptBlockData.GetParameterMetadata(this); } + get => _scriptBlockData.GetParameterMetadata(this); } - internal bool UsesCmdletBinding - { - get { return _scriptBlockData.UsesCmdletBinding; } - } + internal bool UsesCmdletBinding { get => _scriptBlockData.UsesCmdletBinding; } - internal bool HasDynamicParameters - { - get { return AstInternal.Body.DynamicParamBlock != null; } - } + internal bool HasDynamicParameters { get => AstInternal.Body.DynamicParamBlock != null; } /// /// DebuggerHidden. /// public bool DebuggerHidden { - get { return _scriptBlockData.DebuggerHidden; } - - set { _scriptBlockData.DebuggerHidden = value; } + get => _scriptBlockData.DebuggerHidden; + set => _scriptBlockData.DebuggerHidden = value; } /// /// The unique ID of this script block. /// - public Guid Id - { - get { return _scriptBlockData.Id; } - } + public Guid Id { get => _scriptBlockData.Id; } internal bool DebuggerStepThrough { @@ -815,14 +819,13 @@ internal bool DebuggerStepThrough internal RuntimeDefinedParameterDictionary RuntimeDefinedParameters { - get { return _scriptBlockData.RuntimeDefinedParameters; } + get => _scriptBlockData.RuntimeDefinedParameters; } internal bool HasLogged { - get { return _scriptBlockData.HasLogged; } - - set { _scriptBlockData.HasLogged = value; } + get => _scriptBlockData.HasLogged; + set => _scriptBlockData.HasLogged = value; } internal bool SkipLogging @@ -834,16 +837,27 @@ internal bool SkipLogging internal Assembly AssemblyDefiningPSTypes { set; get; } - internal HelpInfo GetHelpInfo(ExecutionContext context, CommandInfo commandInfo, bool dontSearchOnRemoteComputer, - Dictionary scriptBlockTokenCache, out string helpFile, out string helpUriFromDotLink) + internal HelpInfo GetHelpInfo( + ExecutionContext context, + CommandInfo commandInfo, + bool dontSearchOnRemoteComputer, + Dictionary scriptBlockTokenCache, + out string helpFile, + out string helpUriFromDotLink) { helpUriFromDotLink = null; var commentTokens = HelpCommentsParser.GetHelpCommentTokens(AstInternal, scriptBlockTokenCache); if (commentTokens != null) { - return HelpCommentsParser.CreateFromComments(context, commandInfo, commentTokens.Item1, - commentTokens.Item2, dontSearchOnRemoteComputer, out helpFile, out helpUriFromDotLink); + return HelpCommentsParser.CreateFromComments( + context, + commandInfo, + commentTokens.Item1, + commentTokens.Item2, + dontSearchOnRemoteComputer, + out helpFile, + out helpUriFromDotLink); } helpFile = null; @@ -860,7 +874,10 @@ internal HelpInfo GetHelpInfo(ExecutionContext context, CommandInfo commandInfo, /// any variable will be allowed. /// /// The environment variables that are allowed. - public void CheckRestrictedLanguage(IEnumerable allowedCommands, IEnumerable allowedVariables, bool allowEnvironmentVariables) + public void CheckRestrictedLanguage( + IEnumerable allowedCommands, + IEnumerable allowedVariables, + bool allowEnvironmentVariables) { Parser parser = new Parser(); @@ -868,16 +885,25 @@ public void CheckRestrictedLanguage(IEnumerable allowedCommands, IEnumer if (HasBeginBlock || HasProcessBlock || ast.Body.ParamBlock != null) { Ast errorAst = ast.Body.BeginBlock ?? (Ast)ast.Body.ProcessBlock ?? ast.Body.ParamBlock; - parser.ReportError(errorAst.Extent, + parser.ReportError( + errorAst.Extent, nameof(ParserStrings.InvalidScriptBlockInDataSection), ParserStrings.InvalidScriptBlockInDataSection); } if (HasEndBlock) { - RestrictedLanguageChecker rlc = new RestrictedLanguageChecker(parser, allowedCommands, allowedVariables, allowEnvironmentVariables); - var endBlock = ast.Body.EndBlock; - StatementBlockAst.InternalVisit(rlc, endBlock.Traps, endBlock.Statements, AstVisitAction.Continue); + var rlc = new RestrictedLanguageChecker( + parser, + allowedCommands, + allowedVariables, + allowEnvironmentVariables); + + StatementBlockAst.InternalVisit( + rlc, + ast.Body.EndBlock.Traps, + ast.Body.EndBlock.Statements, + AstVisitAction.Continue); } if (parser.ErrorList.Any()) @@ -886,10 +912,7 @@ public void CheckRestrictedLanguage(IEnumerable allowedCommands, IEnumer } } - internal string GetWithInputHandlingForInvokeCommand() - { - return AstInternal.GetWithInputHandlingForInvokeCommand(); - } + internal string GetWithInputHandlingForInvokeCommand() => AstInternal.GetWithInputHandlingForInvokeCommand(); internal string GetWithInputHandlingForInvokeCommandWithUsingExpression( Tuple, string> usingVariablesTuple) @@ -898,67 +921,59 @@ internal string GetWithInputHandlingForInvokeCommandWithUsingExpression( AstInternal.GetWithInputHandlingForInvokeCommandWithUsingExpression(usingVariablesTuple); // result.Item1 is ParamText; result.Item2 is ScriptBlockText - if (result.Item1 == null) - return result.Item2; - return result.Item1 + result.Item2; - } - - internal bool IsUsingDollarInput() - { - return AstSearcher.IsUsingDollarInput(this.Ast); - } - - internal void InvokeWithPipeImpl(bool createLocalScope, - Dictionary functionsToDefine, - List variablesToDefine, - ErrorHandlingBehavior errorHandlingBehavior, - object dollarUnder, - object input, - object scriptThis, - Pipe outputPipe, - InvocationInfo invocationInfo, - params object[] args) - { - InvokeWithPipeImpl(ScriptBlockClauseToInvoke.ProcessBlockOnly, createLocalScope, - functionsToDefine, - variablesToDefine, - errorHandlingBehavior, - dollarUnder, - input, - scriptThis, - outputPipe, - invocationInfo, - args); - } - - internal void InvokeWithPipeImpl(ScriptBlockClauseToInvoke clauseToInvoke, - bool createLocalScope, - Dictionary functionsToDefine, - List variablesToDefine, - ErrorHandlingBehavior errorHandlingBehavior, - object dollarUnder, - object input, - object scriptThis, - Pipe outputPipe, - InvocationInfo invocationInfo, - params object[] args) - { - if (clauseToInvoke == ScriptBlockClauseToInvoke.Begin && !HasBeginBlock) - { - return; - } - else if (clauseToInvoke == ScriptBlockClauseToInvoke.Process && !HasProcessBlock) - { - return; - } - else if (clauseToInvoke == ScriptBlockClauseToInvoke.End && !HasEndBlock) + return result.Item1 == null ? result.Item2 : result.Item1 + result.Item2; + } + + internal bool IsUsingDollarInput() => AstSearcher.IsUsingDollarInput(this.Ast); + + internal void InvokeWithPipeImpl( + bool createLocalScope, + Dictionary functionsToDefine, + List variablesToDefine, + ErrorHandlingBehavior errorHandlingBehavior, + object dollarUnder, + object input, + object scriptThis, + Pipe outputPipe, + InvocationInfo invocationInfo, + params object[] args) + => InvokeWithPipeImpl( + clauseToInvoke: ScriptBlockClauseToInvoke.ProcessBlockOnly, + createLocalScope, + functionsToDefine, + variablesToDefine, + errorHandlingBehavior, + dollarUnder, + input, + scriptThis, + outputPipe, + invocationInfo, + args); + + internal void InvokeWithPipeImpl( + ScriptBlockClauseToInvoke clauseToInvoke, + bool createLocalScope, + Dictionary functionsToDefine, + List variablesToDefine, + ErrorHandlingBehavior errorHandlingBehavior, + object dollarUnder, + object input, + object scriptThis, + Pipe outputPipe, + InvocationInfo invocationInfo, + params object[] args) + { + if ((clauseToInvoke == ScriptBlockClauseToInvoke.Begin && !HasBeginBlock) + || (clauseToInvoke == ScriptBlockClauseToInvoke.Process && !HasProcessBlock) + || (clauseToInvoke == ScriptBlockClauseToInvoke.End && !HasEndBlock)) { return; } ExecutionContext context = GetContextFromTLS(); - Diagnostics.Assert(SessionStateInternal == null || SessionStateInternal.ExecutionContext == context, - "The scriptblock is being invoked in a runspace different than the one where it was created"); + Diagnostics.Assert( + SessionStateInternal == null || SessionStateInternal.ExecutionContext == context, + "The scriptblock is being invoked in a runspace different than the one where it was created"); if (context.CurrentPipelineStopping) { @@ -966,8 +981,12 @@ internal void InvokeWithPipeImpl(ScriptBlockClauseToInvoke clauseToInvoke, } // Validate at the arguments are consistent. The only public API that gets you here never sets createLocalScope to false... - Diagnostics.Assert(createLocalScope == true || functionsToDefine == null, "When calling ScriptBlock.InvokeWithContext(), if 'functionsToDefine' != null then 'createLocalScope' must be true"); - Diagnostics.Assert(createLocalScope == true || variablesToDefine == null, "When calling ScriptBlock.InvokeWithContext(), if 'variablesToDefine' != null then 'createLocalScope' must be true"); + Diagnostics.Assert( + createLocalScope == true || functionsToDefine == null, + "When calling ScriptBlock.InvokeWithContext(), if 'functionsToDefine' != null then 'createLocalScope' must be true"); + Diagnostics.Assert( + createLocalScope == true || variablesToDefine == null, + "When calling ScriptBlock.InvokeWithContext(), if 'variablesToDefine' != null then 'createLocalScope' must be true"); if (args == null) { @@ -977,7 +996,9 @@ internal void InvokeWithPipeImpl(ScriptBlockClauseToInvoke clauseToInvoke, bool runOptimized = context._debuggingMode > 0 ? false : createLocalScope; var codeToInvoke = GetCodeToInvoke(ref runOptimized, clauseToInvoke); if (codeToInvoke == null) + { return; + } if (outputPipe == null) { @@ -1013,14 +1034,14 @@ internal void InvokeWithPipeImpl(ScriptBlockClauseToInvoke clauseToInvoke, // change the language mode. PSLanguageMode? oldLanguageMode = null; PSLanguageMode? newLanguageMode = null; - if ((this.LanguageMode.HasValue) && - (this.LanguageMode != context.LanguageMode)) + if (this.LanguageMode.HasValue + && this.LanguageMode != context.LanguageMode) { // Don't allow context: ConstrainedLanguage -> FullLanguage transition if // this is dot sourcing into the current scope, unless it is within a trusted module scope. - if (this.LanguageMode != PSLanguageMode.FullLanguage || - createLocalScope || - (context.EngineSessionState.Module?.LanguageMode == PSLanguageMode.FullLanguage)) + if (this.LanguageMode != PSLanguageMode.FullLanguage + || createLocalScope + || context.EngineSessionState.Module?.LanguageMode == PSLanguageMode.FullLanguage) { oldLanguageMode = context.LanguageMode; newLanguageMode = this.LanguageMode; @@ -1043,7 +1064,9 @@ internal void InvokeWithPipeImpl(ScriptBlockClauseToInvoke clauseToInvoke, locals.SetAutomaticVariable(AutomaticVariable.MyInvocation, myInvocationInfo, context); if (SessionStateInternal != null) + { context.EngineSessionState = SessionStateInternal; + } // If we don't want errors written, hide the error pipe. switch (errorHandlingBehavior) @@ -1108,7 +1131,10 @@ internal void InvokeWithPipeImpl(ScriptBlockClauseToInvoke clauseToInvoke, } string name = psvar.Name; - Diagnostics.Assert(!(string.Equals(name, "this") || string.Equals(name, "_") || string.Equals(name, "input")), + Diagnostics.Assert( + !(string.Equals(name, "this") + || string.Equals(name, "_") + || string.Equals(name, "input")), "The list of variables to set in the scriptblock's scope cannot contain 'this', '_' or 'input'. These variables should be removed before passing the collection to this routine."); index++; newScope.Variables.Add(name, psvar); @@ -1139,7 +1165,11 @@ internal void InvokeWithPipeImpl(ScriptBlockClauseToInvoke clauseToInvoke, args = BindArgumentsForScriptblockInvoke( (RuntimeDefinedParameter[])RuntimeDefinedParameters.Data, - args, context, !createLocalScope, backupWhenDotting, locals); + args, + context, + !createLocalScope, + backupWhenDotting, + locals); locals.SetAutomaticVariable(AutomaticVariable.Args, args, context); context.EngineSessionState.CurrentScope.ScopeOrigin = CommandOrigin.Internal; @@ -1219,11 +1249,15 @@ internal MutableTuple MakeLocalsTuple(bool createLocalScope) MutableTuple locals; if (createLocalScope) { - locals = MutableTuple.MakeTuple(_scriptBlockData.LocalsMutableTupleType, _scriptBlockData.NameToIndexMap, _scriptBlockData.LocalsMutableTupleCreator); + locals = MutableTuple.MakeTuple( + _scriptBlockData.LocalsMutableTupleType, + _scriptBlockData.NameToIndexMap, + _scriptBlockData.LocalsMutableTupleCreator); } else { - locals = MutableTuple.MakeTuple(_scriptBlockData.UnoptimizedLocalsMutableTupleType, + locals = MutableTuple.MakeTuple( + _scriptBlockData.UnoptimizedLocalsMutableTupleType, UsesCmdletBinding ? Compiler.DottedScriptCmdletLocalsNameIndexMap : Compiler.DottedLocalsNameIndexMap, @@ -1272,7 +1306,8 @@ internal static object[] BindArgumentsForScriptblockInvoke( bool valueSet = false; if (dotting && backupWhenDotting != null) { - backupWhenDotting[parameter.Name] = context.EngineSessionState.GetVariableAtScope(parameter.Name, "local"); + backupWhenDotting[parameter.Name] = + context.EngineSessionState.GetVariableAtScope(parameter.Name, "local"); } else { @@ -1281,7 +1316,11 @@ internal static object[] BindArgumentsForScriptblockInvoke( if (!valueSet) { - var variable = new PSVariable(parameter.Name, valueToBind, ScopedItemOptions.None, parameter.Attributes); + var variable = new PSVariable( + parameter.Name, + valueToBind, + ScopedItemOptions.None, + parameter.Attributes); context.EngineSessionState.SetVariable(variable, false, CommandOrigin.Internal); } @@ -1292,7 +1331,10 @@ internal static object[] BindArgumentsForScriptblockInvoke( } } - locals.SetAutomaticVariable(AutomaticVariable.PSBoundParameters, boundParameters.GetValueToBindToPSBoundParameters(), context); + locals.SetAutomaticVariable( + AutomaticVariable.PSBoundParameters, + boundParameters.GetValueToBindToPSBoundParameters(), + context); var leftOverArgs = args.Length - parameters.Length; if (leftOverArgs <= 0) @@ -1306,13 +1348,12 @@ internal static object[] BindArgumentsForScriptblockInvoke( } internal static void SetAutomaticVariable(AutomaticVariable variable, object value, MutableTuple locals) - { - locals.SetValue((int)variable, value); - } + => locals.SetValue((int)variable, value); private Action GetCodeToInvoke(ref bool optimized, ScriptBlockClauseToInvoke clauseToInvoke) { - if (clauseToInvoke == ScriptBlockClauseToInvoke.ProcessBlockOnly && (HasBeginBlock || (HasEndBlock && HasProcessBlock))) + if (clauseToInvoke == ScriptBlockClauseToInvoke.ProcessBlockOnly + && (HasBeginBlock || (HasEndBlock && HasProcessBlock))) { throw PSTraceSource.NewInvalidOperationException(AutomationExceptions.ScriptBlockInvokeOnOneClauseOnly); } @@ -1347,25 +1388,13 @@ private Action GetCodeToInvoke(ref bool optimized, ScriptBlockC } } - internal CmdletBindingAttribute CmdletBindingAttribute - { - get { return _scriptBlockData.CmdletBindingAttribute; } - } + internal CmdletBindingAttribute CmdletBindingAttribute { get => _scriptBlockData.CmdletBindingAttribute; } - internal ObsoleteAttribute ObsoleteAttribute - { - get { return _scriptBlockData.ObsoleteAttribute; } - } + internal ObsoleteAttribute ObsoleteAttribute { get => _scriptBlockData.ObsoleteAttribute; } - internal ExperimentalAttribute ExperimentalAttribute - { - get { return _scriptBlockData.ExperimentalAttribute; } - } + internal ExperimentalAttribute ExperimentalAttribute { get => _scriptBlockData.ExperimentalAttribute; } - internal bool Compile(bool optimized) - { - return _scriptBlockData.Compile(optimized); - } + internal bool Compile(bool optimized) => _scriptBlockData.Compile(optimized); internal static void LogScriptBlockCreation(ScriptBlock scriptBlock, bool force) { @@ -1380,8 +1409,8 @@ internal static void LogScriptBlockCreation(ScriptBlock scriptBlock, bool force) { // If script block logging is explicitly disabled, or it's from a trusted // file or internal, skip logging. - if (logSetting?.EnableScriptBlockLogging == false || - scriptBlock.ScriptBlockData.IsProductCode) + if (logSetting?.EnableScriptBlockLogging == false + || scriptBlock.ScriptBlockData.IsProductCode) { scriptBlock.SkipLogging = true; return; @@ -1430,7 +1459,8 @@ private static bool WriteScriptBlockToLog(ScriptBlock scriptBlock, int segment, { // See if we need to encrypt the event log message. This info is all cached by Utils.GetPolicySetting(), // so we're not hitting the configuration file for every script block we compile. - ProtectedEventLogging logSetting = Utils.GetPolicySetting(Utils.SystemWideOnlyConfig); + ProtectedEventLogging logSetting = + Utils.GetPolicySetting(Utils.SystemWideOnlyConfig); bool wasEncoded = false; if (logSetting != null) { @@ -1449,11 +1479,16 @@ private static bool WriteScriptBlockToLog(ScriptBlock scriptBlock, int segment, // version. if (s_encryptionRecipients != null) { - // Encrypt the raw Text from the scriptblock. The user may have to deal with any control characters in the data. + // Encrypt the raw Text from the scriptblock. The user may have to deal with any control + // characters in the data. ExecutionContext executionContext = LocalPipeline.GetExecutionContextFromTLS(); ErrorRecord error = null; byte[] contentBytes = System.Text.Encoding.UTF8.GetBytes(textToLog); - string encodedContent = CmsUtils.Encrypt(contentBytes, s_encryptionRecipients, executionContext.SessionState, out error); + string encodedContent = CmsUtils.Encrypt( + contentBytes, + s_encryptionRecipients, + executionContext.SessionState, + out error); // Can't cache the reporting of encryption errors, as they are likely content-based. if (error != null) @@ -1464,9 +1499,20 @@ private static bool WriteScriptBlockToLog(ScriptBlock scriptBlock, int segment, // attacker seeing potentially sensitive data. Because if they aren't detected, then // they can just wait on the compromised box and see the sensitive data eventually anyways. - string errorMessage = StringUtil.Format(SecuritySupportStrings.CouldNotEncryptContent, textToLog, error.ToString()); - PSEtwLog.LogOperationalError(PSEventId.ScriptBlock_Compile_Detail, PSOpcode.Create, PSTask.ExecuteCommand, PSKeyword.UseAlwaysOperational, - 0, 0, errorMessage, scriptBlock.Id.ToString(), scriptBlock.File ?? string.Empty); + string errorMessage = StringUtil.Format( + SecuritySupportStrings.CouldNotEncryptContent, + textToLog, + error.ToString()); + PSEtwLog.LogOperationalError( + id: PSEventId.ScriptBlock_Compile_Detail, + opcode: PSOpcode.Create, + task: PSTask.ExecuteCommand, + keyword: PSKeyword.UseAlwaysOperational, + 0, + 0, + errorMessage, + scriptBlock.Id.ToString(), + scriptBlock.File ?? string.Empty); } else { @@ -1488,19 +1534,37 @@ private static bool WriteScriptBlockToLog(ScriptBlock scriptBlock, int segment, if (scriptBlock._scriptBlockData.HasSuspiciousContent) { - PSEtwLog.LogOperationalWarning(PSEventId.ScriptBlock_Compile_Detail, PSOpcode.Create, PSTask.ExecuteCommand, PSKeyword.UseAlwaysOperational, - segment + 1, segments, textToLog, scriptBlock.Id.ToString(), scriptBlock.File ?? string.Empty); + PSEtwLog.LogOperationalWarning( + id: PSEventId.ScriptBlock_Compile_Detail, + opcode: PSOpcode.Create, + task: PSTask.ExecuteCommand, + keyword: PSKeyword.UseAlwaysOperational, + segment + 1, + segments, + textToLog, + scriptBlock.Id.ToString(), + scriptBlock.File ?? string.Empty); } else { - PSEtwLog.LogOperationalVerbose(PSEventId.ScriptBlock_Compile_Detail, PSOpcode.Create, PSTask.ExecuteCommand, PSKeyword.UseAlwaysOperational, - segment + 1, segments, textToLog, scriptBlock.Id.ToString(), scriptBlock.File ?? string.Empty); + PSEtwLog.LogOperationalVerbose( + id: PSEventId.ScriptBlock_Compile_Detail, + opcode: PSOpcode.Create, + task: PSTask.ExecuteCommand, + keyword: PSKeyword.UseAlwaysOperational, + segment + 1, + segments, + textToLog, + scriptBlock.Id.ToString(), + scriptBlock.File ?? string.Empty); } return true; } - private static bool GetAndValidateEncryptionRecipients(ScriptBlock scriptBlock, ProtectedEventLogging logSetting) + private static bool GetAndValidateEncryptionRecipients( + ScriptBlock scriptBlock, + ProtectedEventLogging logSetting) { // See if protected event logging is enabled if (logSetting.EnableProtectedEventLogging == true) @@ -1558,9 +1622,19 @@ private static bool GetAndValidateEncryptionRecipients(ScriptBlock scriptBlock, // being able to detect that an attacker has compromised a box outweighs the danger of the // attacker seeing potentially sensitive data. Because if they aren't detected, then // they can just wait on the compromised box and see the sensitive data eventually anyways. - string errorMessage = StringUtil.Format(SecuritySupportStrings.CouldNotUseCertificate, error.ToString()); - PSEtwLog.LogOperationalError(PSEventId.ScriptBlock_Compile_Detail, PSOpcode.Create, PSTask.ExecuteCommand, PSKeyword.UseAlwaysOperational, - 0, 0, errorMessage, scriptBlock.Id.ToString(), scriptBlock.File ?? string.Empty); + string errorMessage = StringUtil.Format( + SecuritySupportStrings.CouldNotUseCertificate, + error.ToString()); + PSEtwLog.LogOperationalError( + id: PSEventId.ScriptBlock_Compile_Detail, + opcode: PSOpcode.Create, + task: PSTask.ExecuteCommand, + keyword: PSKeyword.UseAlwaysOperational, + 0, + 0, + errorMessage, + scriptBlock.Id.ToString(), + scriptBlock.File ?? string.Empty); return true; } @@ -1583,9 +1657,19 @@ private static bool GetAndValidateEncryptionRecipients(ScriptBlock scriptBlock, certificateForLog = logSetting.EncryptionCertificate[1]; } - string errorMessage = StringUtil.Format(SecuritySupportStrings.CertificateContainsPrivateKey, certificateForLog); - PSEtwLog.LogOperationalError(PSEventId.ScriptBlock_Compile_Detail, PSOpcode.Create, PSTask.ExecuteCommand, PSKeyword.UseAlwaysOperational, - 0, 0, errorMessage, scriptBlock.Id.ToString(), scriptBlock.File ?? string.Empty); + string errorMessage = StringUtil.Format( + SecuritySupportStrings.CertificateContainsPrivateKey, + certificateForLog); + PSEtwLog.LogOperationalError( + id: PSEventId.ScriptBlock_Compile_Detail, + opcode: PSOpcode.Create, + task: PSTask.ExecuteCommand, + keyword: PSKeyword.UseAlwaysOperational, + 0, + 0, + errorMessage, + scriptBlock.Id.ToString(), + scriptBlock.File ?? string.Empty); } } } @@ -1635,12 +1719,13 @@ internal static string CheckSuspiciousContent(Ast scriptBlockAst) if (scriptBlockAst.HasSuspiciousContent) { - Ast foundAst = scriptBlockAst.Find(ast => - { - // Try to find the lowest AST that was not considered suspicious, but its parent - // was. - return (!ast.HasSuspiciousContent) && (ast.Parent.HasSuspiciousContent); - }, true); + Ast foundAst = scriptBlockAst.Find( + ast => + { + // Try to find the lowest AST that was not considered suspicious, but its parent + // was. + return (!ast.HasSuspiciousContent) && ast.Parent.HasSuspiciousContent; + }, true); if (foundAst != null) { @@ -1830,13 +1915,18 @@ static string LookupHash(uint h) private static string CheckForMatches(uint[] runningHash, int upTo) { var upToMax = runningHash.Length; - if (upTo == 0) upTo = upToMax; - else if (upTo > upToMax) upTo = upToMax; + if (upTo == 0 || upTo > upToMax) + { + upTo = upToMax; + } for (var i = 0; i < upTo; i++) { var result = LookupHash(runningHash[i]); - if (result != null) return result; + if (result != null) + { + return result; + } } return null; @@ -1926,7 +2016,8 @@ char ToLower(char c) } if (pattern.Length > 29) { - throw new Exception("Update runningHash in match for new longest string.\n" + + throw new Exception( + "Update runningHash in match for new longest string.\n" + "Also a longer maximum length could greatly affect the performance of this algorithm, so only increase with care."); } @@ -1956,8 +2047,13 @@ internal static void LogScriptBlockStart(ScriptBlock scriptBlock, Guid runspaceI if (GetScriptBlockLoggingSetting()?.EnableScriptBlockInvocationLogging == true) { - PSEtwLog.LogOperationalVerbose(PSEventId.ScriptBlock_Invoke_Start_Detail, PSOpcode.Create, PSTask.CommandStart, PSKeyword.UseAlwaysOperational, - scriptBlock.Id.ToString(), runspaceId.ToString()); + PSEtwLog.LogOperationalVerbose( + id: PSEventId.ScriptBlock_Invoke_Start_Detail, + opcode: PSOpcode.Create, + task: PSTask.CommandStart, + keyword: PSKeyword.UseAlwaysOperational, + scriptBlock.Id.ToString(), + runspaceId.ToString()); } } @@ -1965,43 +2061,48 @@ internal static void LogScriptBlockEnd(ScriptBlock scriptBlock, Guid runspaceId) { if (GetScriptBlockLoggingSetting()?.EnableScriptBlockInvocationLogging == true) { - PSEtwLog.LogOperationalVerbose(PSEventId.ScriptBlock_Invoke_Complete_Detail, PSOpcode.Create, PSTask.CommandStop, PSKeyword.UseAlwaysOperational, - scriptBlock.Id.ToString(), runspaceId.ToString()); + PSEtwLog.LogOperationalVerbose( + id: PSEventId.ScriptBlock_Invoke_Complete_Detail, + opcode: PSOpcode.Create, + task: PSTask.CommandStop, + keyword: PSKeyword.UseAlwaysOperational, + scriptBlock.Id.ToString(), + runspaceId.ToString()); } } - internal CompiledScriptBlockData ScriptBlockData { get { return _scriptBlockData; } } + internal CompiledScriptBlockData ScriptBlockData { get => _scriptBlockData; } /// /// Returns the AST corresponding to the script block. /// - public Ast Ast { get { return (Ast)_scriptBlockData.Ast; } } + public Ast Ast { get => (Ast)_scriptBlockData.Ast; } - internal IParameterMetadataProvider AstInternal { get { return _scriptBlockData.Ast; } } + internal IParameterMetadataProvider AstInternal { get => _scriptBlockData.Ast; } - internal IScriptExtent[] SequencePoints { get { return _scriptBlockData.SequencePoints; } } + internal IScriptExtent[] SequencePoints { get => _scriptBlockData.SequencePoints; } - internal Action DynamicParamBlock { get { return _scriptBlockData.DynamicParamBlock; } } + internal Action DynamicParamBlock { get => _scriptBlockData.DynamicParamBlock; } - internal Action UnoptimizedDynamicParamBlock { get { return _scriptBlockData.UnoptimizedDynamicParamBlock; } } + internal Action UnoptimizedDynamicParamBlock { get => _scriptBlockData.UnoptimizedDynamicParamBlock; } - internal Action BeginBlock { get { return _scriptBlockData.BeginBlock; } } + internal Action BeginBlock { get => _scriptBlockData.BeginBlock; } - internal Action UnoptimizedBeginBlock { get { return _scriptBlockData.UnoptimizedBeginBlock; } } + internal Action UnoptimizedBeginBlock { get => _scriptBlockData.UnoptimizedBeginBlock; } - internal Action ProcessBlock { get { return _scriptBlockData.ProcessBlock; } } + internal Action ProcessBlock { get => _scriptBlockData.ProcessBlock; } - internal Action UnoptimizedProcessBlock { get { return _scriptBlockData.UnoptimizedProcessBlock; } } + internal Action UnoptimizedProcessBlock { get => _scriptBlockData.UnoptimizedProcessBlock; } - internal Action EndBlock { get { return _scriptBlockData.EndBlock; } } + internal Action EndBlock { get => _scriptBlockData.EndBlock; } - internal Action UnoptimizedEndBlock { get { return _scriptBlockData.UnoptimizedEndBlock; } } + internal Action UnoptimizedEndBlock { get => _scriptBlockData.UnoptimizedEndBlock; } - internal bool HasBeginBlock { get { return AstInternal.Body.BeginBlock != null; } } + internal bool HasBeginBlock { get => AstInternal.Body.BeginBlock != null; } - internal bool HasProcessBlock { get { return AstInternal.Body.ProcessBlock != null; } } + internal bool HasProcessBlock { get => AstInternal.Body.ProcessBlock != null; } - internal bool HasEndBlock { get { return AstInternal.Body.EndBlock != null; } } + internal bool HasEndBlock { get => AstInternal.Body.EndBlock != null; } } [Serializable] @@ -2011,7 +2112,10 @@ internal class ScriptBlockSerializationHelper : ISerializable, IObjectReference private ScriptBlockSerializationHelper(SerializationInfo info, StreamingContext context) { - if (info == null) throw new ArgumentNullException("info"); + if (info == null) + { + throw new ArgumentNullException(nameof(info)); + } _scriptText = info.GetValue("ScriptText", typeof(string)) as string; if (_scriptText == null) @@ -2025,10 +2129,7 @@ private ScriptBlockSerializationHelper(SerializationInfo info, StreamingContext /// /// The streaming context for this instance. /// A script block that corresponds to the version deserialized. - public object GetRealObject(StreamingContext context) - { - return ScriptBlock.Create(_scriptText); - } + public object GetRealObject(StreamingContext context) => ScriptBlock.Create(_scriptText); /// /// Implements the ISerializable contract for serializing a scriptblock. @@ -2036,9 +2137,7 @@ public object GetRealObject(StreamingContext context) /// Serialization information for this instance. /// The streaming context for this instance. public virtual void GetObjectData(SerializationInfo info, StreamingContext context) - { - throw new NotSupportedException(); - } + => throw new NotSupportedException(); } internal sealed class PSScriptCmdlet : PSCmdlet, IDynamicParameters, IDisposable @@ -2092,7 +2191,10 @@ protected override void BeginProcessing() if (_scriptBlock.HasBeginBlock) { - RunClause(_runOptimized ? _scriptBlock.BeginBlock : _scriptBlock.UnoptimizedBeginBlock, AutomationNull.Value, _input); + RunClause( + _runOptimized ? _scriptBlock.BeginBlock : _scriptBlock.UnoptimizedBeginBlock, + AutomationNull.Value, + _input); } } @@ -2116,7 +2218,10 @@ internal override void DoProcessRecord() if (_scriptBlock.HasProcessBlock) { - RunClause(_runOptimized ? _scriptBlock.ProcessBlock : _scriptBlock.UnoptimizedProcessBlock, dollarUnder, _input); + RunClause( + _runOptimized ? _scriptBlock.ProcessBlock : _scriptBlock.UnoptimizedProcessBlock, + dollarUnder, + _input); _input.Clear(); } } @@ -2130,7 +2235,10 @@ internal override void DoEndProcessing() if (_scriptBlock.HasEndBlock) { - RunClause(_runOptimized ? _scriptBlock.EndBlock : _scriptBlock.UnoptimizedEndBlock, AutomationNull.Value, _input.ToArray()); + RunClause( + _runOptimized ? _scriptBlock.EndBlock : _scriptBlock.UnoptimizedEndBlock, + AutomationNull.Value, + _input.ToArray()); } } @@ -2152,8 +2260,8 @@ private void RunClause(Action clause, object dollarUnderbar, ob // change the language mode. PSLanguageMode? oldLanguageMode = null; PSLanguageMode? newLanguageMode = null; - if ((_scriptBlock.LanguageMode.HasValue) && - (_scriptBlock.LanguageMode != Context.LanguageMode)) + if (_scriptBlock.LanguageMode.HasValue + && _scriptBlock.LanguageMode != Context.LanguageMode) { oldLanguageMode = Context.LanguageMode; newLanguageMode = _scriptBlock.LanguageMode; @@ -2223,7 +2331,9 @@ private void RunClause(Action clause, object dollarUnderbar, ob this.Context.SetVariable(SpecialVariables.LastExitCodeVarPath, exitCode); if (exitCode != 0) + { _commandRuntime.PipelineProcessor.ExecutionFailed = true; + } } } @@ -2236,11 +2346,14 @@ public object GetDynamicParameters() var resultList = new List(); Diagnostics.Assert(_functionContext._outputPipe == null, "Output pipe should not be set yet."); _functionContext._outputPipe = new Pipe(resultList); - RunClause(_runOptimized ? _scriptBlock.DynamicParamBlock : _scriptBlock.UnoptimizedDynamicParamBlock, - AutomationNull.Value, AutomationNull.Value); + RunClause( + _runOptimized ? _scriptBlock.DynamicParamBlock : _scriptBlock.UnoptimizedDynamicParamBlock, + AutomationNull.Value, + AutomationNull.Value); if (resultList.Count > 1) { - throw PSTraceSource.NewInvalidOperationException(AutomationExceptions.DynamicParametersWrongType, + throw PSTraceSource.NewInvalidOperationException( + AutomationExceptions.DynamicParametersWrongType, PSObject.ToStringParser(this.Context, resultList)); } @@ -2262,38 +2375,38 @@ internal void SetLocalsTupleForNewScope(SessionStateScope scope) /// /// If the script cmdlet is dotted, this method is used to push the locals to the 'DottedScopes' of the current scope. /// - internal void PushDottedScope(SessionStateScope scope) - { - scope.DottedScopes.Push(_localsTuple); - } + internal void PushDottedScope(SessionStateScope scope) => scope.DottedScopes.Push(_localsTuple); /// /// If the script cmdlet is dotted, this method is used to pop the locals from the 'DottedScopes' of the current scope. /// - internal void PopDottedScope(SessionStateScope scope) - { - scope.DottedScopes.Pop(); - } + internal void PopDottedScope(SessionStateScope scope) => scope.DottedScopes.Pop(); internal void PrepareForBinding(CommandLineParameters commandLineParameters) { - _localsTuple.SetAutomaticVariable(AutomaticVariable.PSBoundParameters, - commandLineParameters.GetValueToBindToPSBoundParameters(), this.Context); - _localsTuple.SetAutomaticVariable(AutomaticVariable.MyInvocation, MyInvocation, this.Context); + _localsTuple.SetAutomaticVariable( + AutomaticVariable.PSBoundParameters, + commandLineParameters.GetValueToBindToPSBoundParameters(), + this.Context); + _localsTuple.SetAutomaticVariable( + AutomaticVariable.MyInvocation, + MyInvocation, this.Context); } private void SetPreferenceVariables() { if (_commandRuntime.IsDebugFlagSet) { - _localsTuple.SetPreferenceVariable(PreferenceVariable.Debug, - _commandRuntime.Debug ? ActionPreference.Continue : ActionPreference.SilentlyContinue); + _localsTuple.SetPreferenceVariable( + PreferenceVariable.Debug, + _commandRuntime.Debug ? ActionPreference.Continue : ActionPreference.SilentlyContinue); } if (_commandRuntime.IsVerboseFlagSet) { - _localsTuple.SetPreferenceVariable(PreferenceVariable.Verbose, - _commandRuntime.Verbose ? ActionPreference.Continue : ActionPreference.SilentlyContinue); + _localsTuple.SetPreferenceVariable( + PreferenceVariable.Verbose, + _commandRuntime.Verbose ? ActionPreference.Continue : ActionPreference.SilentlyContinue); } if (_commandRuntime.IsErrorActionSet) @@ -2318,8 +2431,9 @@ private void SetPreferenceVariables() if (_commandRuntime.IsConfirmFlagSet) { - _localsTuple.SetPreferenceVariable(PreferenceVariable.Confirm, - _commandRuntime.Confirm ? ConfirmImpact.Low : ConfirmImpact.None); + _localsTuple.SetPreferenceVariable( + PreferenceVariable.Confirm, + _commandRuntime.Confirm ? ConfirmImpact.Low : ConfirmImpact.None); } } @@ -2349,7 +2463,9 @@ protected override void StopProcessing() public void Dispose() { if (_disposed) + { return; + } this.DisposingEvent.SafeInvoke(this, EventArgs.Empty); commandRuntime = null; From 12cf72281e37aa395c51292332dfe8a98b66c65e Mon Sep 17 00:00:00 2001 From: vexx32 <32407840+vexx32@users.noreply.github.com> Date: Tue, 28 May 2019 22:42:39 -0400 Subject: [PATCH 2/6] :recycle: named method params --- .../engine/runtime/CompiledScriptBlock.cs | 30 +++++++++---------- 1 file changed, 14 insertions(+), 16 deletions(-) diff --git a/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs b/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs index 339b017b047..ebafd0c420b 100644 --- a/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs +++ b/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs @@ -2192,9 +2192,9 @@ protected override void BeginProcessing() if (_scriptBlock.HasBeginBlock) { RunClause( - _runOptimized ? _scriptBlock.BeginBlock : _scriptBlock.UnoptimizedBeginBlock, - AutomationNull.Value, - _input); + clause: _runOptimized ? _scriptBlock.BeginBlock : _scriptBlock.UnoptimizedBeginBlock, + dollarUnderbar: AutomationNull.Value, + inputToProcess: _input); } } @@ -2219,9 +2219,9 @@ internal override void DoProcessRecord() if (_scriptBlock.HasProcessBlock) { RunClause( - _runOptimized ? _scriptBlock.ProcessBlock : _scriptBlock.UnoptimizedProcessBlock, - dollarUnder, - _input); + clause: _runOptimized ? _scriptBlock.ProcessBlock : _scriptBlock.UnoptimizedProcessBlock, + dollarUnderbar: dollarUnder, + inputToProcess: _input); _input.Clear(); } } @@ -2236,9 +2236,9 @@ internal override void DoEndProcessing() if (_scriptBlock.HasEndBlock) { RunClause( - _runOptimized ? _scriptBlock.EndBlock : _scriptBlock.UnoptimizedEndBlock, - AutomationNull.Value, - _input.ToArray()); + clause: _runOptimized ? _scriptBlock.EndBlock : _scriptBlock.UnoptimizedEndBlock, + dollarUnderbar: AutomationNull.Value, + inputToProcess: _input.ToArray()); } } @@ -2347,9 +2347,9 @@ public object GetDynamicParameters() Diagnostics.Assert(_functionContext._outputPipe == null, "Output pipe should not be set yet."); _functionContext._outputPipe = new Pipe(resultList); RunClause( - _runOptimized ? _scriptBlock.DynamicParamBlock : _scriptBlock.UnoptimizedDynamicParamBlock, - AutomationNull.Value, - AutomationNull.Value); + clause: _runOptimized ? _scriptBlock.DynamicParamBlock : _scriptBlock.UnoptimizedDynamicParamBlock, + dollarUnderbar: AutomationNull.Value, + inputToProcess: AutomationNull.Value); if (resultList.Count > 1) { throw PSTraceSource.NewInvalidOperationException( @@ -2386,11 +2386,9 @@ internal void PrepareForBinding(CommandLineParameters commandLineParameters) { _localsTuple.SetAutomaticVariable( AutomaticVariable.PSBoundParameters, - commandLineParameters.GetValueToBindToPSBoundParameters(), + value: commandLineParameters.GetValueToBindToPSBoundParameters(), this.Context); - _localsTuple.SetAutomaticVariable( - AutomaticVariable.MyInvocation, - MyInvocation, this.Context); + _localsTuple.SetAutomaticVariable(AutomaticVariable.MyInvocation, value: MyInvocation, this.Context); } private void SetPreferenceVariables() From a8ca7d0ff062556fb2448b079d47388f0f1c9aa5 Mon Sep 17 00:00:00 2001 From: vexx32 <32407840+vexx32@users.noreply.github.com> Date: Wed, 29 May 2019 22:20:10 -0400 Subject: [PATCH 3/6] :recycle: Address review comments --- .../engine/runtime/CompiledScriptBlock.cs | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs b/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs index ebafd0c420b..b519ef90592 100644 --- a/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs +++ b/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs @@ -716,13 +716,15 @@ internal PowerShell GetPowerShellImpl( bool filterNonUsingVariables, bool? createLocalScope, params object[] args) - => AstInternal.GetPowerShell( + { + return AstInternal.GetPowerShell( context, variables, isTrustedInput, filterNonUsingVariables, createLocalScope, args); + } internal SteppablePipeline GetSteppablePipelineImpl(CommandOrigin commandOrigin, object[] args) @@ -1132,9 +1134,7 @@ internal void InvokeWithPipeImpl( string name = psvar.Name; Diagnostics.Assert( - !(string.Equals(name, "this") - || string.Equals(name, "_") - || string.Equals(name, "input")), + !(string.Equals(name, "this") || string.Equals(name, "_") || string.Equals(name, "input")), "The list of variables to set in the scriptblock's scope cannot contain 'this', '_' or 'input'. These variables should be removed before passing the collection to this routine."); index++; newScope.Variables.Add(name, psvar); @@ -1475,12 +1475,12 @@ private static bool WriteScriptBlockToLog(ScriptBlock scriptBlock, int segment, return false; } - // If we have recipients to encrypt to, then do so. Otherwise, we'll just log the plain text - // version. + // If we have recipients to encrypt to, then do so. + // Otherwise, we'll just log the plain text version. if (s_encryptionRecipients != null) { - // Encrypt the raw Text from the scriptblock. The user may have to deal with any control - // characters in the data. + // Encrypt the raw text from the scriptblock. + // The user may have to deal with any control characters in the data. ExecutionContext executionContext = LocalPipeline.GetExecutionContextFromTLS(); ErrorRecord error = null; byte[] contentBytes = System.Text.Encoding.UTF8.GetBytes(textToLog); From f2fb0f4a8c0c38f8a505164a6ae63ee76b9513a2 Mon Sep 17 00:00:00 2001 From: vexx32 <32407840+vexx32@users.noreply.github.com> Date: Sun, 16 Jun 2019 08:17:55 -0400 Subject: [PATCH 4/6] :recycle: Address review comments --- .../engine/runtime/CompiledScriptBlock.cs | 16 ++++++---------- 1 file changed, 6 insertions(+), 10 deletions(-) diff --git a/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs b/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs index b519ef90592..e899cf7d334 100644 --- a/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs +++ b/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs @@ -576,16 +576,10 @@ internal static ScriptBlock TryGetCachedScriptBlock(string fileName, string file } private static bool IsDynamicKeyword(Ast ast) - { - var cmdAst = ast as CommandAst; - return cmdAst?.DefiningKeyword != null; - } + => ast is CommandAst cmdAst && cmdAst.DefiningKeyword != null; private static bool IsUsingTypes(Ast ast) - { - var cmdAst = ast as UsingStatementAst; - return cmdAst?.IsUsingModuleOrAssembly() == true; - } + => ast is UsingStatementAst cmdAst && cmdAst.IsUsingModuleOrAssembly() == true; internal static void CacheScriptBlock(ScriptBlock scriptBlock, string fileName, string fileContents) { @@ -939,8 +933,9 @@ internal void InvokeWithPipeImpl( Pipe outputPipe, InvocationInfo invocationInfo, params object[] args) - => InvokeWithPipeImpl( - clauseToInvoke: ScriptBlockClauseToInvoke.ProcessBlockOnly, + { + InvokeWithPipeImpl( + ScriptBlockClauseToInvoke.ProcessBlockOnly, createLocalScope, functionsToDefine, variablesToDefine, @@ -951,6 +946,7 @@ internal void InvokeWithPipeImpl( outputPipe, invocationInfo, args); + } internal void InvokeWithPipeImpl( ScriptBlockClauseToInvoke clauseToInvoke, From 85e391f5603d9ab52d3ca840554dadfa8267a9d6 Mon Sep 17 00:00:00 2001 From: vexx32 <32407840+vexx32@users.noreply.github.com> Date: Sun, 16 Jun 2019 08:54:17 -0400 Subject: [PATCH 5/6] :memo: tidy comment --- .../engine/runtime/CompiledScriptBlock.cs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs b/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs index e899cf7d334..cbe44590886 100644 --- a/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs +++ b/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs @@ -1718,8 +1718,7 @@ internal static string CheckSuspiciousContent(Ast scriptBlockAst) Ast foundAst = scriptBlockAst.Find( ast => { - // Try to find the lowest AST that was not considered suspicious, but its parent - // was. + // Try to find the lowest AST that was not considered suspicious, but its parent was. return (!ast.HasSuspiciousContent) && ast.Parent.HasSuspiciousContent; }, true); From 5c02e7af53a2cdb41f98e854acb54b7278bdebdb Mon Sep 17 00:00:00 2001 From: vexx32 <32407840+vexx32@users.noreply.github.com> Date: Sun, 16 Jun 2019 16:10:52 -0400 Subject: [PATCH 6/6] :wrench: Address Ilya's comment --- .../engine/runtime/CompiledScriptBlock.cs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs b/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs index cbe44590886..e87786c7ca5 100644 --- a/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs +++ b/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs @@ -604,7 +604,7 @@ internal static void CacheScriptBlock(ScriptBlock scriptBlock, string fileName, if (s_cachedScripts.Count > 1024) { - ClearScriptBlockCache(); + s_cachedScripts.Clear(); } var key = Tuple.Create(fileName, fileContents); @@ -630,8 +630,7 @@ internal static ScriptBlock Create(Parser parser, string fileName, string fileCo return scriptBlock; } - ParseError[] errors; - var ast = parser.Parse(fileName, fileContents, null, out errors, ParseMode.Default); + var ast = parser.Parse(fileName, fileContents, null, out ParseError[] errors, ParseMode.Default); if (errors.Length != 0) { throw new ParseException(errors);