Пример #1
0
        public IEnumerable <TResult> ExecuteCommandInDebugger <TResult>(
            PowerShellContext powerShellContext,
            Runspace currentRunspace,
            PSCommand psCommand,
            bool sendOutputToHost)
        {
            PSDataCollection <PSObject> outputCollection = new PSDataCollection <PSObject>();

#if !PowerShellv3
            if (sendOutputToHost)
            {
                outputCollection.DataAdded +=
                    (obj, e) =>
                {
                    for (int i = e.Index; i < outputCollection.Count; i++)
                    {
                        powerShellContext.WriteOutput(
                            outputCollection[i].ToString(),
                            true);
                    }
                };
            }

            DebuggerCommandResults commandResults =
                currentRunspace.Debugger.ProcessCommand(
                    psCommand,
                    outputCollection);
#endif

            return
                (outputCollection
                 .Select(pso => pso.BaseObject)
                 .Cast <TResult>());
        }
 public void ProcessDebuggerResult(DebuggerCommandResults debuggerResult)
 {
     if (debuggerResult?.ResumeAction is not null)
     {
         SetDebugResuming(debuggerResult.ResumeAction.Value);
         RaiseDebuggerResumingEvent(new DebuggerResumingEventArgs(debuggerResult.ResumeAction.Value));
     }
 }
Пример #3
0
        public IEnumerable <TResult> ExecuteCommandInDebugger <TResult>(
            PowerShellContext powerShellContext,
            Runspace currentRunspace,
            PSCommand psCommand,
            bool sendOutputToHost,
            out DebuggerResumeAction?debuggerResumeAction)
        {
            debuggerResumeAction = null;
            PSDataCollection <PSObject> outputCollection = new PSDataCollection <PSObject>();

#if !PowerShellv3
            if (sendOutputToHost)
            {
                outputCollection.DataAdded +=
                    (obj, e) =>
                {
                    for (int i = e.Index; i < outputCollection.Count; i++)
                    {
                        powerShellContext.WriteOutput(
                            outputCollection[i].ToString(),
                            true);
                    }
                };
            }

            DebuggerCommandResults commandResults =
                currentRunspace.Debugger.ProcessCommand(
                    psCommand,
                    outputCollection);

            // Pass along the debugger's resume action if the user's
            // command caused one to be returned
            debuggerResumeAction = commandResults.ResumeAction;
#endif

            IEnumerable <TResult> results = null;
            if (typeof(TResult) != typeof(PSObject))
            {
                results =
                    outputCollection
                    .Select(pso => pso.BaseObject)
                    .Cast <TResult>();
            }
            else
            {
                results = outputCollection.Cast <TResult>();
            }

            return(results);
        }
 private void RefreshCallStack40()
 {
     ServiceCommon.Log("Debuggger stopped, let us retreive all call stack frames");
     if (_runspace.ConnectionInfo != null)
     {
         PSCommand psCommand = new PSCommand();
         psCommand.AddScript("Get-PSCallstack");
         var output = new PSDataCollection <PSObject>();
         DebuggerCommandResults results = _runspace.Debugger.ProcessCommand(psCommand, output);
         _callstack = output;
     }
     else
     {
         RefreshCallStack();
     }
 }
 private void RefreshScopedVariable40()
 {
     ServiceCommon.Log("Debuggger stopped, let us retreive all local variable in scope");
     if (_runspace.ConnectionInfo != null)
     {
         PSCommand psCommand = new PSCommand();
         psCommand.AddScript("Get-Variable");
         var output = new PSDataCollection <PSObject>();
         DebuggerCommandResults results = _runspace.Debugger.ProcessCommand(psCommand, output);
         _varaiables = output;
     }
     else
     {
         RefreshScopedVariable();
     }
 }
        // Method to handle the Debugger DebuggerStop event.
        // The debugger will remain in debugger stop mode until this event
        // handler returns, at which time DebuggerStopEventArgs.ResumeAction should
        // be set to indicate how the debugger should proceed (Continue, StepInto,
        // StepOut, StepOver, Stop).
        // This handler should run a REPL (Read Evaluate Print Loop) to allow user
        // to investigate the state of script execution, by processing user commands
        // with the Debugger.ProcessCommand method.  If a user command releases the
        // debugger then the DebuggerStopEventArgs.ResumeAction is set and this
        // handler returns.
        private void HandleDebuggerStopEvent(object sender, DebuggerStopEventArgs args)
        {
            Debugger             debugger     = sender as Debugger;
            DebuggerResumeAction?resumeAction = null;

            // Display messages pertaining to this debugger stop.
            WriteDebuggerStopMessages(args);

            // Simple REPL (Read Evaluate Print Loop) to process
            // Debugger commands.
            while (resumeAction == null)
            {
                // Write debug prompt.
                Console.Write("[DBG] PS >> ");
                string command = Console.ReadLine();
                Console.WriteLine();

                // Stream output from command processing to console.
                var output = new PSDataCollection <PSObject>();
                output.DataAdded += (dSender, dArgs) =>
                {
                    foreach (var item in output.ReadAll())
                    {
                        Console.WriteLine(item);
                    }
                };

                // Process command.
                // The Debugger.ProcesCommand method will parse and handle debugger specific
                // commands such as 'h' (help), 'list', 'stepover', etc.  If the command is
                // not specific to the debugger then it will be evaluated as a PowerShell
                // command or script.  The returned DebuggerCommandResults object will indicate
                // whether the command was evaluated by the debugger and if the debugger should
                // be released with a specific resume action.
                PSCommand psCommand = new PSCommand();
                psCommand.AddScript(command).AddCommand("Out-String").AddParameter("Stream", true);
                DebuggerCommandResults results = debugger.ProcessCommand(psCommand, output);
                if (results.ResumeAction != null)
                {
                    resumeAction = results.ResumeAction;
                }
            }

            // Return from event handler with user resume action.
            args.ResumeAction = resumeAction.Value;
        }
Пример #7
0
        private DebuggerCommandResults RunDebuggerCommand(Debugger debugger, string command)
        {
            var output = new PSDataCollection <PSObject>();

            output.DataAdded += (dSender, dArgs) =>
            {
                foreach (var item in output.ReadAll())
                {
                    UserIOImpl.PrintMessage(item.ToString() + "\n");
                }
            };

            PSCommand psCommand = new PSCommand();

            psCommand.AddScript(command);
            DebuggerCommandResults results = debugger.ProcessCommand(psCommand, output);

            return(results);
        }
        public void ProcessDebuggerResult(DebuggerCommandResults debuggerResult)
        {
            if (debuggerResult?.ResumeAction is not null)
            {
                // Since we're processing a command like 'c' or 's' remotely, we need to tell the
                // host to stop the remote REPL loop.
                if (debuggerResult.ResumeAction is not DebuggerResumeAction.Stop || _psesHost.CurrentFrame.IsRemote)
                {
                    _psesHost.ForceSetExit();
                }

                SetDebugResuming(debuggerResult.ResumeAction.Value);
                RaiseDebuggerResumingEvent(new DebuggerResumingEventArgs(debuggerResult.ResumeAction.Value));

                // The Terminate exception is used by the engine for flow control
                // when it needs to unwind the callstack out of the debugger.
                if (debuggerResult.ResumeAction is DebuggerResumeAction.Stop)
                {
                    throw new TerminateException();
                }
            }
        }
Пример #9
0
        private bool CheckVariables(Debugger debugger)
        {
            bool updatedVariable  = false;
            var  processVariables = new PSDataCollection <PSObject>();

            processVariables.DataAdded += (dSender, dArgs) =>
            {
                foreach (PSObject item in processVariables.ReadAll())
                {
                    if (item.ImmediateBaseObject is PSVariable)
                    {
                        PSVariable psv = (PSVariable)item.ImmediateBaseObject;

                        if (
                            !VariableMap.ContainsKey(psv.Name) ||
                            (
                                VariableMap[psv.Name] != null &&
                                VariableMap[psv.Name].ToString() != psv.Value.ToString()
                            )
                            )
                        {
                            DumpVariable(psv.Name, psv.Value);
                        }

                        if (VariableReplaceMap != null && VariableReplaceMap.ContainsKey(psv.Name))
                        {
                            if (psv.Value.ToString() != VariableReplaceMap[psv.Name])
                            {
                                UserIOImpl.PrintMessage(@"Updated variable " + psv.Name + ": " + psv.Value + " --> " + VariableReplaceMap[psv.Name], "Red");
                                psv.Value       = VariableReplaceMap[psv.Name];
                                updatedVariable = true;
                            }
                        }

                        VariableMap[psv.Name] = psv.Value;
                    }
                    else if (item.ImmediateBaseObject is ErrorRecord)
                    {
                        ErrorRecord errorRecord = (ErrorRecord)item.ImmediateBaseObject;

                        UserIOImpl.PrintMessage(@"* item: " + item.ImmediateBaseObject.GetType() + "\n");

                        if (errorRecord != null && errorRecord.ErrorDetails != null)
                        {
                            UserIOImpl.PrintMessage(errorRecord.ErrorDetails.Message + "\n");
                        }
                    }
                    else
                    {
                        UserIOImpl.PrintMessage(@"* item: " + item.ImmediateBaseObject.GetType());
                    }
                }
            };

            PSCommand psCommand = new PSCommand();

            psCommand.AddScript("Get-Variable");
            DebuggerCommandResults results = debugger.ProcessCommand(psCommand, processVariables);

            return(updatedVariable);
        }
Пример #10
0
        private void DebuggerOnDebuggerStop(object sender, DebuggerStopEventArgs args)
        {
            Debugger             debugger     = sender as Debugger;
            DebuggerResumeAction?resumeAction = null;

            DebuggingInBreakpoint = true;
            try
            {
                if (
                    ((ScriptingHostUserInterface)host.UI).CheckSessionCanDoInteractiveAction(
                        nameof(DebuggerOnDebuggerStop), false))
                {
                    var output = new PSDataCollection <PSObject>();
                    output.DataAdded += (dSender, dArgs) =>
                    {
                        foreach (var item in output.ReadAll())
                        {
                            host.UI.WriteLine(item.ToString());
                        }
                    };

                    var message = Message.Parse(this, "ise:breakpointhit");
                    //var position = args.InvocationInfo.DisplayScriptPosition;
                    IScriptExtent position;
                    try
                    {
                        position = args.InvocationInfo.GetType()
                                   .GetProperty("ScriptPosition",
                                                BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.GetProperty)
                                   .GetValue(args.InvocationInfo) as IScriptExtent;
                    }
                    catch (Exception)
                    {
                        position = args.InvocationInfo.DisplayScriptPosition;
                    }

                    if (position != null)
                    {
                        message.Arguments.Add("Line", (position.StartLineNumber - 1).ToString());
                        message.Arguments.Add("Column", (position.StartColumnNumber - 1).ToString());
                        message.Arguments.Add("EndLine", (position.EndLineNumber - 1).ToString());
                        message.Arguments.Add("EndColumn", (position.EndColumnNumber - 1).ToString());
                    }
                    else
                    {
                        message.Arguments.Add("Line", (args.InvocationInfo.ScriptLineNumber - 1).ToString());
                        message.Arguments.Add("Column", (args.InvocationInfo.OffsetInLine - 1).ToString());
                        message.Arguments.Add("EndLine", (args.InvocationInfo.ScriptLineNumber).ToString());
                        message.Arguments.Add("EndColumn", (0).ToString());
                    }

                    message.Arguments.Add("HitCount",
                                          args.Breakpoints.Count > 0 ? args.Breakpoints[0].HitCount.ToString() : "1");
                    SendUiMessage(message);

                    while (resumeAction == null && !abortRequested)
                    {
                        if (ImmediateCommand is string commandString)
                        {
                            PowerShellLog.Info($"Executing a debug command in ScriptSession '{Key}'.");
                            PowerShellLog.Debug(commandString);
                            DebuggerCommandResults results = null;
                            try
                            {
                                var psCommand     = new PSCommand();
                                var scriptCommand = new Command(commandString, true)
                                {
                                    MergeUnclaimedPreviousCommandResults = PipelineResultTypes.Warning
                                };
                                psCommand.AddCommand(scriptCommand)
                                .AddCommand(OutDefaultCommand);

                                results          = debugger?.ProcessCommand(psCommand, output);
                                ImmediateResults = output;
                                LogErrors(null, output.ToList());
                            }
                            catch (Exception ex)
                            {
                                PowerShellLog.Error("Error while executing Debugging command.", ex);
                                ImmediateCommand = null;
                                host.UI.WriteErrorLine(GetExceptionString(ex, ExceptionStringFormat.Default));
                            }

                            if (results?.ResumeAction != null)
                            {
                                resumeAction = results.ResumeAction;
                            }
                            ImmediateCommand = null;
                        }
                        else
                        {
                            Thread.Sleep(20);
                        }
                    }


                    args.ResumeAction = resumeAction ?? DebuggerResumeAction.Continue;
                }
            }
            finally
            {
                DebuggingInBreakpoint = false;
            }
        }
Пример #11
0
        private IEnumerable <TResult> ExecuteCommandInDebugger <TResult>(PSCommand psCommand, bool sendOutputToHost)
        {
            IEnumerable <TResult> executionResult = null;

            if (PowerShellVersion >= new Version(4, 0))
            {
#if PowerShellv4 || PowerShellv5
                PSDataCollection <PSObject> outputCollection = new PSDataCollection <PSObject>();

                if (sendOutputToHost)
                {
                    outputCollection.DataAdded +=
                        (obj, e) =>
                    {
                        for (int i = e.Index; i < outputCollection.Count; i++)
                        {
                            this.WriteOutput(outputCollection[i].ToString(), true);
                        }
                    };
                }

                DebuggerCommandResults commandResults =
                    this.currentRunspace.Debugger.ProcessCommand(
                        psCommand,
                        outputCollection);

                // If the command was a debugger action, run it
                if (commandResults.ResumeAction.HasValue)
                {
                    this.ResumeDebugger(commandResults.ResumeAction.Value);
                }

                executionResult =
                    outputCollection
                    .Select(pso => pso.BaseObject)
                    .Cast <TResult>();
#endif
            }
            else
            {
                using (var nestedPipeline = this.currentRunspace.CreateNestedPipeline())
                {
                    foreach (var command in psCommand.Commands)
                    {
                        nestedPipeline.Commands.Add(command);
                    }

                    executionResult =
                        nestedPipeline
                        .Invoke()
                        .Select(pso => pso.BaseObject)
                        .Cast <TResult>();
                }

                // Write the output to the host if necessary
                if (sendOutputToHost)
                {
                    foreach (var line in executionResult)
                    {
                        this.WriteOutput(line.ToString(), true);
                    }
                }
            }

            return(executionResult);
        }