示例#1
0
        // Show debug dialog
        void OnDebuggerStop(object sender, DebuggerStopEventArgs e)
        {
            var ui = new UI.DebuggerDialog(e);

            // viewer writer?
            var writer = FarUI.Writer as TranscriptOutputWriter;

            // no? if console writer and transcript then use transcript
            if (writer == null && FarUI.Writer is ConsoleOutputWriter && Transcript != null)
            {
                writer = Transcript;
            }

            // add View handler
            if (writer != null)
            {
                ui.OnView = delegate
                {
                    // ensure file
                    if (writer.FileName == null)
                    {
                        writer.Write(string.Empty);
                    }

                    // view file
                    Zoo.StartExternalViewer(writer.FileName);
                };
            }

            e.ResumeAction = ui.Show();
        }
示例#2
0
        async void DebugService_DebuggerStopped(object sender, DebuggerStopEventArgs e)
        {
            // Flush pending output before sending the event
            await this.outputDebouncer.Flush();

            // Provide the reason for why the debugger has stopped script execution.
            // See https://github.com/Microsoft/vscode/issues/3648
            // The reason is displayed in the breakpoints viewlet.  Some recommended reasons are:
            // "step", "breakpoint", "function breakpoint", "exception" and "pause".
            // We don't support exception breakpoints and for "pause", we can't distinguish
            // between stepping and the user pressing the pause/break button in the debug toolbar.
            string debuggerStoppedReason = "step";

            if (e.Breakpoints.Count > 0)
            {
                debuggerStoppedReason =
                    e.Breakpoints[0] is CommandBreakpoint
                        ? "function breakpoint"
                        : "breakpoint";
            }

            await this.SendEvent(
                StoppedEvent.Type,
                new StoppedEventBody
            {
                Source = new Source
                {
                    Path = e.InvocationInfo.ScriptName,
                },
                Line     = e.InvocationInfo.ScriptLineNumber,
                Column   = e.InvocationInfo.OffsetInLine,
                ThreadId = 1,     // TODO: Change this based on context
                Reason   = debuggerStoppedReason
            });
        }
示例#3
0
        private void OnDebugStopped(object sender, DebuggerStopEventArgs e)
        {
            var lineNumber = e.InvocationInfo.ScriptLineNumber - 2;

            // Notify the UI
            DebuggerStopped?.Invoke(this, new DebugEventArgs(lineNumber, _editorSession.DebugService.GetStackFrames()));
        }
        void Debugger_DebuggerStop(object sender, DebuggerStopEventArgs e)
        {
            Log.InfoFormat("Debugger stopped");

            if (CurrentExecutingNode == null)
            {
                return;
            }

            RefreshScopedVariables();
            RefreshCallStack();

            if (e.Breakpoints.Count == 0 || !ProcessLineBreakpoints(e))
            {
                if (DebuggerPaused != null)
                {
                    var scriptLocation = new ScriptLocation();
                    scriptLocation.File   = e.InvocationInfo.ScriptName;
                    scriptLocation.Line   = e.InvocationInfo.ScriptLineNumber;
                    scriptLocation.Column = 0;

                    DebuggerPaused(this, new EventArgs <ScriptLocation>(scriptLocation));
                }
            }

            Log.Debug("Waiting for debuggee to resume.");

            //Wait for the user to step, continue or stop
            _pausedEvent.WaitOne();
            Log.DebugFormat("Debuggee resume action is {0}", _resumeAction);
            e.ResumeAction = _resumeAction;
        }
        private bool ProcessLineBreakpoints(DebuggerStopEventArgs e)
        {
            Log.InfoFormat("Process Line Breapoints");

            var lbp = e.Breakpoints[0] as LineBreakpoint;

            if (lbp != null)
            {
                var bp =
                    _breakpoints.FirstOrDefault(
                        m =>
                        m.Column == lbp.Column && lbp.Line == m.Line &&
                        lbp.Script.Equals(m.File, StringComparison.InvariantCultureIgnoreCase));

                if (bp != null)
                {
                    if (BreakpointHit != null)
                    {
                        Log.InfoFormat("Breakpoint @ {0} {1} {2} was hit.", bp.File, bp.Line, bp.Column);
                        BreakpointHit(this, new EventArgs <ScriptBreakpoint>(bp));
                        return(true);
                    }
                }
            }

            return(false);
        }
示例#6
0
        private void HandleDebuggerStopEvent(object sender, DebuggerStopEventArgs args)
        {
            Debugger             debugger     = sender as Debugger;
            DebuggerResumeAction?resumeAction = null;

            if (!ShowHelpMessage)
            {
                UserIOImpl.PrintMessage("Entering debug mode. Type 'h' to get help.\n");
                ShowHelpMessage = true;
            }

            CheckVariables(debugger);
            PrintCurrentCode(args);

            while (resumeAction == null)
            {
                if (CommandCount > 0)
                {
                    resumeAction = RunDebuggerCommand(debugger, Command)?.ResumeAction;
                    CommandCount--;
                }
                else
                {
                    string   commandLine = UserIOImpl.GetInput("PowerShellRunBox>> ");
                    string[] commandArgs = commandLine.Split(' ');

                    if (commandArgs.Length <= 0)
                    {
                        continue;
                    }

                    if (commandArgs[0] == "s")
                    {
                        Command = commandArgs[0];

                        if (commandArgs.Length > 1)
                        {
                            CommandCount = Convert.ToInt32(commandArgs[1]);
                        }
                    }
                    else
                    {
                        Command = commandLine;
                    }

                    resumeAction = RunDebuggerCommand(debugger, Command)?.ResumeAction;
                }
            }

            // DebuggerStopEventArgs.ResumeAction:
            //  - Continue      Continue execution until next breakpoint is hit.
            //  - StepInto      Step into function.
            //  - StepOut       Step out of function.
            //  - StepOver      Step over function.
            //  - Stop          Stop debugging.
            args.ResumeAction = resumeAction.Value;
        }
        private async void OnDebuggerStop(object sender, DebuggerStopEventArgs e)
        {
            // Get call stack and variables.
            await this.FetchStackFramesAndVariables();

            // Notify the host that the debugger is stopped
            if (this.DebuggerStopped != null)
            {
                this.DebuggerStopped(sender, e);
            }
        }
示例#8
0
        private async void OnDebuggerStop(object sender, DebuggerStopEventArgs e)
        {
            var lineNumber = e.InvocationInfo.ScriptLineNumber - 2;

            // Create a waitable task so that we can continue when the user has chosen the appropriate action.
            _pipelineThreadId      = Thread.CurrentThread.ManagedThreadId;
            _debuggerExecutionTask =
                new TaskCompletionSource <DebuggerResumeAction>();

            // Create a pipeline execution task
            _pipelineExecutionTask =
                new TaskCompletionSource <IPipelineExecutionRequest>();

            // Get call stack and variables.
            await FetchStackFramesAndVariables();

            // Notify the UI
            DebuggerStopped?.Invoke(this, new DebugEventArgs(lineNumber, GetStackFrames()));

            while (true)
            {
                var taskIdx = Task.WaitAny(
                    _debuggerExecutionTask.Task,
                    _pipelineExecutionTask.Task);

                if (taskIdx == 0)
                {
                    // Set the resume action to what the user choose
                    try
                    {
                        e.ResumeAction = _debuggerExecutionTask.Task.Result;
                    }
                    catch (TaskCanceledException) { }
                    catch (AggregateException) { }
                    break;
                }
                else if (taskIdx == 1)
                {
                    try
                    {
                        var executionRequest = _pipelineExecutionTask.Task.Result;

                        _pipelineExecutionTask = new TaskCompletionSource <IPipelineExecutionRequest>();

                        executionRequest.Execute().Wait(_cancellationTokenSource.Token);
                        _pipelineResultTask.SetResult(executionRequest);
                    }
                    catch (TaskCanceledException) { }
                    catch (AggregateException) { }
                }
            }

            _debuggerExecutionTask = null;
        }
示例#9
0
        private void WriteDebuggerBanner(DebuggerStopEventArgs eventArgs)
        {
            // TODO: What do we display when we don't know why we stopped?

            if (eventArgs.Breakpoints.Count > 0)
            {
                // The breakpoint classes have nice ToString output so use that
                this.WriteOutput(
                    Environment.NewLine + $"Hit {eventArgs.Breakpoints[0].ToString()}\n",
                    true,
                    OutputType.Normal,
                    ConsoleColor.Blue);
            }
        }
        public async Task AssertDebuggerStopped(
            string scriptPath,
            int lineNumber = -1)
        {
            SynchronizationContext syncContext = SynchronizationContext.Current;

            DebuggerStopEventArgs eventArgs =
                await this.debuggerStoppedQueue.DequeueAsync();

            Assert.Equal(scriptPath, eventArgs.InvocationInfo.ScriptName);
            if (lineNumber > -1)
            {
                Assert.Equal(lineNumber, eventArgs.InvocationInfo.ScriptLineNumber);
            }
        }
        public async Task AssertDebuggerStopped(
            string scriptPath,
            int lineNumber = -1)
        {
            DebuggerStopEventArgs eventArgs =
                await this.debuggerStoppedQueue.DequeueAsync();

            // TODO #22 - Need to re-enable these Asserts once we figure
            // out how to make them work correctly
            //Assert.Equal(scriptPath, eventArgs.InvocationInfo.ScriptName);
            if (lineNumber > -1)
            {
                //Assert.Equal(lineNumber, eventArgs.InvocationInfo.ScriptLineNumber);
            }
        }
        /// <summary>
        /// Helper method to write debugger stop messages.
        /// </summary>
        /// <param name="args">DebuggerStopEventArgs for current debugger stop</param>
        private void WriteDebuggerStopMessages(DebuggerStopEventArgs args)
        {
            // Write debugger stop information in yellow.
            ConsoleColor saveFGColor = Console.ForegroundColor;

            Console.ForegroundColor = ConsoleColor.Yellow;

            // Show help message only once.
            if (!_showHelpMessage)
            {
                Console.WriteLine("Entering debug mode. Type 'h' to get help.");
                Console.WriteLine();
                _showHelpMessage = true;
            }

            // Break point summary message.
            string breakPointMsg = String.Format(System.Globalization.CultureInfo.InvariantCulture,
                                                 "Breakpoints: Enabled {0}, Disabled {1}",
                                                 (_breakPoints.Values.Where <Breakpoint>((bp) => { return(bp.Enabled); })).Count(),
                                                 (_breakPoints.Values.Where <Breakpoint>((bp) => { return(!bp.Enabled); })).Count());

            Console.WriteLine(breakPointMsg);
            Console.WriteLine();

            // Breakpoint stop information.  Writes all breakpoints that
            // pertain to this debugger execution stop point.
            if (args.Breakpoints.Count > 0)
            {
                Console.WriteLine("Debugger hit breakpoint on:");
                foreach (var breakPoint in args.Breakpoints)
                {
                    Console.WriteLine(breakPoint.ToString());
                }
                Console.WriteLine();
            }

            // Script position stop information.
            // This writes the InvocationInfo position message if
            // there is one.
            if (args.InvocationInfo != null)
            {
                Console.WriteLine(args.InvocationInfo.PositionMessage);
                Console.WriteLine();
            }

            Console.ForegroundColor = saveFGColor;
        }
        // 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;
        }
        async void DebugService_DebuggerStopped(object sender, DebuggerStopEventArgs e)
        {
            // Flush pending output before sending the event
            await this.outputDebouncer.Flush();

            await this.SendEvent(
                StoppedEvent.Type,
                new StoppedEventBody
            {
                Source = new Source
                {
                    Path = e.InvocationInfo.ScriptName,
                },
                Line     = e.InvocationInfo.ScriptLineNumber,
                Column   = e.InvocationInfo.OffsetInLine,
                ThreadId = 1,           // TODO: Change this based on context
                Reason   = "breakpoint" // TODO: Change this based on context
            });
        }
 void DebugService_DebuggerStopped(object sender, DebuggerStopEventArgs e)
 {
     // Push the write operation to the correct thread
     this.messageLoopSyncContext.Post(
         async(obj) =>
     {
         await this.messageWriter.WriteEvent(
             StoppedEvent.Type,
             new StoppedEventBody
         {
             Source = new Source
             {
                 Path = e.InvocationInfo.ScriptName,
             },
             Line     = e.InvocationInfo.ScriptLineNumber,
             Column   = e.InvocationInfo.OffsetInLine,
             ThreadId = 1,           // TODO: Change this based on context
             Reason   = "breakpoint" // TODO: Change this based on context
         });
     }, null);
 }
        /// <summary>
        /// Creates a new instance of the DebuggerStoppedEventArgs class.
        /// </summary>
        /// <param name="originalEvent">The original DebuggerStopEventArgs instance from which this instance is based.</param>
        /// <param name="runspaceDetails">The RunspaceDetails of the runspace which raised this event.</param>
        /// <param name="localScriptPath">The local path of the remote script being debugged.</param>
        public DebuggerStoppedEventArgs(
            DebuggerStopEventArgs originalEvent,
            RunspaceDetails runspaceDetails,
            string localScriptPath)
        {
            Validate.IsNotNull(nameof(originalEvent), originalEvent);
            Validate.IsNotNull(nameof(runspaceDetails), runspaceDetails);

            if (!string.IsNullOrEmpty(localScriptPath))
            {
                this.ScriptPath       = localScriptPath;
                this.RemoteScriptPath = originalEvent.InvocationInfo.ScriptName;
            }
            else
            {
                this.ScriptPath = originalEvent.InvocationInfo.ScriptName;
            }

            this.OriginalEvent   = originalEvent;
            this.RunspaceDetails = runspaceDetails;
        }
示例#17
0
        /// <summary>
        /// Creates a new instance of the DebuggerStoppedEventArgs class.
        /// </summary>
        /// <param name="originalEvent">The original DebuggerStopEventArgs instance from which this instance is based.</param>
        /// <param name="runspaceInfo">The RunspaceDetails of the runspace which raised this event.</param>
        /// <param name="localScriptPath">The local path of the remote script being debugged.</param>
        public DebuggerStoppedEventArgs(
            DebuggerStopEventArgs originalEvent,
            IRunspaceInfo runspaceInfo,
            string localScriptPath)
        {
            Validate.IsNotNull(nameof(originalEvent), originalEvent);
            Validate.IsNotNull(nameof(runspaceInfo), runspaceInfo);

            if (!string.IsNullOrEmpty(localScriptPath))
            {
                ScriptPath       = localScriptPath;
                RemoteScriptPath = originalEvent.InvocationInfo.ScriptName;
            }
            else
            {
                ScriptPath = originalEvent.InvocationInfo.ScriptName;
            }

            OriginalEvent = originalEvent;
            RunspaceInfo  = runspaceInfo;
        }
示例#18
0
        /// <summary>
        /// Helper method to write debugger stop messages.
        /// </summary>
        /// <param name="args">DebuggerStopEventArgs for current debugger stop</param>
        private void PrintCurrentCode(DebuggerStopEventArgs args)
        {
            if (args.InvocationInfo == null)
            {
                return;
            }

            Token[]      tokens;
            ParseError[] parseErrors;

            ScriptBlockAst sciptBlockAst = Parser.ParseInput(
                args.InvocationInfo.Line,
                out tokens,
                out parseErrors);

            UserIOImpl.PrintCode("--------------------------------------------------------------------------------------------------------------\n");
            if (!string.IsNullOrEmpty(args.InvocationInfo.ScriptName))
            {
                ReadFile(args.InvocationInfo.ScriptName);
                UserIOImpl.PrintCode(String.Format("* File {0}:\n",
                                                   args.InvocationInfo.ScriptName));

                UserIOImpl.PrintCode(GetFileLine(args.InvocationInfo.ScriptName, args.InvocationInfo.ScriptLineNumber - 1) + "\n", args.InvocationInfo.ScriptLineNumber - 1);
            }

            foreach (StatementAst statementAst in sciptBlockAst.EndBlock.Statements)
            {
                PrintAST(statementAst, args.InvocationInfo.OffsetInLine);
            }

            if (!string.IsNullOrEmpty(args.InvocationInfo.ScriptName))
            {
                UserIOImpl.PrintCode(GetFileLine(args.InvocationInfo.ScriptName, args.InvocationInfo.ScriptLineNumber + 1) + "\n", args.InvocationInfo.ScriptLineNumber + 1);
            }

            UserIOImpl.PrintCode("\n--------------------------------------------------------------------------------------------------------------\n\n");
        }
 async void debugService_DebuggerStopped(object sender, DebuggerStopEventArgs e)
 {
     await this.debuggerStoppedQueue.EnqueueAsync(e);
 }
示例#20
0
        /// <summary>
        /// PS debugger stopped event handler
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Debugger_DebuggerStop(object sender, DebuggerStopEventArgs e)
        {
            ServiceCommon.Log("Debugger stopped ...");
            DebugScenario currScenario = GetDebugScenario();

            if (_installedPowerShellVersion < RequiredPowerShellVersionForRemoteSessionDebugging)
            {
                RefreshScopedVariable();
                RefreshCallStack();
            }
            else
            {
                RefreshScopedVariable40();
                RefreshCallStack40();
            }

            ServiceCommon.LogCallbackEvent("Callback to client, and wait for debuggee to resume");
            if (e.Breakpoints.Count > 0)
            {
                LineBreakpoint bp = (LineBreakpoint)e.Breakpoints[0];
                if (_callback != null)
                {
                    string file = bp.Script;
                    if (currScenario != DebugScenario.Local && _mapRemoteToLocal.ContainsKey(bp.Script))
                    {
                        file = _mapRemoteToLocal[bp.Script];
                    }

                    // breakpoint is always hit for this case
                    _callback.DebuggerStopped(new DebuggerStoppedEventArgs(file, bp.Line, bp.Column, true, false));
                }
            }
            else
            {
                if (_callback != null)
                {
                    string file;
                    int    lineNum, column;

                    switch (currScenario)
                    {
                    case DebugScenario.LocalAttach:
                        file    = e.InvocationInfo.ScriptName;
                        lineNum = e.InvocationInfo.ScriptLineNumber;
                        column  = e.InvocationInfo.OffsetInLine;

                        // the stop which occurs after attaching is not associated with a breakpoint and should result in the process' script being opened
                        _callback.DebuggerStopped(new DebuggerStoppedEventArgs(file, lineNum, column, false, true));
                        break;

                    case DebugScenario.RemoteAttach:
                        // copy the remote file over to host machine
                        file    = OpenRemoteAttachedFile(e.InvocationInfo.ScriptName);
                        lineNum = e.InvocationInfo.ScriptLineNumber;
                        column  = e.InvocationInfo.OffsetInLine;

                        // the stop which occurs after attaching is not associated with a breakpoint and should result in the remote process' script being opened
                        _callback.DebuggerStopped(new DebuggerStoppedEventArgs(file, lineNum, column, false, true));
                        _needToCopyRemoteScript = false;
                        break;

                    default:
                        _callback.DebuggerStopped(new DebuggerStoppedEventArgs());
                        break;
                    }
                }
            }

            bool resumed = false;

            while (!resumed)
            {
                _pausedEvent.WaitOne();

                try
                {
                    currScenario = GetDebugScenario();
                    if (!string.IsNullOrEmpty(_debuggingCommand))
                    {
                        if (currScenario == DebugScenario.Local)
                        {
                            // local debugging
                            var output = new Collection <PSObject>();

                            using (var pipeline = (_runspace.CreateNestedPipeline()))
                            {
                                pipeline.Commands.AddScript(_debuggingCommand);
                                pipeline.Commands[0].MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output);
                                output = pipeline.Invoke();
                            }

                            ProcessDebuggingCommandResults(output);
                        }
                        else
                        {
                            // remote session and local attach debugging
                            ProcessRemoteDebuggingCommandResults(ExecuteDebuggingCommand());
                        }
                    }
                    else
                    {
                        ServiceCommon.Log(string.Format("Debuggee resume action is {0}", _resumeAction));
                        e.ResumeAction = _resumeAction;
                        resumed        = true; // debugger resumed executing
                    }
                }
                catch (Exception ex)
                {
                    NotifyOutputString(ex.Message);
                }

                // Notify the debugging command execution call that debugging command was complete.
                _debugCommandEvent.Set();
            }
        }
 public void SetDebuggerStopped(DebuggerStopEventArgs args)
 {
     IsStopped         = true;
     LastStopEventArgs = args;
 }
示例#22
0
        public DebuggerDialog(DebuggerStopEventArgs e)
        {
            _InvocationInfo = e.InvocationInfo;

            int maxLine = 0;

            string[] lines = null;
            if (!string.IsNullOrEmpty(e.InvocationInfo.ScriptName) && File.Exists(e.InvocationInfo.ScriptName))
            {
                try
                {
                    lines = File.ReadAllLines(e.InvocationInfo.ScriptName, Encoding.Default);
                    foreach (string s in lines)
                    {
                        if (s.Length > maxLine)
                        {
                            maxLine = s.Length;
                        }
                    }
                }
                catch (IOException) { }
            }

            int dw = Math.Max(Math.Min(Far.Api.UI.WindowSize.X - 7, maxLine + 12), 73);
            int dh = 22;

            string title;
            int    h1;

            if (e.Breakpoints.Count > 0)
            {
                title = "DEBUG: Hit breakpoint(s)";
                h1    = e.Breakpoints.Count + 2;
            }
            else
            {
                title = "DEBUG: Step";
                h1    = 2;
            }

            _Dialog           = Far.Api.CreateDialog(-1, -1, dw, dh);
            _Dialog.HelpTopic = Far.Api.GetHelpTopic("DebuggerDialog");
            _Dialog.AddBox(3, 1, dw - 4, dh - 2, title);

            _List1          = _Dialog.AddListBox(4, 2, dw - 5, h1 + 1, null);
            _List1.Disabled = true;
            _List1.NoBox    = true;
            _List1.NoClose  = true;
            _List1.NoFocus  = true;
            if (e.Breakpoints.Count > 0)
            {
                foreach (Breakpoint bp in e.Breakpoints)
                {
                    CommandBreakpoint bpc = bp as CommandBreakpoint;
                    if (bpc != null && Kit.Equals(bpc.Command, Commands.AssertFarCommand.MyName))
                    {
                        A.InvokeCode("Remove-PSBreakpoint -Breakpoint $args[0]", bpc);
                    }
                }
            }
            foreach (string s in e.InvocationInfo.PositionMessage.Trim().Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries))
            {
                _List1.Add(s);
            }

            _Dialog.AddText(0, -_List1.Rect.Height, 0, null).Separator = 1;

            _List2         = _Dialog.AddListBox(4, _List1.Rect.Bottom + 2, dw - 5, dh - 5, null);
            _List2.NoBox   = true;
            _List2.NoClose = true;
            if (lines != null)
            {
                foreach (string s in lines)
                {
                    _List2.Add(s);
                }
                int i = e.InvocationInfo.ScriptLineNumber - 1;
                _List2.Items[i].Checked = true;
            }

            _Dialog.AddText(0, -_List2.Rect.Height, 0, null).Separator = 1;

            _Step             = _Dialog.AddButton(0, -1, BtnStep);
            _Step.CenterGroup = true;

            _Over             = _Dialog.AddButton(0, 0, BtnOver);
            _Over.CenterGroup = true;

            _Out             = _Dialog.AddButton(0, 0, BtnOut);
            _Out.CenterGroup = true;

            _Console             = _Dialog.AddButton(0, 0, BtnInteractive);
            _Console.CenterGroup = true;
            _Console.NoBrackets  = true;

            _Edit             = _Dialog.AddButton(0, 0, BtnEdit);
            _Edit.CenterGroup = true;
            _Edit.NoBrackets  = true;

            // to be completed on show
            _View             = _Dialog.AddButton(0, 0, BtnView);
            _View.CenterGroup = true;
            _View.NoBrackets  = true;
            _View.NoClose     = true;

            _Goto                = _Dialog.AddButton(0, 0, BtnLine);
            _Goto.CenterGroup    = true;
            _Goto.NoBrackets     = true;
            _Goto.NoClose        = true;
            _Goto.ButtonClicked += OnGoto;

            _Quit             = _Dialog.AddButton(0, 0, BtnQuit);
            _Quit.CenterGroup = true;
            _Quit.NoBrackets  = true;

            _Dialog.Initialized += OnInitialized;
        }
示例#23
0
        internal async void OnDebuggerStopAsync(object sender, DebuggerStopEventArgs e)
        {
            bool   noScriptName    = false;
            string localScriptPath = e.InvocationInfo.ScriptName;

            // If there's no ScriptName, get the "list" of the current source
            if (this.remoteFileManager != null && string.IsNullOrEmpty(localScriptPath))
            {
                // Get the current script listing and create the buffer
                PSCommand command = new PSCommand();
                command.AddScript($"list 1 {int.MaxValue}");

                IEnumerable <PSObject> scriptListingLines =
                    await this.powerShellContext.ExecuteCommandAsync <PSObject>(
                        command, false, false).ConfigureAwait(false);

                if (scriptListingLines != null)
                {
                    int linePrefixLength = 0;

                    string scriptListing =
                        string.Join(
                            Environment.NewLine,
                            scriptListingLines
                            .Select(o => DebugService.TrimScriptListingLine(o, ref linePrefixLength))
                            .Where(s => s != null));

                    this.temporaryScriptListingPath =
                        this.remoteFileManager.CreateTemporaryFile(
                            $"[{this.powerShellContext.CurrentRunspace.SessionDetails.ComputerName}] {TemporaryScriptFileName}",
                            scriptListing,
                            this.powerShellContext.CurrentRunspace);

                    localScriptPath =
                        this.temporaryScriptListingPath
                        ?? StackFrameDetails.NoFileScriptPath;

                    noScriptName = localScriptPath != null;
                }
                else
                {
                    this.logger.LogWarning($"Could not load script context");
                }
            }

            // Get call stack and variables.
            await this.FetchStackFramesAndVariablesAsync(
                noScriptName?localScriptPath : null).ConfigureAwait(false);

            // If this is a remote connection and the debugger stopped at a line
            // in a script file, get the file contents
            if (this.powerShellContext.CurrentRunspace.Location == RunspaceLocation.Remote &&
                this.remoteFileManager != null &&
                !noScriptName)
            {
                localScriptPath =
                    await this.remoteFileManager.FetchRemoteFileAsync(
                        e.InvocationInfo.ScriptName,
                        powerShellContext.CurrentRunspace).ConfigureAwait(false);
            }

            if (this.stackFrameDetails.Length > 0)
            {
                // Augment the top stack frame with details from the stop event

                if (this.invocationTypeScriptPositionProperty
                    .GetValue(e.InvocationInfo) is IScriptExtent scriptExtent)
                {
                    this.stackFrameDetails[0].StartLineNumber   = scriptExtent.StartLineNumber;
                    this.stackFrameDetails[0].EndLineNumber     = scriptExtent.EndLineNumber;
                    this.stackFrameDetails[0].StartColumnNumber = scriptExtent.StartColumnNumber;
                    this.stackFrameDetails[0].EndColumnNumber   = scriptExtent.EndColumnNumber;
                }
            }

            this.CurrentDebuggerStoppedEventArgs =
                new DebuggerStoppedEventArgs(
                    e,
                    this.powerShellContext.CurrentRunspace,
                    localScriptPath);

            // Notify the host that the debugger is stopped
            this.DebuggerStopped?.Invoke(
                sender,
                this.CurrentDebuggerStoppedEventArgs);
        }
示例#24
0
 private void HandleDebuggerStop(object sender, DebuggerStopEventArgs e)
 {
     this.RaiseDebuggerStopEvent(e);
 }
示例#25
0
 /// <summary>
 /// Creates a new instance of the DebuggerStoppedEventArgs class.
 /// </summary>
 /// <param name="originalEvent">The original DebuggerStopEventArgs instance from which this instance is based.</param>
 /// <param name="runspaceInfo">The RunspaceDetails of the runspace which raised this event.</param>
 public DebuggerStoppedEventArgs(
     DebuggerStopEventArgs originalEvent,
     IRunspaceInfo runspaceInfo)
     : this(originalEvent, runspaceInfo, null)
 {
 }
        private void OnDebuggerStop(object sender, DebuggerStopEventArgs e)
        {
            Logger.Write(LogLevel.Verbose, "Debugger stopped execution.");

            // Set the task so a result can be set
            this.debuggerStoppedTask =
                new TaskCompletionSource <DebuggerResumeAction>();

            // Save the pipeline thread ID and create the pipeline execution task
            this.pipelineThreadId      = Thread.CurrentThread.ManagedThreadId;
            this.pipelineExecutionTask = new TaskCompletionSource <IPipelineExecutionRequest>();

            // Update the session state
            this.OnSessionStateChanged(
                this,
                new SessionStateChangedEventArgs(
                    PowerShellContextState.Ready,
                    PowerShellExecutionResult.Stopped,
                    null));

            // Write out the debugger prompt
            // TODO: Eventually re-enable this and put it behind a setting, #133
            //this.WritePromptWithNestedPipeline();

            // Raise the event for the debugger service
            if (this.DebuggerStop != null)
            {
                this.DebuggerStop(sender, e);
            }

            Logger.Write(LogLevel.Verbose, "Starting pipeline thread message loop...");

            while (true)
            {
                int taskIndex =
                    Task.WaitAny(
                        this.debuggerStoppedTask.Task,
                        this.pipelineExecutionTask.Task);

                if (taskIndex == 0)
                {
                    // Write a new output line before continuing
                    // TODO: Re-enable this with fix for #133
                    //this.WriteOutput("", true);

                    e.ResumeAction = this.debuggerStoppedTask.Task.Result;
                    Logger.Write(LogLevel.Verbose, "Received debugger resume action " + e.ResumeAction.ToString());

                    break;
                }
                else if (taskIndex == 1)
                {
                    Logger.Write(LogLevel.Verbose, "Received pipeline thread execution request.");

                    IPipelineExecutionRequest executionRequest =
                        this.pipelineExecutionTask.Task.Result;

                    this.pipelineExecutionTask = new TaskCompletionSource <IPipelineExecutionRequest>();

                    executionRequest.Execute().Wait();

                    Logger.Write(LogLevel.Verbose, "Pipeline thread execution completed.");

                    this.pipelineResultTask.SetResult(executionRequest);
                }
                else
                {
                    // TODO: How to handle this?
                }
            }

            // Clear the task so that it won't be used again
            this.debuggerStoppedTask = null;
        }
 private void Debugger_DebuggerStop(object sender, DebuggerStopEventArgs e)
 {
     //Console.WriteLine(e);
 }
 void debugService_DebuggerStopped(object sender, DebuggerStopEventArgs e)
 {
     this.debuggerStoppedQueue.Enqueue(e);
 }
示例#29
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;
            }
        }
 /// <summary>
 /// Creates a new instance of the DebuggerStoppedEventArgs class.
 /// </summary>
 /// <param name="originalEvent">The original DebuggerStopEventArgs instance from which this instance is based.</param>
 /// <param name="runspaceDetails">The RunspaceDetails of the runspace which raised this event.</param>
 public DebuggerStoppedEventArgs(
     DebuggerStopEventArgs originalEvent,
     RunspaceDetails runspaceDetails)
     : this(originalEvent, runspaceDetails, null)
 {
 }