internal override void Prepare(IDictionary psDefaultParameterValues) { _localsTuple.SetAutomaticVariable(AutomaticVariable.MyInvocation, this.Command.MyInvocation, _context); _scriptBlock.SetPSScriptRootAndPSCommandPath(_localsTuple, _context); _functionContext = new FunctionContext { _executionContext = _context, _outputPipe = commandRuntime.OutputPipe, _localsTuple = _localsTuple, _scriptBlock = _scriptBlock, _file = _scriptBlock.File, _debuggerHidden = _scriptBlock.DebuggerHidden, _debuggerStepThrough = _scriptBlock.DebuggerStepThrough, _sequencePoints = _scriptBlock.SequencePoints, }; }
internal override void Prepare(IDictionary psDefaultParameterValues) { if (UseLocalScope) { Diagnostics.Assert(CommandScope.LocalsTuple == null, "a newly created scope shouldn't have it's tuple set."); CommandScope.LocalsTuple = _localsTuple; } _localsTuple.SetAutomaticVariable(AutomaticVariable.MyInvocation, this.Command.MyInvocation, _context); _scriptBlock.SetPSScriptRootAndPSCommandPath(_localsTuple, _context); _functionContext = new FunctionContext { _executionContext = _context, _outputPipe = commandRuntime.OutputPipe, _localsTuple = _localsTuple, _scriptBlock = _scriptBlock, _file = _scriptBlock.File, _debuggerHidden = _scriptBlock.DebuggerHidden, _debuggerStepThrough = _scriptBlock.DebuggerStepThrough, _sequencePoints = _scriptBlock.SequencePoints, }; }
internal static int FindMatchingHandler(MutableTuple tuple, RuntimeException rte, Type[] types, ExecutionContext context) { Exception replaceParentContainsErrorRecordException = rte; Exception innerException = rte.InnerException; int index = -1; if (innerException != null) { index = FindMatchingHandlerByType(innerException.GetType(), types); replaceParentContainsErrorRecordException = innerException; } if ((index == -1) || types[index].Equals(typeof(CatchAll))) { index = FindMatchingHandlerByType(rte.GetType(), types); replaceParentContainsErrorRecordException = rte; } if ((index == -1) || types[index].Equals(typeof(CatchAll))) { ActionPreferenceStopException exception3 = rte as ActionPreferenceStopException; if (exception3 != null) { replaceParentContainsErrorRecordException = exception3.ErrorRecord.Exception; if (replaceParentContainsErrorRecordException is RuntimeException) { return(FindMatchingHandler(tuple, (RuntimeException)replaceParentContainsErrorRecordException, types, context)); } if (replaceParentContainsErrorRecordException != null) { index = FindMatchingHandlerByType(replaceParentContainsErrorRecordException.GetType(), types); } } else if ((rte is CmdletInvocationException) && (innerException != null)) { replaceParentContainsErrorRecordException = innerException.InnerException; if (replaceParentContainsErrorRecordException != null) { index = FindMatchingHandlerByType(replaceParentContainsErrorRecordException.GetType(), types); } } } if (index != -1) { ErrorRecord record = new ErrorRecord(rte.ErrorRecord, replaceParentContainsErrorRecordException); tuple.SetAutomaticVariable(AutomaticVariable.Underbar, record, context); } return(index); }
public PSScriptCmdlet(ScriptBlock scriptBlock, bool useNewScope, bool fromScriptFile, ExecutionContext context) { _scriptBlock = scriptBlock; _useLocalScope = useNewScope; _fromScriptFile = fromScriptFile; _runOptimized = _scriptBlock.Compile(optimized: context._debuggingMode > 0 ? false : useNewScope); _localsTuple = _scriptBlock.MakeLocalsTuple(_runOptimized); _localsTuple.SetAutomaticVariable(AutomaticVariable.PSCmdlet, this, context); _scriptBlock.SetPSScriptRootAndPSCommandPath(_localsTuple, context); _functionContext = new FunctionContext { _localsTuple = _localsTuple, _scriptBlock = _scriptBlock, _file = _scriptBlock.File, _sequencePoints = _scriptBlock.SequencePoints, _debuggerHidden = _scriptBlock.DebuggerHidden, _debuggerStepThrough = _scriptBlock.DebuggerStepThrough, _executionContext = context, }; _rethrowExitException = context.ScriptCommandProcessorShouldRethrowExit; context.ScriptCommandProcessorShouldRethrowExit = false; }
internal static object[] BindArgumentsForScriptblockInvoke( RuntimeDefinedParameter[] parameters, object[] args, ExecutionContext context, bool dotting, Dictionary<string, PSVariable> backupWhenDotting, MutableTuple locals) { var boundParameters = new CommandLineParameters(); if (parameters.Length == 0) { return args; } for (int i = 0; i < parameters.Length; i++) { var parameter = parameters[i]; object valueToBind; bool wasDefaulted = false; if (i >= args.Length) { valueToBind = parameter.Value; if (valueToBind is Compiler.DefaultValueExpressionWrapper) { // We pass in a null SessionStateInternal because the current scope is already set correctly. valueToBind = ((Compiler.DefaultValueExpressionWrapper)valueToBind).GetValue(context, null); } wasDefaulted = true; } else { valueToBind = args[i]; } bool valueSet = false; if (dotting && backupWhenDotting != null) { backupWhenDotting[parameter.Name] = context.EngineSessionState.GetVariableAtScope(parameter.Name, "local"); } else { valueSet = locals.TrySetParameter(parameter.Name, valueToBind); } if (!valueSet) { var variable = new PSVariable(parameter.Name, valueToBind, ScopedItemOptions.None, parameter.Attributes); context.EngineSessionState.SetVariable(variable, false, CommandOrigin.Internal); } if (!wasDefaulted) { boundParameters.Add(parameter.Name, valueToBind); boundParameters.MarkAsBoundPositionally(parameter.Name); } } locals.SetAutomaticVariable(AutomaticVariable.PSBoundParameters, boundParameters.GetValueToBindToPSBoundParameters(), context); var leftOverArgs = args.Length - parameters.Length; if (leftOverArgs <= 0) { return Utils.EmptyArray<object>(); } object[] result = new object[leftOverArgs]; Array.Copy(args, parameters.Length, result, 0, result.Length); return result; }
internal static object[] BindArgumentsForScripblockInvoke(RuntimeDefinedParameter[] parameters, object[] args, ExecutionContext context, bool dotting, Dictionary<string, PSVariable> backupWhenDotting, MutableTuple locals) { object value; CommandLineParameters commandLineParameter = new CommandLineParameters(); if ((int)parameters.Length != 0) { for (int i = 0; i < (int)parameters.Length; i++) { RuntimeDefinedParameter variableAtScope = parameters[i]; bool flag = false; if (i < (int)args.Length) { value = args[i]; } else { value = variableAtScope.Value; if (value as Compiler.DefaultValueExpressionWrapper != null) { value = ((Compiler.DefaultValueExpressionWrapper)value).GetValue(context, null, null); } flag = true; } bool flag1 = false; if (!dotting || backupWhenDotting == null) { flag1 = locals.TrySetParameter(variableAtScope.Name, value); } else { backupWhenDotting[variableAtScope.Name] = context.EngineSessionState.GetVariableAtScope(variableAtScope.Name, "local"); } if (!flag1) { PSVariable pSVariable = new PSVariable(variableAtScope.Name, value, ScopedItemOptions.None, variableAtScope.Attributes); context.EngineSessionState.SetVariable(pSVariable, false, CommandOrigin.Internal); } if (!flag) { commandLineParameter.Add(variableAtScope.Name, value); commandLineParameter.MarkAsBoundPositionally(variableAtScope.Name); } } locals.SetAutomaticVariable(AutomaticVariable.PSBoundParameters, commandLineParameter.GetValueToBindToPSBoundParameters(), context); int length = (int)args.Length - (int)parameters.Length; if (length > 0) { object[] objArray = new object[length]; Array.Copy(args, (int)parameters.Length, objArray, 0, (int)objArray.Length); return objArray; } else { return ScriptBlock.EmptyArray; } } else { return args; } }
internal void SetPSScriptRootAndPSCommandPath(MutableTuple locals, ExecutionContext context) { string empty = string.Empty; string file = string.Empty; if (!string.IsNullOrEmpty(this.File)) { empty = Path.GetDirectoryName(this.File); file = this.File; } locals.SetAutomaticVariable(AutomaticVariable.PSScriptRoot, empty, context); locals.SetAutomaticVariable(AutomaticVariable.PSCommandPath, file, context); }
private void WriteToCurrentErrorPipe(bool createLocalScope, Pipe outputPipe, ref object[] args, ExecutionContext contextFromTLS, Action<FunctionContext> codeToInvoke, MutableTuple mutableTuple, PSLanguageMode? languageMode, ref Dictionary<string, PSVariable> strs) { if (!createLocalScope) { if (contextFromTLS.EngineSessionState.CurrentScope.LocalsTuple != null) { contextFromTLS.EngineSessionState.CurrentScope.DottedScopes.Push(mutableTuple); strs = new Dictionary<string, PSVariable>(); } else { contextFromTLS.EngineSessionState.CurrentScope.LocalsTuple = mutableTuple; } } else { SessionStateScope sessionStateScope = contextFromTLS.EngineSessionState.NewScope(false); contextFromTLS.EngineSessionState.CurrentScope = sessionStateScope; sessionStateScope.LocalsTuple = mutableTuple; } if (languageMode.HasValue) { contextFromTLS.LanguageMode = languageMode.Value; } args = ScriptBlock.BindArgumentsForScripblockInvoke((RuntimeDefinedParameter[])this.RuntimeDefinedParameters.Data, args, contextFromTLS, !createLocalScope, strs, mutableTuple); mutableTuple.SetAutomaticVariable(AutomaticVariable.Args, args, contextFromTLS); contextFromTLS.EngineSessionState.CurrentScope.ScopeOrigin = CommandOrigin.Internal; FunctionContext functionContext = new FunctionContext(); functionContext._executionContext = contextFromTLS; functionContext._outputPipe = outputPipe; functionContext._localsTuple = mutableTuple; functionContext._scriptBlock = this; functionContext._sequencePoints = this.SequencePoints; FunctionContext functionContext1 = functionContext; codeToInvoke(functionContext1); }
private static ActionPreference ProcessTraps(FunctionContext funcContext, RuntimeException rte) { int index = -1; Exception replaceParentContainsErrorRecordException = null; Exception innerException = rte.InnerException; Type[] types = funcContext._traps.Last <Tuple <Type[], Action <FunctionContext>[], Type[]> >().Item1; Action <FunctionContext>[] actionArray = funcContext._traps.Last <Tuple <Type[], Action <FunctionContext>[], Type[]> >().Item2; if (innerException != null) { index = FindMatchingHandlerByType(innerException.GetType(), types); replaceParentContainsErrorRecordException = innerException; } if ((index == -1) || types[index].Equals(typeof(CatchAll))) { int num2 = FindMatchingHandlerByType(rte.GetType(), types); if (num2 != index) { index = num2; replaceParentContainsErrorRecordException = rte; } } if (index != -1) { try { ErrorRecord errorRecord = rte.ErrorRecord; ExecutionContext context = funcContext._executionContext; if (context.CurrentCommandProcessor != null) { context.CurrentCommandProcessor.ForgetScriptException(); } try { MutableTuple tuple = MutableTuple.MakeTuple(funcContext._traps.Last <Tuple <Type[], Action <FunctionContext>[], Type[]> >().Item3[index], Compiler.DottedLocalsNameIndexMap); tuple.SetAutomaticVariable(AutomaticVariable.Underbar, new ErrorRecord(errorRecord, replaceParentContainsErrorRecordException), context); for (int i = 1; i < 9; i++) { tuple.SetValue(i, funcContext._localsTuple.GetValue(i)); } SessionStateScope scope = context.EngineSessionState.NewScope(false); context.EngineSessionState.CurrentScope = scope; scope.LocalsTuple = tuple; FunctionContext context2 = new FunctionContext { _scriptBlock = funcContext._scriptBlock, _sequencePoints = funcContext._sequencePoints, _executionContext = funcContext._executionContext, _boundBreakpoints = funcContext._boundBreakpoints, _outputPipe = funcContext._outputPipe, _breakPoints = funcContext._breakPoints, _localsTuple = tuple }; actionArray[index](context2); } catch (TargetInvocationException exception3) { throw exception3.InnerException; } finally { context.EngineSessionState.RemoveScope(context.EngineSessionState.CurrentScope); } return(QueryForAction(rte, replaceParentContainsErrorRecordException.Message, context)); } catch (ContinueException) { return(ActionPreference.SilentlyContinue); } catch (BreakException) { return(ActionPreference.Stop); } } return(ActionPreference.Stop); }
internal static PowerShell Convert(ScriptBlockAst body, IEnumerable <ParameterAst> functionParameters, ExecutionContext context, Dictionary <string, object> variables, bool filterNonUsingVariables, bool?createLocalScope, object[] args) { string str; string str2; PowerShell shell; ExecutionContext.CheckStackDepth(); if (args == null) { args = ScriptBlock.EmptyArray; } body.GetSimplePipeline(false, out str, out str2); if (str != null) { throw new ScriptBlockToPowerShellNotSupportedException(str, null, str2, new object[0]); } ScriptBlockToPowerShellChecker visitor = new ScriptBlockToPowerShellChecker { ScriptBeingConverted = body }; if (functionParameters != null) { foreach (ParameterAst ast in functionParameters) { ast.InternalVisit(visitor); } } body.InternalVisit(visitor); if (((context == null) && (visitor.HasUsingExpr || visitor.UsesParameter)) && (variables == null)) { throw new PSInvalidOperationException(AutomationExceptions.CantConvertScriptBlockWithNoContext); } try { ScriptBlockToPowerShellConverter converter = new ScriptBlockToPowerShellConverter { _context = context, _createLocalScope = createLocalScope }; if (visitor.HasUsingExpr) { converter._usingValues = GetUsingValues(body, context, variables, filterNonUsingVariables); } if (visitor.UsesParameter) { SessionStateScope scope = context.EngineSessionState.NewScope(false); context.EngineSessionState.CurrentScope = scope; context.EngineSessionState.CurrentScope.ScopeOrigin = CommandOrigin.Internal; MutableTuple locals = MutableTuple.MakeTuple(Compiler.DottedLocalsTupleType, Compiler.DottedLocalsNameIndexMap); bool usesCmdletBinding = false; object[] objArray = ScriptBlock.BindArgumentsForScripblockInvoke((RuntimeDefinedParameter[])((IParameterMetadataProvider)body).GetParameterMetadata(true, ref usesCmdletBinding).Data, args, context, false, null, locals); locals.SetAutomaticVariable(AutomaticVariable.Args, objArray, context); scope.LocalsTuple = locals; } foreach (PipelineAst ast2 in body.EndBlock.Statements.OfType <PipelineAst>()) { converter._powershell.AddStatement(); converter.ConvertPipeline(ast2); } shell = converter._powershell; } finally { if (visitor.UsesParameter) { context.EngineSessionState.RemoveScope(context.EngineSessionState.CurrentScope); } } return(shell); }
internal static int FindMatchingHandler(MutableTuple tuple, RuntimeException rte, Type[] types, ExecutionContext context) { Exception replaceParentContainsErrorRecordException = rte; Exception innerException = rte.InnerException; int index = -1; if (innerException != null) { index = FindMatchingHandlerByType(innerException.GetType(), types); replaceParentContainsErrorRecordException = innerException; } if ((index == -1) || types[index].Equals(typeof(CatchAll))) { index = FindMatchingHandlerByType(rte.GetType(), types); replaceParentContainsErrorRecordException = rte; } if ((index == -1) || types[index].Equals(typeof(CatchAll))) { ActionPreferenceStopException exception3 = rte as ActionPreferenceStopException; if (exception3 != null) { replaceParentContainsErrorRecordException = exception3.ErrorRecord.Exception; if (replaceParentContainsErrorRecordException is RuntimeException) { return FindMatchingHandler(tuple, (RuntimeException) replaceParentContainsErrorRecordException, types, context); } if (replaceParentContainsErrorRecordException != null) { index = FindMatchingHandlerByType(replaceParentContainsErrorRecordException.GetType(), types); } } else if ((rte is CmdletInvocationException) && (innerException != null)) { replaceParentContainsErrorRecordException = innerException.InnerException; if (replaceParentContainsErrorRecordException != null) { index = FindMatchingHandlerByType(replaceParentContainsErrorRecordException.GetType(), types); } } } if (index != -1) { ErrorRecord record = new ErrorRecord(rte.ErrorRecord, replaceParentContainsErrorRecordException); tuple.SetAutomaticVariable(AutomaticVariable.Underbar, record, context); } return index; }