Esempio n. 1
0
 internal void Invoke(PSEventSubscriber eventSubscriber, PSEventArgs eventArgs)
 {
     if (!base.IsFinishedState(base.JobStateInfo.State))
     {
         base.SetJobState(JobState.Running);
         SessionState publicSessionState = this.action.SessionStateInternal.PublicSessionState;
         publicSessionState.PSVariable.Set("eventSubscriber", eventSubscriber);
         publicSessionState.PSVariable.Set("event", eventArgs);
         publicSessionState.PSVariable.Set("sender", eventArgs.Sender);
         publicSessionState.PSVariable.Set("eventArgs", eventArgs.SourceEventArgs);
         ArrayList resultList = new ArrayList();
         try
         {
             Pipe outputPipe = new Pipe(resultList);
             this.action.InvokeWithPipe(false, System.Management.Automation.ScriptBlock.ErrorHandlingBehavior.WriteToExternalErrorPipe, AutomationNull.Value, AutomationNull.Value, AutomationNull.Value, outputPipe, null, eventArgs.SourceArgs);
         }
         catch (Exception exception)
         {
             CommandProcessorBase.CheckForSevereException(exception);
             if (!(exception is PipelineStoppedException))
             {
                 this.LogErrorsAndOutput(resultList, publicSessionState);
                 base.SetJobState(JobState.Failed);
             }
             throw;
         }
         this.LogErrorsAndOutput(resultList, publicSessionState);
         this.moreData = true;
     }
 }
Esempio n. 2
0
 protected override void ProcessRecord()
 {
     this.stopWatch.Start();
     Pipe outputPipe = new Pipe {
         NullPipe = true
     };
     this.script.InvokeWithPipe(false, ScriptBlock.ErrorHandlingBehavior.WriteToCurrentErrorPipe, this.InputObject, new object[0], AutomationNull.Value, outputPipe, null, new object[0]);
     this.stopWatch.Stop();
 }
Esempio n. 3
0
        internal Pipe[] BindForExpression(FunctionContext funcContext)
        {
            ExecutionContext context = funcContext._executionContext;
            Pipe redirectionPipe = this.GetRedirectionPipe(context, null);
            Pipe[] pipeArray = new Pipe[7];
            switch (base.FromStream)
            {
                case RedirectionStream.All:
                    pipeArray[1] = funcContext._outputPipe;
                    pipeArray[2] = context.ShellFunctionErrorOutputPipe;
                    pipeArray[3] = context.ExpressionWarningOutputPipe;
                    pipeArray[4] = context.ExpressionVerboseOutputPipe;
                    pipeArray[5] = context.ExpressionDebugOutputPipe;
                    funcContext._outputPipe = redirectionPipe;
                    context.ShellFunctionErrorOutputPipe = redirectionPipe;
                    context.ExpressionWarningOutputPipe = redirectionPipe;
                    context.ExpressionVerboseOutputPipe = redirectionPipe;
                    context.ExpressionDebugOutputPipe = redirectionPipe;
                    return pipeArray;

                case RedirectionStream.Output:
                    pipeArray[1] = funcContext._outputPipe;
                    funcContext._outputPipe = redirectionPipe;
                    return pipeArray;

                case RedirectionStream.Error:
                    pipeArray[(int) base.FromStream] = context.ShellFunctionErrorOutputPipe;
                    context.ShellFunctionErrorOutputPipe = redirectionPipe;
                    return pipeArray;

                case RedirectionStream.Warning:
                    pipeArray[(int) base.FromStream] = context.ExpressionWarningOutputPipe;
                    context.ExpressionWarningOutputPipe = redirectionPipe;
                    return pipeArray;

                case RedirectionStream.Verbose:
                    pipeArray[(int) base.FromStream] = context.ExpressionVerboseOutputPipe;
                    context.ExpressionVerboseOutputPipe = redirectionPipe;
                    return pipeArray;

                case RedirectionStream.Debug:
                    pipeArray[(int) base.FromStream] = context.ExpressionDebugOutputPipe;
                    context.ExpressionDebugOutputPipe = redirectionPipe;
                    return pipeArray;

                case RedirectionStream.Host:
                    return pipeArray;
            }
            return pipeArray;
        }
 internal ScriptBlockInvocationEventArgs(System.Management.Automation.ScriptBlock scriptBlock, bool useLocalScope, System.Management.Automation.ScriptBlock.ErrorHandlingBehavior errorHandlingBehavior, object dollarUnder, object input, object scriptThis, Pipe outputPipe, System.Management.Automation.InvocationInfo invocationInfo, params object[] args)
 {
     if (scriptBlock == null)
     {
         throw PSTraceSource.NewArgumentNullException("scriptBlock");
     }
     this.ScriptBlock = scriptBlock;
     this.OutputPipe = outputPipe;
     this.UseLocalScope = useLocalScope;
     this.ErrorHandlingBehavior = errorHandlingBehavior;
     this.DollarUnder = dollarUnder;
     this.Input = input;
     this.ScriptThis = scriptThis;
     this.InvocationInfo = invocationInfo;
     this.Args = args;
 }
Esempio n. 5
0
        internal void UnbindForExpression(FunctionContext funcContext, Pipe[] pipes)
        {
            if (pipes != null)
            {
                ExecutionContext context = funcContext._executionContext;
                switch (this.FromStream)
                {
                    case RedirectionStream.All:
                        funcContext._outputPipe = pipes[1];
                        context.ShellFunctionErrorOutputPipe = pipes[2];
                        context.ExpressionWarningOutputPipe = pipes[3];
                        context.ExpressionVerboseOutputPipe = pipes[4];
                        context.ExpressionDebugOutputPipe = pipes[5];
                        return;

                    case RedirectionStream.Output:
                        funcContext._outputPipe = pipes[1];
                        return;

                    case RedirectionStream.Error:
                        context.ShellFunctionErrorOutputPipe = pipes[(int) this.FromStream];
                        return;

                    case RedirectionStream.Warning:
                        context.ExpressionWarningOutputPipe = pipes[(int) this.FromStream];
                        return;

                    case RedirectionStream.Verbose:
                        context.ExpressionVerboseOutputPipe = pipes[(int) this.FromStream];
                        return;

                    case RedirectionStream.Debug:
                        context.ExpressionDebugOutputPipe = pipes[(int) this.FromStream];
                        return;

                    case RedirectionStream.Host:
                        return;
                }
            }
        }
Esempio n. 6
0
 private void CopyVariableToTempPipe(VariableStreamKind streamKind, List<IList> variableList, Pipe tempPipe)
 {
     if (variableList != null && variableList.Count > 0)
     {
         for (int i = 0; i < variableList.Count; i++)
         {
             tempPipe.AddVariableList(streamKind, variableList[i]);
         }
     }
 }
Esempio n. 7
0
 /// <summary>
 /// When a temporary pipe is used in the middle of execution, then we need to pass along
 /// the error and warning variable list to hold the errors and warnings get written out
 /// while the temporary pipe is being used.
 /// 
 /// We don't need to pass along the out variable list because we don't care about the output
 /// generated in the middle of execution.
 /// </summary>
 internal void SetVariableListForTemporaryPipe(Pipe tempPipe)
 {
     CopyVariableToTempPipe(VariableStreamKind.Error, _errorVariableList, tempPipe);
     CopyVariableToTempPipe(VariableStreamKind.Warning, _warningVariableList, tempPipe);
     CopyVariableToTempPipe(VariableStreamKind.Information, _informationVariableList, tempPipe);
 }
Esempio n. 8
0
 internal void LinkPipelineSuccessOutput(Pipe pipeToUse)
 {
     CommandProcessorBase base2 = this._commands[this._commands.Count - 1];
     if ((base2 == null) || (base2.CommandRuntime == null))
     {
         throw PSTraceSource.NewInvalidOperationException();
     }
     base2.CommandRuntime.OutputPipe = pipeToUse;
     this._linkedSuccessOutput = true;
 }
Esempio n. 9
0
 internal void LinkPipelineErrorOutput(Pipe pipeToUse)
 {
     for (int i = 0; i < this._commands.Count; i++)
     {
         CommandProcessorBase base2 = this._commands[i];
         if ((base2 == null) || (base2.CommandRuntime == null))
         {
             throw PSTraceSource.NewInvalidOperationException();
         }
         Pipe errorOutputPipe = base2.CommandRuntime.ErrorOutputPipe;
         if (base2.CommandRuntime.ErrorOutputPipe.DownstreamCmdlet == null)
         {
             base2.CommandRuntime.ErrorOutputPipe = pipeToUse;
         }
     }
     this._linkedErrorOutput = true;
 }
Esempio n. 10
0
 internal static void SetErrorVariables(IScriptExtent extent, RuntimeException rte, ExecutionContext context, Pipe outputPipe)
 {
     string newValue = null;
     Exception innerException = rte;
     int num = 0;
     while ((innerException != null) && (num++ < 10))
     {
         if (!string.IsNullOrEmpty(innerException.StackTrace))
         {
             newValue = innerException.StackTrace;
         }
         innerException = innerException.InnerException;
     }
     context.SetVariable(SpecialVariables.StackTraceVarPath, newValue);
     InterpreterError.UpdateExceptionErrorRecordPosition(rte, extent);
     ErrorRecord record = rte.ErrorRecord.WrapException(rte);
     if (!(rte is PipelineStoppedException))
     {
         if (outputPipe != null)
         {
             outputPipe.AppendVariableList(VariableStreamKind.Error, record);
         }
         context.AppendDollarError(record);
     }
 }
Esempio n. 11
0
 private static object GetExpressionValue(ExpressionAst expressionAst, System.Management.Automation.ExecutionContext context, SessionStateInternal sessionStateInternal, IList usingValues, ref Func<FunctionContext, object> lambda, ref IScriptExtent[] sequencePoints, ref Type localsTupleType)
 {
     object obj2;
     object obj4;
     if (IsConstantValueVisitor.IsConstant(expressionAst, out obj2, false, false))
     {
         return obj2;
     }
     VariableExpressionAst varAst = expressionAst as VariableExpressionAst;
     if (varAst != null)
     {
         return VariableOps.GetVariableValue(varAst.VariablePath, context, varAst);
     }
     if (lambda == null)
     {
         lambda = new Compiler().CompileSingleExpression(expressionAst, out sequencePoints, out localsTupleType);
     }
     SessionStateInternal engineSessionState = context.EngineSessionState;
     try
     {
         if ((sessionStateInternal != null) && (context.EngineSessionState != sessionStateInternal))
         {
             context.EngineSessionState = sessionStateInternal;
         }
         ArrayList resultList = new ArrayList();
         Pipe pipe = new Pipe(resultList);
         try
         {
             FunctionContext arg = new FunctionContext {
                 _sequencePoints = sequencePoints,
                 _executionContext = context,
                 _outputPipe = pipe,
                 _localsTuple = MutableTuple.MakeTuple(localsTupleType, DottedLocalsNameIndexMap)
             };
             if (usingValues != null)
             {
                 PSBoundParametersDictionary dictionary = new PSBoundParametersDictionary {
                     ImplicitUsingParameters = usingValues
                 };
                 arg._localsTuple.SetAutomaticVariable(AutomaticVariable.PSBoundParameters, dictionary, context);
             }
             object obj3 = lambda(arg);
             if (obj3 == AutomationNull.Value)
             {
                 return ((resultList.Count == 0) ? null : PipelineOps.PipelineResult(resultList));
             }
             obj4 = obj3;
         }
         catch (TargetInvocationException exception)
         {
             throw exception.InnerException;
         }
     }
     catch (TerminateException)
     {
         throw;
     }
     catch (FlowControlException)
     {
         obj4 = null;
     }
     finally
     {
         context.EngineSessionState = engineSessionState;
     }
     return obj4;
 }
Esempio n. 12
0
        } // private void SetResultPipe

        internal void LinkPipelineErrorOutput(Pipe pipeToUse)
        {
            Dbg.Assert(pipeToUse != null, "Caller should verify pipeToUse != null");

            for (int i = 0; i < _commands.Count; i++)
            {
                CommandProcessorBase commandProcessor = _commands[i];
                if (null == commandProcessor
                    || null == commandProcessor.CommandRuntime)
                {
                    // "null command or request or ErrorOutputPipe " + i
                    throw PSTraceSource.NewInvalidOperationException();
                }

                if (commandProcessor.CommandRuntime.ErrorOutputPipe.DownstreamCmdlet == null)
                {
                    commandProcessor.CommandRuntime.ErrorOutputPipe = pipeToUse;
                }
            }

            _linkedErrorOutput = true;
        }
Esempio n. 13
0
        private bool IsDownstreamOutDefault(Pipe downstreamPipe)
        {
            Diagnostics.Assert(downstreamPipe != null, "Caller makes sure the passed-in parameter is not null.");

            // Check if the downstream cmdlet is Out-Default, which is the default outputter.
            CommandProcessorBase outputProcessor = downstreamPipe.DownstreamCmdlet;
            if (outputProcessor != null)
            {
                // We have the test 'utscript\Engine\TestOutDefaultRedirection.ps1' to check that a user defined
                // Out-Default function should not cause a native command to be redirected. So here we should only 
                // compare the command name to avoid breaking change.
                if (String.Equals(outputProcessor.CommandInfo.Name, "Out-Default", StringComparison.OrdinalIgnoreCase))
                {
                    // Verify that this isn't an Out-Default added for transcribing
                    if (!outputProcessor.Command.MyInvocation.BoundParameters.ContainsKey("Transcript"))
                    {
                        return true;
                    }
                }
            }

            return false;
        }
Esempio n. 14
0
        } // private Array RetrieveResults

        /// <summary>
        /// Links this pipeline to a pre-existing Pipe object. This allows nested pipes
        /// to write into the parent pipeline. It does this by resetting the terminal
        /// pipeline object.
        /// </summary>
        /// <param name="pipeToUse">The pipeline to write success objects to</param>
        internal void LinkPipelineSuccessOutput(Pipe pipeToUse)
        {
            Dbg.Assert(pipeToUse != null, "Caller should verify pipeToUse != null");

            CommandProcessorBase LastCommandProcessor = _commands[_commands.Count - 1];
            if (null == LastCommandProcessor
                || null == LastCommandProcessor.CommandRuntime)
            {
                // "PipelineProcessor.RetrieveResults(): LastCommandProcessor == null"
                throw PSTraceSource.NewInvalidOperationException();
            }

            LastCommandProcessor.CommandRuntime.OutputPipe = pipeToUse;
            _linkedSuccessOutput = true;
        } // private void SetResultPipe
Esempio n. 15
0
 internal void InvokeWithPipeImpl(bool createLocalScope,
                                 Dictionary<string, ScriptBlock> functionsToDefine,
                                 List<PSVariable> 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);
 }
Esempio n. 16
0
        internal void InvokeWithPipeImpl(ScriptBlockClauseToInvoke clauseToInvoke,
                                                bool createLocalScope,
                                                Dictionary<string, ScriptBlock> functionsToDefine,
                                                List<PSVariable> 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;
            }

            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");

            if (context.CurrentPipelineStopping)
            {
                throw new PipelineStoppedException();
            }

            // 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");

            if (args == null)
            {
                args = Utils.EmptyArray<object>();
            }

            bool runOptimized = context._debuggingMode > 0 ? false : createLocalScope;
            var codeToInvoke = GetCodeToInvoke(ref runOptimized, clauseToInvoke);
            if (codeToInvoke == null)
                return;

            if (outputPipe == null)
            {
                // If we don't have a pipe to write to, we need to discard all results.
                outputPipe = new Pipe { NullPipe = true };
            }

            var locals = MakeLocalsTuple(runOptimized);

            if (dollarUnder != AutomationNull.Value)
            {
                locals.SetAutomaticVariable(AutomaticVariable.Underbar, dollarUnder, context);
            }
            if (input != AutomationNull.Value)
            {
                locals.SetAutomaticVariable(AutomaticVariable.Input, input, context);
            }
            if (scriptThis != AutomationNull.Value)
            {
                locals.SetAutomaticVariable(AutomaticVariable.This, scriptThis, context);
            }
            SetPSScriptRootAndPSCommandPath(locals, context);

            var oldShellFunctionErrorOutputPipe = context.ShellFunctionErrorOutputPipe;
            var oldExternalErrorOutput = context.ExternalErrorOutput;
            var oldScopeOrigin = context.EngineSessionState.CurrentScope.ScopeOrigin;
            var oldSessionState = context.EngineSessionState;

            // If the script block has a different language mode than the current,
            // change the language mode.
            PSLanguageMode? oldLanguageMode = null;
            PSLanguageMode? newLanguageMode = null;
            if ((this.LanguageMode.HasValue) &&
                (this.LanguageMode != context.LanguageMode))
            {
                oldLanguageMode = context.LanguageMode;
                newLanguageMode = this.LanguageMode;
            }

            Dictionary<string, PSVariable> backupWhenDotting = null;
            try
            {
                var myInvocationInfo = invocationInfo;
                if (myInvocationInfo == null)
                {
                    var callerFrame = context.Debugger.GetCallStack().LastOrDefault();
                    var extent = (callerFrame != null)
                        ? callerFrame.FunctionContext.CurrentPosition
                        : Ast.Extent;
                    myInvocationInfo = new InvocationInfo(null, extent, context);
                }

                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)
                {
                    case ErrorHandlingBehavior.WriteToCurrentErrorPipe:
                        // no need to do anything
                        break;
                    case ErrorHandlingBehavior.WriteToExternalErrorPipe:
                        context.ShellFunctionErrorOutputPipe = null;
                        break;
                    case ErrorHandlingBehavior.SwallowErrors:
                        context.ShellFunctionErrorOutputPipe = null;
                        context.ExternalErrorOutput = new DiscardingPipelineWriter();
                        break;
                }

                if (createLocalScope)
                {
                    var newScope = context.EngineSessionState.NewScope(false);
                    context.EngineSessionState.CurrentScope = newScope;
                    newScope.LocalsTuple = locals;
                    // Inject passed in functions into the scope
                    if (functionsToDefine != null)
                    {
                        foreach (var def in functionsToDefine)
                        {
                            if (string.IsNullOrWhiteSpace(def.Key))
                            {
                                PSInvalidOperationException e = PSTraceSource.NewInvalidOperationException(
                                    ParserStrings.EmptyFunctionNameInFunctionDefinitionDictionary);

                                e.SetErrorId("EmptyFunctionNameInFunctionDefinitionDictionary");
                                throw e;
                            }
                            if (def.Value == null)
                            {
                                PSInvalidOperationException e = PSTraceSource.NewInvalidOperationException(
                                    ParserStrings.NullFunctionBodyInFunctionDefinitionDictionary, def.Key);

                                e.SetErrorId("NullFunctionBodyInFunctionDefinitionDictionary");
                                throw e;
                            }
                            newScope.FunctionTable.Add(def.Key, new FunctionInfo(def.Key, def.Value, context));
                        }
                    }
                    // Inject passed in variables into the scope
                    if (variablesToDefine != null)
                    {
                        int index = 0;
                        foreach (var psvar in variablesToDefine)
                        {
                            // Check for null entries.
                            if (psvar == null)
                            {
                                PSInvalidOperationException e = PSTraceSource.NewInvalidOperationException(
                                    ParserStrings.NullEntryInVariablesDefinitionList, index);

                                e.SetErrorId("NullEntryInVariablesDefinitionList");
                                throw e;
                            }
                            string name = psvar.Name;
                            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);
                        }
                    }
                }
                else
                {
                    if (context.EngineSessionState.CurrentScope.LocalsTuple == null)
                    {
                        // If the locals tuple is, that means either:
                        //     * we're invoking a script block for a module
                        //     * something unexpected
                        context.EngineSessionState.CurrentScope.LocalsTuple = locals;
                    }
                    else
                    {
                        context.EngineSessionState.CurrentScope.DottedScopes.Push(locals);
                        backupWhenDotting = new Dictionary<string, PSVariable>();
                    }
                }

                // Set the language mode
                if (newLanguageMode.HasValue)
                {
                    context.LanguageMode = newLanguageMode.Value;
                }

                args = BindArgumentsForScriptblockInvoke(
                    (RuntimeDefinedParameter[])RuntimeDefinedParameters.Data,
                    args, context, !createLocalScope, backupWhenDotting, locals);
                locals.SetAutomaticVariable(AutomaticVariable.Args, args, context);

                context.EngineSessionState.CurrentScope.ScopeOrigin = CommandOrigin.Internal;

                var functionContext = new FunctionContext
                {
                    _executionContext = context,
                    _outputPipe = outputPipe,
                    _localsTuple = locals,
                    _scriptBlock = this,
                    _file = this.File,
                    _debuggerHidden = this.DebuggerHidden,
                    _debuggerStepThrough = this.DebuggerStepThrough,
                    _sequencePoints = SequencePoints,
                };

                ScriptBlock.LogScriptBlockStart(this, context.CurrentRunspace.InstanceId);

                try
                {
                    codeToInvoke(functionContext);
                }
                finally
                {
                    ScriptBlock.LogScriptBlockEnd(this, context.CurrentRunspace.InstanceId);
                }
            }
            catch (TargetInvocationException tie)
            {
                // DynamicInvoke always wraps, so unwrap here.
                throw tie.InnerException;
            }
            finally
            {
                // Restore the language mode
                if (oldLanguageMode.HasValue)
                {
                    context.LanguageMode = oldLanguageMode.Value;
                }

                // Now restore the output pipe...
                context.ShellFunctionErrorOutputPipe = oldShellFunctionErrorOutputPipe;
                context.ExternalErrorOutput = oldExternalErrorOutput;

                // Restore the interactive command state...
                context.EngineSessionState.CurrentScope.ScopeOrigin = oldScopeOrigin;

                if (createLocalScope)
                {
                    context.EngineSessionState.RemoveScope(context.EngineSessionState.CurrentScope);
                }
                else if (backupWhenDotting != null)
                {
                    context.EngineSessionState.CurrentScope.DottedScopes.Pop();

                    Diagnostics.Assert(backupWhenDotting != null, "when dotting, this dictionary isn't null");
                    foreach (var pair in backupWhenDotting)
                    {
                        if (pair.Value != null)
                        {
                            context.EngineSessionState.SetVariable(pair.Value, false, CommandOrigin.Internal);
                        }
                        else
                        {
                            context.EngineSessionState.RemoveVariable(pair.Key);
                        }
                    }
                }

                // Restore session state...
                context.EngineSessionState = oldSessionState;
            }
        }
Esempio n. 17
0
        internal void InvokeWithPipeImpl(bool createLocalScope, ScriptBlock.ErrorHandlingBehavior errorHandlingBehavior, object dollarUnder, object input, object scriptThis, Pipe outputPipe, InvocationInfo invocationInfo, object[] args)
        {
            bool flag;
            bool hasValue;
            ExecutionContext contextFromTLS = this.GetContextFromTLS();
            if (!contextFromTLS.CurrentPipelineStopping)
            {
                if (args == null)
                {
                    args = new object[0];
                }
                if (contextFromTLS._debuggingMode > 0)
                {
                    flag = false;
                }
                else
                {
                    flag = createLocalScope;
                }
                bool flag1 = flag;
                Action<FunctionContext> codeToInvoke = this.GetCodeToInvoke(ref flag1);
                if (codeToInvoke != null)
                {
                    if (outputPipe == null)
                    {
                        Pipe pipe = new Pipe();
                        pipe.NullPipe = true;
                        outputPipe = pipe;
                    }
                    MutableTuple mutableTuple = this.MakeLocalsTuple(flag1);
                    if (dollarUnder != AutomationNull.Value)
                    {
                        mutableTuple.SetAutomaticVariable(AutomaticVariable.Underbar, dollarUnder, contextFromTLS);
                    }
                    if (input != AutomationNull.Value)
                    {
                        mutableTuple.SetAutomaticVariable(AutomaticVariable.Input, input, contextFromTLS);
                    }
                    if (scriptThis != AutomationNull.Value)
                    {
                        mutableTuple.SetAutomaticVariable(AutomaticVariable.This, scriptThis, contextFromTLS);
                    }
                    this.SetPSScriptRootAndPSCommandPath(mutableTuple, contextFromTLS);
                    Pipe shellFunctionErrorOutputPipe = contextFromTLS.ShellFunctionErrorOutputPipe;
                    PipelineWriter externalErrorOutput = contextFromTLS.ExternalErrorOutput;
                    CommandOrigin scopeOrigin = contextFromTLS.EngineSessionState.CurrentScope.ScopeOrigin;
                    SessionStateInternal engineSessionState = contextFromTLS.EngineSessionState;
                    PSLanguageMode? nullable = null;
                    PSLanguageMode? languageMode = null;
                    PSLanguageMode? languageMode1 = this.LanguageMode;
                    if (languageMode1.HasValue)
                    {
                        PSLanguageMode? nullable1 = this.LanguageMode;
                        PSLanguageMode pSLanguageMode = contextFromTLS.LanguageMode;
                        if (nullable1.GetValueOrDefault() != pSLanguageMode)
                        {
                            hasValue = true;
                        }
                        else
                        {
                            hasValue = !nullable1.HasValue;
                        }
                        if (hasValue)
                        {
                            nullable = new PSLanguageMode?(contextFromTLS.LanguageMode);
                            languageMode = this.LanguageMode;
                        }
                    }
                    Dictionary<string, PSVariable> strs = null;
                    try
                    {
                        try
                        {
                            InvocationInfo invocationInfo1 = invocationInfo;
                            if (invocationInfo1 == null)
                            {
                                invocationInfo1 = new InvocationInfo(null, ((Ast)this._ast).Extent, contextFromTLS);
                            }
                            mutableTuple.SetAutomaticVariable(AutomaticVariable.MyInvocation, invocationInfo1, contextFromTLS);
                            if (this.SessionStateInternal != null)
                            {
                                contextFromTLS.EngineSessionState = this.SessionStateInternal;
                            }
                            ScriptBlock.ErrorHandlingBehavior errorHandlingBehavior1 = errorHandlingBehavior;
                            switch (errorHandlingBehavior1)
                            {
                                case ScriptBlock.ErrorHandlingBehavior.WriteToCurrentErrorPipe:
                                    {
                                        WriteToCurrentErrorPipe(createLocalScope, outputPipe, ref args, contextFromTLS, codeToInvoke, mutableTuple, languageMode, ref strs);
                                        break;
                                    }
                                case ScriptBlock.ErrorHandlingBehavior.WriteToExternalErrorPipe:
                                    {
                                        contextFromTLS.ShellFunctionErrorOutputPipe = null;
                                        WriteToCurrentErrorPipe(createLocalScope, outputPipe, ref args, contextFromTLS, codeToInvoke, mutableTuple, languageMode, ref strs);
                                        break;
                                    }
                                case ScriptBlock.ErrorHandlingBehavior.SwallowErrors:
                                    {
                                        contextFromTLS.ShellFunctionErrorOutputPipe = null;
                                        contextFromTLS.ExternalErrorOutput = new DiscardingPipelineWriter();
                                        WriteToCurrentErrorPipe(createLocalScope, outputPipe, ref args, contextFromTLS, codeToInvoke, mutableTuple, languageMode, ref strs);
                                        break;
                                    }
                                default:
                                    {
                                        WriteToCurrentErrorPipe(createLocalScope, outputPipe, ref args, contextFromTLS, codeToInvoke, mutableTuple, languageMode, ref strs);
                                        break;
                                    }
                            }
                        }
                        catch (TargetInvocationException targetInvocationException1)
                        {
                            TargetInvocationException targetInvocationException = targetInvocationException1;
                            throw targetInvocationException.InnerException;
                        }
                    }
					catch(Exception ex)
					{
						var msg = ex.Message;
					}
                    finally
                    {
                        if (nullable.HasValue)
                        {
                            contextFromTLS.LanguageMode = nullable.Value;
                        }
                        contextFromTLS.ShellFunctionErrorOutputPipe = shellFunctionErrorOutputPipe;
                        contextFromTLS.ExternalErrorOutput = externalErrorOutput;
                        contextFromTLS.EngineSessionState.CurrentScope.ScopeOrigin = scopeOrigin;
                        if (!createLocalScope)
                        {
                            if (strs != null)
                            {
                                contextFromTLS.EngineSessionState.CurrentScope.DottedScopes.Pop();
                                foreach (KeyValuePair<string, PSVariable> str in strs)
                                {
                                    if (str.Value == null)
                                    {
                                        contextFromTLS.EngineSessionState.RemoveVariable(str.Key);
                                    }
                                    else
                                    {
                                        contextFromTLS.EngineSessionState.SetVariable(str.Value, false, CommandOrigin.Internal);
                                    }
                                }
                            }
                        }
                        else
                        {
                            contextFromTLS.EngineSessionState.RemoveScope(contextFromTLS.EngineSessionState.CurrentScope);
                        }
                        contextFromTLS.EngineSessionState = engineSessionState;
                    }
                    return;
                }
                else
                {
                    return;
                }
            }
            else
            {
                throw new PipelineStoppedException();
            }
        }
Esempio n. 18
0
 public PSModuleInfo(ScriptBlock scriptBlock)
 {
     this._name = string.Empty;
     this._path = string.Empty;
     this._description = string.Empty;
     this._version = new System.Version(0, 0);
     this._detectedFunctionExports = new List<string>();
     this._detectedWorkflowExports = new List<string>();
     this._detectedCmdletExports = new List<string>();
     this._compiledExports = new List<CmdletInfo>();
     this._fileList = new List<string>();
     this._moduleList = new Collection<object>();
     this._nestedModules = new List<PSModuleInfo>();
     this._scripts = new List<string>();
     this._requiredAssemblies = new Collection<string>();
     this._requiredModules = new List<PSModuleInfo>();
     this._requiredModulesSpecification = new List<ModuleSpecification>();
     this._detectedAliasExports = new Dictionary<string, string>();
     this._exportedFormatFiles = new ReadOnlyCollection<string>(new List<string>());
     this._exportedTypeFiles = new ReadOnlyCollection<string>(new List<string>());
     if (scriptBlock == null)
     {
         throw PSTraceSource.NewArgumentException("scriptBlock");
     }
     ExecutionContext executionContextFromTLS = LocalPipeline.GetExecutionContextFromTLS();
     if (executionContextFromTLS == null)
     {
         throw new InvalidOperationException("PSModuleInfo");
     }
     SetDefaultDynamicNameAndPath(this);
     this._sessionState = new System.Management.Automation.SessionState(executionContextFromTLS, true, true);
     this._sessionState.Internal.Module = this;
     SessionStateInternal engineSessionState = executionContextFromTLS.EngineSessionState;
     try
     {
         executionContextFromTLS.EngineSessionState = this._sessionState.Internal;
         executionContextFromTLS.SetVariable(SpecialVariables.PSScriptRootVarPath, this._path);
         scriptBlock = scriptBlock.Clone(true);
         scriptBlock.SessionState = this._sessionState;
         Pipe outputPipe = new Pipe {
             NullPipe = true
         };
         scriptBlock.InvokeWithPipe(false, ScriptBlock.ErrorHandlingBehavior.WriteToCurrentErrorPipe, AutomationNull.Value, AutomationNull.Value, AutomationNull.Value, outputPipe, null, new object[0]);
     }
     finally
     {
         executionContextFromTLS.EngineSessionState = engineSessionState;
     }
 }
Esempio n. 19
0
 internal object InvokeAsDelegateHelper(object dollarUnder, object dollarThis, object[] args)
 {
     ExecutionContext contextFromTLS = this.GetContextFromTLS();
     ArrayList arrayLists = new ArrayList();
     Pipe pipe = new Pipe(arrayLists);
     this.InvokeWithPipe(true, ScriptBlock.ErrorHandlingBehavior.WriteToCurrentErrorPipe, dollarUnder, null, dollarThis, pipe, null, args);
     return ScriptBlock.GetRawResult(arrayLists);
 }
Esempio n. 20
0
 internal void InvokeWithPipe(bool useLocalScope, ScriptBlock.ErrorHandlingBehavior errorHandlingBehavior, object dollarUnder, object input, object scriptThis, Pipe outputPipe, InvocationInfo invocationInfo, object[] args)
 {
     bool flag;
     Action action = null;
     ExecutionContext contextFromTLS = this.GetContextFromTLS();
     if (this.SessionStateInternal == null || this.SessionStateInternal.ExecutionContext == contextFromTLS)
     {
         RunspaceBase currentRunspace = (RunspaceBase)contextFromTLS.CurrentRunspace;
         RunspaceBase runspaceBase = currentRunspace;
         if (action == null)
         {
             action = () => this.InvokeWithPipeImpl(useLocalScope, errorHandlingBehavior, dollarUnder, input, scriptThis, outputPipe, invocationInfo, args);
         }
         flag = !runspaceBase.RunActionIfNoRunningPipelinesWithThreadCheck(action);
     }
     else
     {
         contextFromTLS = this.SessionStateInternal.ExecutionContext;
         flag = true;
     }
     if (flag)
     {
         contextFromTLS.Events.SubscribeEvent(null, "PowerShell.OnScriptBlockInvoke", "PowerShell.OnScriptBlockInvoke", null, new PSEventReceivedEventHandler(ScriptBlock.OnScriptBlockInvokeEventHandler), true, false, true, 1);
         ScriptBlockInvocationEventArgs scriptBlockInvocationEventArg = new ScriptBlockInvocationEventArgs(this, useLocalScope, errorHandlingBehavior, dollarUnder, input, scriptThis, outputPipe, invocationInfo, args);
         object[] objArray = new object[1];
         objArray[0] = scriptBlockInvocationEventArg;
         contextFromTLS.Events.GenerateEvent("PowerShell.OnScriptBlockInvoke", null, objArray, null, true, true);
         if (scriptBlockInvocationEventArg.Exception != null)
         {
             throw scriptBlockInvocationEventArg.Exception;
         }
     }
 }
Esempio n. 21
0
 internal object DoInvokeReturnAsIs(bool useLocalScope, ScriptBlock.ErrorHandlingBehavior errorHandlingBehavior, object dollarUnder, object input, object scriptThis, object[] args)
 {
     ArrayList arrayLists = new ArrayList();
     Pipe pipe = new Pipe(arrayLists);
     this.InvokeWithPipe(useLocalScope, errorHandlingBehavior, dollarUnder, input, scriptThis, pipe, null, args);
     return ScriptBlock.GetRawResult(arrayLists);
 }
Esempio n. 22
0
 internal Collection<PSObject> DoInvoke(object dollarUnder, object input, object[] args)
 {
     ArrayList arrayLists = new ArrayList();
     Pipe pipe = new Pipe(arrayLists);
     this.InvokeWithPipe(true, ScriptBlock.ErrorHandlingBehavior.WriteToExternalErrorPipe, dollarUnder, input, AutomationNull.Value, pipe, null, args);
     return ScriptBlock.GetWrappedResult(arrayLists);
 }
Esempio n. 23
0
 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);
 }
Esempio n. 24
0
 internal static void FlushPipe(Pipe oldPipe, ArrayList arrayList)
 {
     foreach (object obj2 in arrayList)
     {
         oldPipe.Add(obj2);
     }
 }
Esempio n. 25
-1
        private static object GetExpressionValue(ExpressionAst expressionAst,
                                                 bool isTrustedInput,
                                                 ExecutionContext context,
                                                 SessionStateInternal sessionStateInternal,
                                                 IDictionary usingValues,
                                                 ref Func<FunctionContext, object> lambda,
                                                 ref IScriptExtent[] sequencePoints,
                                                 ref Type localsTupleType)
        {
            object constantValue;
            if (IsConstantValueVisitor.IsConstant(expressionAst, out constantValue))
            {
                return constantValue;
            }

            // If this isn't trusted input, then just return.
            if (!isTrustedInput)
            {
                return null;
            }

            // Can't be exposed to untrusted input - exposing private variable names / etc. could be
            // information disclosure.
            var variableAst = expressionAst as VariableExpressionAst;
            if (variableAst != null)
            {
                // We can avoid creating a lambda for the common case of a simple variable expression.
                return VariableOps.GetVariableValue(variableAst.VariablePath, context, variableAst);
            }

            // Can't be exposed to untrusted input - invoking arbitrary code could result in remote code
            // execution.
            if (lambda == null)
            {
                lambda = (new Compiler()).CompileSingleExpression(expressionAst, out sequencePoints, out localsTupleType);
            }

            SessionStateInternal oldSessionState = context.EngineSessionState;
            try
            {
                if (sessionStateInternal != null && context.EngineSessionState != sessionStateInternal)
                {
                    // If we're running a function from a module, we need to evaluate the initializers in the
                    // module context, not the callers context...
                    context.EngineSessionState = sessionStateInternal;
                }

                var resultList = new List<object>();
                var pipe = new Pipe(resultList);
                try
                {
                    var functionContext = new FunctionContext
                    {
                        _sequencePoints = sequencePoints,
                        _executionContext = context,
                        _file = expressionAst.Extent.File,
                        _outputPipe = pipe,
                        _localsTuple = MutableTuple.MakeTuple(localsTupleType, DottedLocalsNameIndexMap)
                    };
                    if (usingValues != null)
                    {
                        var boundParameters = new PSBoundParametersDictionary { ImplicitUsingParameters = usingValues };
                        functionContext._localsTuple.SetAutomaticVariable(AutomaticVariable.PSBoundParameters, boundParameters, context);
                    }
                    var result = lambda(functionContext);
                    if (result == AutomationNull.Value)
                    {
                        return resultList.Count == 0 ? null : PipelineOps.PipelineResult(resultList);
                    }
                    return result;
                }
                catch (TargetInvocationException tie)
                {
                    throw tie.InnerException;
                }
            }
            catch (TerminateException)
            {
                // the debugger is terminating the execution; bubble up the exception
                throw;
            }
            catch (FlowControlException)
            {
                // ignore break, continue and return exceptions
                return null;
            }
            finally
            {
                context.EngineSessionState = oldSessionState;
            }
        }