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())); }
private void PowerShellContext_DebuggerStop(object sender, System.Management.Automation.DebuggerStopEventArgs e) { // Cancel any existing prompt first this.CancelCommandPrompt(); this.WriteDebuggerBanner(e); this.ShowCommandPrompt(); }
private void PowerShellContext_DebuggerStop(object sender, System.Management.Automation.DebuggerStopEventArgs e) { if (!this.IsCommandLoopRunning) { StartCommandLoop(); return; } // Cancel any existing prompt first this.CancelCommandPrompt(); this.WriteDebuggerBanner(e); this.ShowCommandPrompt(); }
private void ResumeExecution(DebuggerStopEventArgs e) { switch (e.ResumeAction) { case DebuggerResumeAction.StepInto: this.SetStep("Step-Into", Debugger.SteppingMode.StepIn, -1); break; case DebuggerResumeAction.StepOut: this.SetStep("Step-Out", Debugger.SteppingMode.StepOut, 1); break; case DebuggerResumeAction.StepOver: this.SetStep("Step-Over", Debugger.SteppingMode.StepOver, 0); break; case DebuggerResumeAction.Stop: throw new TerminateException(); } }
void debugService_DebuggerStopped(object sender, DebuggerStopEventArgs e) { this.debuggerStoppedQueue.Enqueue(e); }
private void OnDebuggerStop(InvocationInfo invocationInfo, List <Breakpoint> breakpoints) { LocalRunspace currentRunspace = this._context.CurrentRunspace as LocalRunspace; if ((currentRunspace.PulsePipeline != null) && (currentRunspace.PulsePipeline == currentRunspace.GetCurrentlyRunningPipeline())) { this._context.EngineHostInterface.UI.WriteWarningLine((breakpoints.Count > 0) ? string.Format(CultureInfo.CurrentCulture, DebuggerStrings.WarningBreakpointWillNotBeHit, new object[] { breakpoints[0] }) : new InvalidOperationException().Message); } else { this._steppingMode = SteppingMode.None; EventHandler <DebuggerStopEventArgs> debuggerStop = this.DebuggerStop; if (debuggerStop != null) { this.InBreakpoint = true; this._context.SetVariable(SpecialVariables.PSDebugContextVarPath, new PSDebugContext(invocationInfo, breakpoints)); FunctionInfo baseObject = null; bool flag = false; try { Collection <PSObject> collection = this._context.SessionState.InvokeProvider.Item.Get(@"function:\prompt"); if ((collection != null) && (collection.Count > 0)) { baseObject = collection[0].BaseObject as FunctionInfo; if (string.Equals(baseObject.Definition, InitialSessionState.DefaultPromptString, StringComparison.OrdinalIgnoreCase)) { flag = true; } } } catch (ItemNotFoundException) { } if (flag) { string script = "\"[DBG]: PS $($executionContext.SessionState.Path.CurrentLocation)$('>' * ($nestedPromptLevel + 1)) \""; baseObject.Update(ScriptBlock.Create(script), true, ScopedItemOptions.Unspecified); } PSLanguageMode languageMode = this._context.LanguageMode; PSLanguageMode?nullable = null; if (this._context.UseFullLanguageModeInDebugger && (this._context.LanguageMode != PSLanguageMode.FullLanguage)) { nullable = new PSLanguageMode?(this._context.LanguageMode); this._context.LanguageMode = PSLanguageMode.FullLanguage; } else if (SystemPolicy.GetSystemLockdownPolicy() == SystemEnforcementMode.Enforce) { nullable = new PSLanguageMode?(this._context.LanguageMode); this._context.LanguageMode = PSLanguageMode.ConstrainedLanguage; } RunspaceAvailability runspaceAvailability = this._context.CurrentRunspace.RunspaceAvailability; this._context.CurrentRunspace.UpdateRunspaceAvailability((this._context.CurrentRunspace.GetCurrentlyRunningPipeline() != null) ? RunspaceAvailability.AvailableForNestedCommand : RunspaceAvailability.Available, true); try { this._context._debuggingMode = -1; if (this._callStack.Any <CallStackInfo>()) { this._callStack.Last <CallStackInfo>().TopFrameAtBreakpoint = true; } DebuggerStopEventArgs e = new DebuggerStopEventArgs(invocationInfo, breakpoints); debuggerStop(this, e); this.ResumeExecution(e.ResumeAction); } finally { this._context._debuggingMode = 1; if (this._callStack.Any <CallStackInfo>()) { this._callStack.Last <CallStackInfo>().TopFrameAtBreakpoint = false; } this._context.CurrentRunspace.UpdateRunspaceAvailability(runspaceAvailability, true); if (nullable.HasValue) { this._context.LanguageMode = nullable.Value; } this._context.EngineSessionState.RemoveVariable("PSDebugContext"); if (flag) { baseObject.Update(ScriptBlock.Create(InitialSessionState.DefaultPromptString), true, ScopedItemOptions.Unspecified); } this.InBreakpoint = false; } } } }
/// <summary> /// Handler for debugger events /// </summary> private void HandleDebuggerStop(object sender, DebuggerStopEventArgs e) { // Ignore if we are in restricted mode. if (!IsDebuggingSupported()) { return; } if (LocalDebugMode) { // Forward event locally. RaiseDebuggerStopEvent(e); return; } if ((DebugMode & DebugModes.RemoteScript) != DebugModes.RemoteScript) { return; } _debuggerStopEventArgs = e; PSHost contextHost = null; try { // Save current context remote host. contextHost = _runspace.ExecutionContext.InternalHost.ExternalHost; // Forward event to remote client. Dbg.Assert(_runspace != null, "Runspace cannot be null."); _runspace.ExecutionContext.Events.GenerateEvent( sourceIdentifier: RemoteDebugger.RemoteDebuggerStopEvent, sender: null, args: new object[] { e }, extraData: null); // // Start the debug mode. This is a blocking call and will return only // after ExitDebugMode() is called. // EnterDebugMode(_wrappedDebugger.Value.IsPushed); // Restore original context remote host. _runspace.ExecutionContext.InternalHost.SetHostRef(contextHost); } catch (Exception ex) { CommandProcessor.CheckForSevereException(ex); } finally { _debuggerStopEventArgs = null; } }
private void OnDebuggerStop(InvocationInfo invocationInfo, List<Breakpoint> breakpoints) { LocalRunspace currentRunspace = this._context.CurrentRunspace as LocalRunspace; if ((currentRunspace.PulsePipeline != null) && (currentRunspace.PulsePipeline == currentRunspace.GetCurrentlyRunningPipeline())) { this._context.EngineHostInterface.UI.WriteWarningLine((breakpoints.Count > 0) ? string.Format(CultureInfo.CurrentCulture, DebuggerStrings.WarningBreakpointWillNotBeHit, new object[] { breakpoints[0] }) : new InvalidOperationException().Message); } else { this._steppingMode = SteppingMode.None; EventHandler<DebuggerStopEventArgs> debuggerStop = this.DebuggerStop; if (debuggerStop != null) { this.InBreakpoint = true; this._context.SetVariable(SpecialVariables.PSDebugContextVarPath, new PSDebugContext(invocationInfo, breakpoints)); FunctionInfo baseObject = null; bool flag = false; try { Collection<PSObject> collection = this._context.SessionState.InvokeProvider.Item.Get(@"function:\prompt"); if ((collection != null) && (collection.Count > 0)) { baseObject = collection[0].BaseObject as FunctionInfo; if (string.Equals(baseObject.Definition, InitialSessionState.DefaultPromptString, StringComparison.OrdinalIgnoreCase)) { flag = true; } } } catch (ItemNotFoundException) { } if (flag) { string script = "\"[DBG]: PS $($executionContext.SessionState.Path.CurrentLocation)$('>' * ($nestedPromptLevel + 1)) \""; baseObject.Update(ScriptBlock.Create(script), true, ScopedItemOptions.Unspecified); } PSLanguageMode languageMode = this._context.LanguageMode; PSLanguageMode? nullable = null; if (this._context.UseFullLanguageModeInDebugger && (this._context.LanguageMode != PSLanguageMode.FullLanguage)) { nullable = new PSLanguageMode?(this._context.LanguageMode); this._context.LanguageMode = PSLanguageMode.FullLanguage; } else if (SystemPolicy.GetSystemLockdownPolicy() == SystemEnforcementMode.Enforce) { nullable = new PSLanguageMode?(this._context.LanguageMode); this._context.LanguageMode = PSLanguageMode.ConstrainedLanguage; } RunspaceAvailability runspaceAvailability = this._context.CurrentRunspace.RunspaceAvailability; this._context.CurrentRunspace.UpdateRunspaceAvailability((this._context.CurrentRunspace.GetCurrentlyRunningPipeline() != null) ? RunspaceAvailability.AvailableForNestedCommand : RunspaceAvailability.Available, true); try { this._context._debuggingMode = -1; if (this._callStack.Any<CallStackInfo>()) { this._callStack.Last<CallStackInfo>().TopFrameAtBreakpoint = true; } DebuggerStopEventArgs e = new DebuggerStopEventArgs(invocationInfo, breakpoints); debuggerStop(this, e); this.ResumeExecution(e.ResumeAction); } finally { this._context._debuggingMode = 1; if (this._callStack.Any<CallStackInfo>()) { this._callStack.Last<CallStackInfo>().TopFrameAtBreakpoint = false; } this._context.CurrentRunspace.UpdateRunspaceAvailability(runspaceAvailability, true); if (nullable.HasValue) { this._context.LanguageMode = nullable.Value; } this._context.EngineSessionState.RemoveVariable("PSDebugContext"); if (flag) { baseObject.Update(ScriptBlock.Create(InitialSessionState.DefaultPromptString), true, ScopedItemOptions.Unspecified); } this.InBreakpoint = false; } } } }
private async void OnDebuggerStop(object sender, DebuggerStopEventArgs e) { // Get the call stack and local variables await this.FetchStackFrames(); await this.FetchVariables(); // Notify the host that the debugger is stopped if (this.DebuggerStopped != null) { this.DebuggerStopped(sender, e); } }
private void DebuggerOnDebuggerStop(object sender, DebuggerStopEventArgs args) { if (((ScriptingHostUserInterface) host.UI).CheckSessionCanDoInteractiveAction(nameof(DebuggerOnDebuggerStop))) { host.Runspace.Debugger.SetDebuggerStepMode(true); foreach (var breakpoint in args.Breakpoints) { var message = Message.Parse(this, "ise:breakpointhit"); message.Arguments.Add("Line", (args.InvocationInfo.ScriptLineNumber-1).ToString()); message.Arguments.Add("HitCount", breakpoint.HitCount.ToString()); SendUiMessage(message); NextDebugResumeAction = string.Empty; while (string.IsNullOrEmpty(NextDebugResumeAction) && !abortRequested) { if (!string.IsNullOrEmpty(ImmediateCommand)) { InvokeImmediateCommand(); } else { Thread.Sleep(100); } } DebuggerResumeAction action; Enum.TryParse(NextDebugResumeAction, true, out action); args.ResumeAction = action; } } }
private void HandleMonitorRunningJobsDebuggerStop(object sender, DebuggerStopEventArgs args) { if (!IsJobDebuggingMode()) { #if !CORECLR // Workflow Not Supported on OneCore PS // Remove workflow job callback. UnsubscribeFromEngineWFJobStartEvent(); // Write warning to user. WriteWorkflowDebugNotSupportedError(); #endif // Ignore job debugger stop. args.ResumeAction = DebuggerResumeAction.Continue; return; } Debugger senderDebugger = sender as Debugger; lock (_syncActiveDebuggerStopObject) { Debugger activeDebugger = null; if (_activeDebuggers.TryPeek(out activeDebugger)) { if (activeDebugger.Equals(senderDebugger)) { HandleActiveJobDebuggerStop(sender, args); return; } if (IsRunningWFJobsDebugger(activeDebugger)) { // Replace current job active debugger by first popping. PopActiveDebugger(); } } if (PushActiveDebugger(senderDebugger, _jobCallStackOffset)) { // Forward the debug stop event. HandleActiveJobDebuggerStop(sender, args); } } }
private void HandleActiveJobDebuggerStop(object sender, DebuggerStopEventArgs args) { // If we are debugging nested runspaces then ignore job debugger stops if (_runningRunspaces.Count > 0) { return; } // Forward active debugger event. if (args != null) { // Save copy of arguments. DebuggerStopEventArgs copyArgs = new DebuggerStopEventArgs( args.InvocationInfo, new Collection<Breakpoint>(args.Breakpoints), args.ResumeAction); _debuggerStopEventArgs.Push(copyArgs); CallStackInfo savedCallStackItem = null; try { // Wait for up to 5 seconds for output processing to complete. _processingOutputCompleteEvent.Wait(5000); // Fix up call stack representing this WF call. savedCallStackItem = FixUpCallStack(); // Blocking call that raises stop event. RaiseDebuggerStopEvent(args); _lastActiveDebuggerAction = args.ResumeAction; } finally { RestoreCallStack(savedCallStackItem); _debuggerStopEventArgs.TryPop(out copyArgs); } } }
/// <summary> /// Raises the DebuggerStop event /// </summary> private void OnDebuggerStop(InvocationInfo invocationInfo, List<Breakpoint> breakpoints) { Diagnostics.Assert(breakpoints != null, "The list of breakpoints should not be null"); LocalRunspace localRunspace = _context.CurrentRunspace as LocalRunspace; Diagnostics.Assert(localRunspace != null, "Debugging is only supported on local runspaces"); if (localRunspace.PulsePipeline != null && localRunspace.PulsePipeline == localRunspace.GetCurrentlyRunningPipeline()) { _context.EngineHostInterface.UI.WriteWarningLine( breakpoints.Count > 0 ? String.Format(CultureInfo.CurrentCulture, DebuggerStrings.WarningBreakpointWillNotBeHit, breakpoints[0]) : new InvalidOperationException().Message); return; } _currentInvocationInfo = invocationInfo; _steppingMode = SteppingMode.None; // Optionally wait for a debug stop event subscriber if requested. _inBreakpoint = true; if (!WaitForDebugStopSubscriber()) { // No subscriber. Ignore this debug stop event. _inBreakpoint = false; return; } _context.SetVariable(SpecialVariables.PSDebugContextVarPath, new PSDebugContext(invocationInfo, breakpoints)); FunctionInfo defaultPromptInfo = null; string originalPromptString = null; bool hadDefaultPrompt = false; try { Collection<PSObject> items = _context.SessionState.InvokeProvider.Item.Get("function:\\prompt"); if ((items != null) && (items.Count > 0)) { defaultPromptInfo = items[0].BaseObject as FunctionInfo; originalPromptString = defaultPromptInfo.Definition as string; if (originalPromptString.Equals(InitialSessionState.DefaultPromptFunctionText, StringComparison.OrdinalIgnoreCase) || originalPromptString.Trim().StartsWith(s_processDebugPromptMatch, StringComparison.OrdinalIgnoreCase)) { hadDefaultPrompt = true; } } } catch (ItemNotFoundException) { // Ignore, it means they don't have the default prompt } // Update the prompt to the debug prompt if (hadDefaultPrompt) { int index = originalPromptString.IndexOf("\"", StringComparison.OrdinalIgnoreCase); if (index > -1) { // Fix up prompt. ++index; string debugPrompt = "\"[DBG]: " + originalPromptString.Substring(index, originalPromptString.Length - index); defaultPromptInfo.Update( ScriptBlock.Create(debugPrompt), true, ScopedItemOptions.Unspecified); } else { hadDefaultPrompt = false; } } PSLanguageMode? originalLanguageMode = null; if (_context.UseFullLanguageModeInDebugger && (_context.LanguageMode != PSLanguageMode.FullLanguage)) { originalLanguageMode = _context.LanguageMode; _context.LanguageMode = PSLanguageMode.FullLanguage; } else if (System.Management.Automation.Security.SystemPolicy.GetSystemLockdownPolicy() == System.Management.Automation.Security.SystemEnforcementMode.Enforce) { // If there is a system lockdown in place, enforce it originalLanguageMode = _context.LanguageMode; _context.LanguageMode = PSLanguageMode.ConstrainedLanguage; } RunspaceAvailability previousAvailability = _context.CurrentRunspace.RunspaceAvailability; _context.CurrentRunspace.UpdateRunspaceAvailability( _context.CurrentRunspace.GetCurrentlyRunningPipeline() != null ? RunspaceAvailability.AvailableForNestedCommand : RunspaceAvailability.Available, true); Diagnostics.Assert(_context._debuggingMode == 1, "Should only be stopping when debugger is on."); try { SetInternalDebugMode(InternalDebugMode.InScriptStop); if (_callStack.Any()) { // Get-PSCallStack shouldn't report any frames above this frame, so mark it. One alternative // to marking the frame would be to not push new frames while debugging, but that limits our // ability to give a full callstack if there are errors during eval. _callStack.Last().TopFrameAtBreakpoint = true; } // Reset list lines. _commandProcessor.Reset(); // Save a copy of the stop arguments. DebuggerStopEventArgs copyArgs = new DebuggerStopEventArgs(invocationInfo, breakpoints); _debuggerStopEventArgs.Push(copyArgs); // Blocking call to raise debugger stop event. DebuggerStopEventArgs e = new DebuggerStopEventArgs(invocationInfo, breakpoints); RaiseDebuggerStopEvent(e); ResumeExecution(e.ResumeAction); } finally { SetInternalDebugMode(InternalDebugMode.Enabled); if (_callStack.Any()) { _callStack.Last().TopFrameAtBreakpoint = false; } _context.CurrentRunspace.UpdateRunspaceAvailability(previousAvailability, true); if (originalLanguageMode.HasValue) { _context.LanguageMode = originalLanguageMode.Value; } _context.EngineSessionState.RemoveVariable(SpecialVariables.PSDebugContext); if (hadDefaultPrompt) { // Restore the prompt if they had our default defaultPromptInfo.Update( ScriptBlock.Create(originalPromptString), true, ScopedItemOptions.Unspecified); } DebuggerStopEventArgs oldArgs; _debuggerStopEventArgs.TryPop(out oldArgs); _inBreakpoint = false; } }
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))) { 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 != null) { var psCommand = new PSCommand(); psCommand.AddScript(ImmediateCommand as string) .AddCommand("Out-Default"); //.AddParameter("Stream", true); var results = debugger?.ProcessCommand(psCommand, output); ImmediateResults = output; if (results?.ResumeAction != null) { resumeAction = results.ResumeAction; } ImmediateCommand = null; } else { Thread.Sleep(20); } } args.ResumeAction = resumeAction ?? DebuggerResumeAction.Continue; } } finally { DebuggingInBreakpoint = false; } }
/// <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; }
private void OnExecutionSuspended(object sender, DebuggerStopEventArgs e) { this.debuggerStopEventArgs = e; try { if (this.displayDebuggerBanner) { this.WriteDebuggerMessage(ConsoleHostStrings.EnteringDebugger); this.WriteDebuggerMessage(""); this.displayDebuggerBanner = false; } if (e.Breakpoints.Count > 0) { string hitBreakpoint = ConsoleHostStrings.HitBreakpoint; foreach (Breakpoint breakpoint in e.Breakpoints) { object[] objArray = new object[1]; objArray[0] = breakpoint; this.WriteDebuggerMessage(string.Format(CultureInfo.CurrentCulture, hitBreakpoint, objArray)); } this.WriteDebuggerMessage(""); } if (e.InvocationInfo != null) { this.WriteDebuggerMessage(e.InvocationInfo.PositionMessage); } this.debuggerCommandProcessor.Reset(); this.EnterDebugMode(); } finally { this.debuggerStopEventArgs = null; } }
private void HandleMonitorRunningRSDebuggerStop(object sender, DebuggerStopEventArgs args) { if (sender == null || args == null) { return; } Debugger senderDebugger = sender as Debugger; lock (_syncActiveDebuggerStopObject) { Debugger activeDebugger; if (_activeDebuggers.TryPeek(out activeDebugger)) { // Replace current runspace debugger by first popping the old debugger. if (IsRunningRSDebugger(activeDebugger)) { PopActiveDebugger(); } } // Get nested debugger runspace info. NestedRunspaceDebugger nestedDebugger = senderDebugger as NestedRunspaceDebugger; if (nestedDebugger == null) { return; } PSMonitorRunspaceType runspaceType = nestedDebugger.RunspaceType; // If this is a workflow debugger then ensure that there is a current active // debugger that is the associated job debugger for this inline script WF runspace. if (runspaceType == PSMonitorRunspaceType.WorkflowInlineScript) { bool needToPushAssociatedWFDebugger = true; if (_activeDebuggers.TryPeek(out activeDebugger)) { needToPushAssociatedWFDebugger = (activeDebugger.InstanceId != nestedDebugger.ParentDebuggerId); if (needToPushAssociatedWFDebugger) { // Pop incorrect active debugger. PopActiveDebugger(); } } if (needToPushAssociatedWFDebugger) { PSJobStartEventArgs wfJobArgs = null; lock (_syncObject) { _runningJobs.TryGetValue(nestedDebugger.ParentDebuggerId, out wfJobArgs); } if (wfJobArgs == null) { Diagnostics.Assert(false, "We should never get a WF job InlineScript debugger without an associated WF parent job."); return; } PushActiveDebugger(wfJobArgs.Debugger, _jobCallStackOffset); } } // Fix up invocation info script extents for embedded nested debuggers where the script source is // from the parent. args.InvocationInfo = nestedDebugger.FixupInvocationInfo(args.InvocationInfo); // Finally push the runspace debugger. if (PushActiveDebugger(senderDebugger, _runspaceCallStackOffset)) { // Forward the debug stop event. // This method will always pop the debugger after debugger stop completes. HandleActiveRunspaceDebuggerStop(sender, args); } } }
// 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(); }
private void HandleActiveRunspaceDebuggerStop(object sender, DebuggerStopEventArgs args) { // Save copy of arguments. DebuggerStopEventArgs copyArgs = new DebuggerStopEventArgs( args.InvocationInfo, new Collection<Breakpoint>(args.Breakpoints), args.ResumeAction); _debuggerStopEventArgs.Push(copyArgs); // Forward active debugger event. try { // Blocking call that raises the stop event. RaiseDebuggerStopEvent(args); _lastActiveDebuggerAction = args.ResumeAction; } catch (Exception ex) { // Catch all external user generated exceptions thrown on event thread. CommandProcessorBase.CheckForSevereException(ex); } finally { _debuggerStopEventArgs.TryPop(out copyArgs); PopActiveDebugger(); } }
private void DebuggerOnDebuggerStop(object sender, DebuggerStopEventArgs args) { if (((ScriptingHostUserInterface) host.UI).CheckSessionCanDoInteractiveAction(nameof(DebuggerOnDebuggerStop))) { InvokeInNewPowerShell("Get-PSBreakpoint -Variable SpeDebug | Remove-PSBreakpoint", OutTarget.OutNull); foreach (var breakpoint in args.Breakpoints) { var message = Message.Parse(this, "ise:breakpointhit"); message.Arguments.Add("Line", (args.InvocationInfo.ScriptLineNumber-1).ToString()); message.Arguments.Add("HitCount", breakpoint.HitCount.ToString()); SendUiMessage(message); NextDebugResumeAction = string.Empty; while (string.IsNullOrEmpty(NextDebugResumeAction) && !abortRequested) { if (ImmediateCommand != null) { InvokeInRunningSession(); } else { Thread.Sleep(100); } } DebuggerResumeAction action; Enum.TryParse(NextDebugResumeAction, true, out action); args.ResumeAction = action; if (action != DebuggerResumeAction.Continue) { InvokeInNewPowerShell("Set-PSBreakpoint -Variable SpeDebug -Mode Read", OutTarget.OutNull); SetVariable("SpeDebug", true); GetVariable("SpeDebug"); } } } }
protected virtual void HandleDebuggerStop(object sender, DebuggerStopEventArgs e) { this.RaiseDebuggerStopEvent(e); }
/// <summary> /// Handler for debugger events /// </summary> private void OnExecutionSuspended(object sender, DebuggerStopEventArgs e) { // Check local runspace internalHost to see if debugging is enabled. LocalRunspace localrunspace = LocalRunspace; if ((localrunspace != null) && !localrunspace.ExecutionContext.EngineHostInterface.DebuggerEnabled) { return; } _debuggerStopEventArgs = e; InputLoop baseLoop = null; try { if (this.IsRunspacePushed) { // For remote debugging block data coming from the main (not-nested) // running command. baseLoop = InputLoop.GetNonNestedLoop(); if (baseLoop != null) { baseLoop.BlockCommandOutput(); } } // // Display the banner only once per session // if (_displayDebuggerBanner) { WriteDebuggerMessage(ConsoleHostStrings.EnteringDebugger); WriteDebuggerMessage(""); _displayDebuggerBanner = false; } // // If we hit a breakpoint output its info // if (e.Breakpoints.Count > 0) { string format = ConsoleHostStrings.HitBreakpoint; foreach (Breakpoint breakpoint in e.Breakpoints) { WriteDebuggerMessage(String.Format(CultureInfo.CurrentCulture, format, breakpoint)); } WriteDebuggerMessage(""); } // // Write the source line // if (e.InvocationInfo != null) { // line = StringUtil.Format(ConsoleHostStrings.DebuggerSourceCodeFormat, scriptFileName, e.InvocationInfo.ScriptLineNumber, e.InvocationInfo.Line); WriteDebuggerMessage(e.InvocationInfo.PositionMessage); } // // Start the debug mode // EnterDebugMode(); } finally { _debuggerStopEventArgs = null; if (baseLoop != null) { baseLoop.ResumeCommandOutput(); } } }
protected override void HandleDebuggerStop(object sender, DebuggerStopEventArgs e) { PowerShell runningCmd = null; try { runningCmd = DrainAndBlockRemoteOutput(); this.RaiseDebuggerStopEvent(e); } finally { RestoreRemoteOutput(runningCmd); } }
async void DebugService_DebuggerStopped(object sender, DebuggerStopEventArgs e) { 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 }); }
protected override void HandleDebuggerStop(object sender, DebuggerStopEventArgs e) { _sendDebuggerArgs = new DebuggerStopEventArgs( e.InvocationInfo, new Collection<Breakpoint>(e.Breakpoints), e.ResumeAction); Object remoteRunningCmd = null; try { // For remote debugging drain/block output channel. remoteRunningCmd = DrainAndBlockRemoteOutput(); this.RaiseDebuggerStopEvent(_sendDebuggerArgs); } finally { RestoreRemoteOutput(remoteRunningCmd); // Return user determined resume action. e.ResumeAction = _sendDebuggerArgs.ResumeAction; } }
async void debugService_DebuggerStopped(object sender, DebuggerStopEventArgs e) { await this.debuggerStoppedQueue.EnqueueAsync(e); }
/// <summary> /// Dispose /// </summary> public override void Dispose() { base.Dispose(); _rootDebugger = null; _parentScriptBlockAst = null; _command = null; _sendDebuggerArgs = null; }
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); }
protected void RaiseDebuggerStopEvent(DebuggerStopEventArgs args) { try { DebuggerStopped = true; DebuggerStop.SafeInvoke<DebuggerStopEventArgs>(this, args); } finally { DebuggerStopped = false; } }
private void ProcessDebuggerStopEvent(DebuggerStopEventArgs args) { // It is possible to get a stop event raise request while // debugger is already in stop mode (after remote runspace debugger // reconnect). In this case ignore the request. if (_handleDebuggerStop) { return; } // Attempt to process debugger stop event on original thread if it // is available (i.e., if it is blocked by EndInvoke). PowerShell powershell = _runspace.RunspacePool.RemoteRunspacePoolInternal.GetCurrentRunningPowerShell(); AsyncResult invokeAsyncResult = (powershell != null) ? powershell.EndInvokeAsyncResult : null; bool invokedOnBlockedThread = false; if ((invokeAsyncResult != null) && (!invokeAsyncResult.IsCompleted)) { invokedOnBlockedThread = invokeAsyncResult.InvokeCallbackOnThread( ProcessDebuggerStopEventProc, args); } if (!invokedOnBlockedThread) { #if CORECLR Threading.ThreadPool.QueueUserWorkItem( ProcessDebuggerStopEventProc, args); #else // Otherwise run on worker thread. Utils.QueueWorkItemWithImpersonation( _identityToPersonate, ProcessDebuggerStopEventProc, args); #endif } }
private void OnDebuggerStop(InvocationInfo invocationInfo, List <Breakpoint> breakpoints) { LocalRunspace currentRunspace = this._context.CurrentRunspace as LocalRunspace; if (currentRunspace.PulsePipeline != null && currentRunspace.PulsePipeline == currentRunspace.GetCurrentlyRunningPipeline()) { if (breakpoints.Count > 0) { this._context.EngineHostInterface.UI.WriteWarningLine(ResourceManagerCache.FormatResourceString("DebuggerStrings", "WarningBreakpointWillNotBeHit", (object)breakpoints[0])); } else { this._context.EngineHostInterface.UI.WriteWarningLine(new InvalidOperationException().Message); } } else { this._steppingMode = Debugger.SteppingMode.None; EventHandler <DebuggerStopEventArgs> debuggerStop = this.DebuggerStop; if (debuggerStop == null) { return; } this._inBreakpoint = true; if (invocationInfo != null) { this._callStack.Push(new Debugger.CallStackInfo() { InvocationInfo = invocationInfo }); } this._context.SetVariable("PSDebugContext", (object)new PSDebugContext(invocationInfo, breakpoints)); PSLanguageMode languageMode = this._context.LanguageMode; bool flag = languageMode != PSLanguageMode.FullLanguage && this._context.UseFullLanguageModeInDebugger; if (flag) { this._context.LanguageMode = PSLanguageMode.FullLanguage; } RunspaceAvailability runspaceAvailability = this._context.CurrentRunspace.RunspaceAvailability; this._context.CurrentRunspace.UpdateRunspaceAvailability(this._context.CurrentRunspace.GetCurrentlyRunningPipeline() != null ? RunspaceAvailability.AvailableForNestedCommand : RunspaceAvailability.Available, true); try { DebuggerStopEventArgs e = new DebuggerStopEventArgs(invocationInfo, breakpoints); debuggerStop((object)this, e); this.ResumeExecution(e); } finally { this._context.CurrentRunspace.UpdateRunspaceAvailability(runspaceAvailability, true); if (flag) { this._context.LanguageMode = languageMode; } this._context.RemoveVariable("PSDebugContext"); if (invocationInfo != null) { this._callStack.Pop(); } this._inBreakpoint = false; } } }