internal InvocationInfo(CommandInfo commandInfo, IScriptExtent scriptPosition, ExecutionContext context) { this._historyId = -1L; this._pipelineIterationInfo = new int[0]; this._commandInfo = commandInfo; this._commandOrigin = System.Management.Automation.CommandOrigin.Internal; this._scriptPosition = scriptPosition; ExecutionContext context2 = null; if ((commandInfo != null) && (commandInfo.Context != null)) { context2 = commandInfo.Context; } else if (context != null) { context2 = context; } if (context2 != null) { LocalRunspace currentRunspace = context2.CurrentRunspace as LocalRunspace; if ((currentRunspace != null) && (currentRunspace.History != null)) { this._historyId = currentRunspace.History.GetNextHistoryId(); } } }
private void HandleRunspaceAvailabilityChanged(object sender, RunspaceAvailabilityEventArgs e) { // Ignore nested commands. LocalRunspace localRunspace = sender as LocalRunspace; if (localRunspace != null) { var basePowerShell = localRunspace.GetCurrentBasePowerShell(); if ((basePowerShell != null) && (basePowerShell.IsNested)) { return; } } RunspaceAvailability prevAvailability = _previousRunspaceAvailability; _previousRunspaceAvailability = e.RunspaceAvailability; if ((e.RunspaceAvailability == RunspaceAvailability.Available) || (e.RunspaceAvailability == RunspaceAvailability.None)) { _debugBlockingCollection.Complete(); } else if ((e.RunspaceAvailability == RunspaceAvailability.Busy) && ((prevAvailability == RunspaceAvailability.Available) || (prevAvailability == RunspaceAvailability.None))) { _newRunningScriptEvent.Set(); } }
public CommandManager(LocalRunspace runspace) { _runspace = runspace; _cmdLets = new Dictionary<string, List<CmdletInfo>>(StringComparer.CurrentCultureIgnoreCase); _scripts = new Dictionary<string, ScriptInfo>(StringComparer.CurrentCultureIgnoreCase); }
internal void EnterNestedPrompt(InternalCommand callingCommand) { LocalRunspace localRunspace = (LocalRunspace)null; try { localRunspace = this.Runspace as LocalRunspace; } catch (PSNotImplementedException ex) { } if (localRunspace != null) { Pipeline currentlyRunningPipeline = this.Runspace.GetCurrentlyRunningPipeline(); if (currentlyRunningPipeline != null && currentlyRunningPipeline == localRunspace.PulsePipeline) { throw new InvalidOperationException(); } } if (this.nestedPromptCount < 0) { throw InternalHost.tracer.NewInvalidOperationException("InternalHostStrings", "EnterExitNestedPromptOutOfSync"); } ++this.nestedPromptCount; this.executionContext.SetVariable("global:NestedPromptLevel", (object)this.nestedPromptCount); InternalHost.PromptContextData promptContextData = new InternalHost.PromptContextData(); promptContextData.SavedContextData = this.executionContext.SaveContextData(); promptContextData.SavedCurrentlyExecutingCommandVarValue = this.executionContext.GetVariable("CurrentlyExecutingCommand"); promptContextData.SavedPSBoundParametersVarValue = this.executionContext.GetVariable("PSBoundParameters"); promptContextData.RunspaceAvailability = this.Context.CurrentRunspace.RunspaceAvailability; if (callingCommand != null) { PSObject psObject = PSObject.AsPSObject((object)callingCommand); psObject.Properties.Add((PSPropertyInfo) new PSNoteProperty("CommandInfo", (object)callingCommand.CommandInfo)); psObject.Properties.Add((PSPropertyInfo) new PSNoteProperty("StackTrace", (object)new StackTrace())); this.executionContext.SetVariable("CurrentlyExecutingCommand", (object)psObject); } this.contextStack.Push(promptContextData); this.executionContext.StepScript = false; this.executionContext.PSDebug = 0; this.executionContext.ResetShellFunctionErrorOutputPipe(); this.Context.CurrentRunspace.UpdateRunspaceAvailability(RunspaceAvailability.AvailableForNestedCommand, true); try { this.externalHostRef.Value.EnterNestedPrompt(); } catch { this.ExitNestedPromptHelper(); throw; } }
public LocalPipeline(LocalRunspace runspace, string command) : base() { _runspace = runspace; _inputStream = new ObjectStream(); _outputStream = new ObjectStream(); _errorStream = new ObjectStream(); _inputPipelineWriter = new ObjectStreamWriter(_inputStream); _outputPipelineReader = new PSObjectPipelineReader(_outputStream); _errorPipelineReader = new ObjectPipelineReader(_errorStream); _pipelineStateInfo = new PipelineStateInfo(PipelineState.NotStarted); if (!string.IsNullOrEmpty(command)) Commands.Add(command); }
private void EnableHostDebugger(Runspace runspace, bool enabled) { // Only enable and disable the host's runspace if we are in process attach mode. if (_debugger is ServerRemoteDebugger) { LocalRunspace localRunspace = runspace as LocalRunspace; if ((localRunspace != null) && (localRunspace.ExecutionContext != null) && (localRunspace.ExecutionContext.EngineHostInterface != null)) { try { localRunspace.ExecutionContext.EngineHostInterface.DebuggerEnabled = enabled; } catch (PSNotImplementedException) { } } } }
public void SetUpRunspace() { TestHost host = new TestHost(new TestHostUserInterface()); // use public static property, so we can access e.g. the ExecutionContext after execution _runspace = RunspaceFactory.CreateRunspace(host) as LocalRunspace; _runspace.Open(); var alias = new AliasInfo("gciAlias", "Get-ChildItem", _runspace.CommandManager); _runspace.ExecutionContext.SessionState.Alias.New(alias, "global"); _runspace.ExecutionContext.SessionState.Function.Set("MyFunction", new ScriptBlock(null)); _runspace.ExecutionContext.SessionState.PSVariable.Set("myvar", 1); var newScope = _runspace.ExecutionContext.Clone(ScopeUsages.NewScope); newScope.SessionState.PSVariable.Set("myothervar", 2); newScope.SessionState.Function.Set("MyFun2", new ScriptBlock(null)); _runspace.ExecutionContext = newScope; _tabExp = new TabExpansionProvider(_runspace); }
private void OnElapsedEvent(object source, ElapsedEventArgs e) { LocalRunspace currentRunspace = this.context.CurrentRunspace as LocalRunspace; if (currentRunspace == null) { this._consecutiveIdleSamples = 0; } else { if (currentRunspace.GetCurrentlyRunningPipeline() == null) { this._consecutiveIdleSamples++; } else { this._consecutiveIdleSamples = 0; } if (this._consecutiveIdleSamples == 4) { this._consecutiveIdleSamples = 0; lock (this.engineEventSubscribers) { List <PSEventSubscriber> list = null; if (this.engineEventSubscribers.TryGetValue("PowerShell.OnIdle", out list) && (list.Count > 0)) { base.GenerateEvent("PowerShell.OnIdle", null, new object[0], null, false, false); this.EnableTimer(); } else { this._isTimerActive = false; } return; } } this.EnableTimer(); } }
/// <summary> /// Internal proxy for EnterNestedPrompt. /// </summary> /// <param name="callingCommand"></param> internal void EnterNestedPrompt(InternalCommand callingCommand) { // Ensure we are in control of the pipeline LocalRunspace localRunspace = null; // This needs to be in a try / catch, since the LocalRunspace cast // tries to verify that the host supports interactive sessions. // Tests hosts do not. try { localRunspace = this.Runspace as LocalRunspace; } catch (PSNotImplementedException) { } if (localRunspace != null) { Pipeline currentlyRunningPipeline = this.Runspace.GetCurrentlyRunningPipeline(); if ((currentlyRunningPipeline != null) && (currentlyRunningPipeline == localRunspace.PulsePipeline)) { throw new InvalidOperationException(); } } // NTRAID#Windows OS Bugs-986407-2004/07/29 When kumarp has done the configuration work in the engine, it // should include setting a bit that indicates that the initialization is complete, and code should be // added here to throw an exception if this function is called before that bit is set. if (NestedPromptCount < 0) { Dbg.Assert(false, "nested prompt counter should never be negative."); throw PSTraceSource.NewInvalidOperationException( InternalHostStrings.EnterExitNestedPromptOutOfSync); } // Increment our nesting counter. When we set the value of the variable, we will replace any existing variable // of the same name. This is good, as any existing value is either 1) ours, and we have claim to replace it, or // 2) is a squatter, and we have claim to clobber it. ++NestedPromptCount; Context.SetVariable(SpecialVariables.NestedPromptCounterVarPath, NestedPromptCount); // On entering a subshell, save and reset values of certain bits of session state PromptContextData contextData = new PromptContextData(); contextData.SavedContextData = Context.SaveContextData(); contextData.SavedCurrentlyExecutingCommandVarValue = Context.GetVariableValue(SpecialVariables.CurrentlyExecutingCommandVarPath); contextData.SavedPSBoundParametersVarValue = Context.GetVariableValue(SpecialVariables.PSBoundParametersVarPath); contextData.RunspaceAvailability = this.Context.CurrentRunspace.RunspaceAvailability; contextData.LanguageMode = Context.LanguageMode; PSPropertyInfo commandInfoProperty = null; PSPropertyInfo stackTraceProperty = null; object oldCommandInfo = null; object oldStackTrace = null; if (callingCommand != null) { Dbg.Assert(callingCommand.Context == Context, "I expect that the contexts should match"); // Populate $CurrentlyExecutingCommand to facilitate debugging. One of the gotchas is that we are going to want // to expose more and more debug info. We could just populate more and more local variables but that is probably // a lousy approach as it pollutes the namespace. A better way to do it is to add NOTES to the variable value // object. PSObject newValue = PSObject.AsPSObject(callingCommand); commandInfoProperty = newValue.Properties["CommandInfo"]; if (commandInfoProperty == null) { newValue.Properties.Add(new PSNoteProperty("CommandInfo", callingCommand.CommandInfo)); } else { oldCommandInfo = commandInfoProperty.Value; commandInfoProperty.Value = callingCommand.CommandInfo; } stackTraceProperty = newValue.Properties["StackTrace"]; if (stackTraceProperty == null) { newValue.Properties.Add(new PSNoteProperty("StackTrace", new System.Diagnostics.StackTrace())); } else { oldStackTrace = stackTraceProperty.Value; stackTraceProperty.Value = new System.Diagnostics.StackTrace(); } Context.SetVariable(SpecialVariables.CurrentlyExecutingCommandVarPath, newValue); } _contextStack.Push(contextData); Dbg.Assert(_contextStack.Count == NestedPromptCount, "number of saved contexts should equal nesting count"); Context.PSDebugTraceStep = false; Context.PSDebugTraceLevel = 0; Context.ResetShellFunctionErrorOutputPipe(); // Lock down the language in the nested prompt if (Context.HasRunspaceEverUsedConstrainedLanguageMode) { Context.LanguageMode = PSLanguageMode.ConstrainedLanguage; } this.Context.CurrentRunspace.UpdateRunspaceAvailability(RunspaceAvailability.AvailableForNestedCommand, true); try { _externalHostRef.Value.EnterNestedPrompt(); } catch { // So where things really go south is this path; which is possible for hosts (like our ConsoleHost) // that don't return from EnterNestedPrompt immediately. // EnterNestedPrompt() starts // ExitNestedPrompt() called // EnterNestedPrompt throws ExitNestedPromptHelper(); throw; } finally { if (commandInfoProperty != null) { commandInfoProperty.Value = oldCommandInfo; } if (stackTraceProperty != null) { stackTraceProperty.Value = oldStackTrace; } } Dbg.Assert(NestedPromptCount >= 0, "nestedPromptCounter should be greater than or equal to 0"); }
internal static ArrayList GetSuggestion(Runspace runspace) { LocalRunspace localRunspace = runspace as LocalRunspace; if (localRunspace == null) { return(new ArrayList()); } // Get the last value of $? bool questionMarkVariableValue = localRunspace.ExecutionContext.QuestionMarkVariableValue; // Get the last history item History history = localRunspace.History; HistoryInfo[] entries = history.GetEntries(-1, 1, true); if (entries.Length == 0) { return(new ArrayList()); } HistoryInfo lastHistory = entries[0]; // Get the last error ArrayList errorList = (ArrayList)localRunspace.GetExecutionContext.DollarErrorVariable; Object lastError = null; if (errorList.Count > 0) { lastError = errorList[0] as Exception; ErrorRecord lastErrorRecord = null; // The error was an actual ErrorRecord if (lastError == null) { lastErrorRecord = errorList[0] as ErrorRecord; } else if (lastError is RuntimeException) { lastErrorRecord = ((RuntimeException)lastError).ErrorRecord; } // If we got information about the error invocation, // we can be more careful with the errors we pass along if ((lastErrorRecord != null) && (lastErrorRecord.InvocationInfo != null)) { if (lastErrorRecord.InvocationInfo.HistoryId == lastHistory.Id) { lastError = lastErrorRecord; } else { lastError = null; } } } Runspace oldDefault = null; bool changedDefault = false; if (Runspace.DefaultRunspace != runspace) { oldDefault = Runspace.DefaultRunspace; changedDefault = true; Runspace.DefaultRunspace = runspace; } ArrayList suggestions = null; try { suggestions = GetSuggestion(lastHistory, lastError, errorList); } finally { if (changedDefault) { Runspace.DefaultRunspace = oldDefault; } } // Restore $? localRunspace.ExecutionContext.QuestionMarkVariableValue = questionMarkVariableValue; return(suggestions); }
internal SessionStateProxy(LocalRunspace runspace) { _runspace = runspace; }
internal static ArrayList GetSuggestion(Runspace runspace) { LocalRunspace runspace2 = runspace as LocalRunspace; if (runspace2 == null) { return(new ArrayList()); } bool questionMarkVariableValue = runspace2.ExecutionContext.QuestionMarkVariableValue; HistoryInfo[] infoArray = runspace2.History.GetEntries((long)(-1L), 1L, true); if (infoArray.Length == 0) { return(new ArrayList()); } HistoryInfo lastHistory = infoArray[0]; ArrayList dollarErrorVariable = (ArrayList)runspace2.GetExecutionContext.DollarErrorVariable; object lastError = null; if (dollarErrorVariable.Count > 0) { lastError = dollarErrorVariable[0] as Exception; ErrorRecord errorRecord = null; if (lastError == null) { errorRecord = dollarErrorVariable[0] as ErrorRecord; } else if (lastError is RuntimeException) { errorRecord = ((RuntimeException)lastError).ErrorRecord; } if ((errorRecord != null) && (errorRecord.InvocationInfo != null)) { if (errorRecord.InvocationInfo.HistoryId == lastHistory.Id) { lastError = errorRecord; } else { lastError = null; } } } Runspace defaultRunspace = null; bool flag2 = false; if (Runspace.DefaultRunspace != runspace) { defaultRunspace = Runspace.DefaultRunspace; flag2 = true; Runspace.DefaultRunspace = runspace; } ArrayList list2 = null; try { list2 = GetSuggestion(lastHistory, lastError, dollarErrorVariable); } finally { if (flag2) { Runspace.DefaultRunspace = defaultRunspace; } } runspace2.ExecutionContext.QuestionMarkVariableValue = questionMarkVariableValue; return(list2); }
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; } } } }
internal void EnterNestedPrompt(InternalCommand callingCommand) { LocalRunspace runspace = null; try { runspace = this.Runspace as LocalRunspace; } catch (PSNotImplementedException) { } if (runspace != null) { Pipeline currentlyRunningPipeline = this.Runspace.GetCurrentlyRunningPipeline(); if ((currentlyRunningPipeline != null) && (currentlyRunningPipeline == runspace.PulsePipeline)) { throw new InvalidOperationException(); } } if (this.nestedPromptCount < 0) { throw PSTraceSource.NewInvalidOperationException("InternalHostStrings", "EnterExitNestedPromptOutOfSync", new object[0]); } this.nestedPromptCount++; this.executionContext.SetVariable(SpecialVariables.NestedPromptCounterVarPath, this.nestedPromptCount); PromptContextData item = new PromptContextData { SavedContextData = this.executionContext.SaveContextData(), SavedCurrentlyExecutingCommandVarValue = this.executionContext.GetVariableValue(SpecialVariables.CurrentlyExecutingCommandVarPath), SavedPSBoundParametersVarValue = this.executionContext.GetVariableValue(SpecialVariables.PSBoundParametersVarPath), RunspaceAvailability = this.Context.CurrentRunspace.RunspaceAvailability, LanguageMode = this.executionContext.LanguageMode }; PSPropertyInfo info = null; PSPropertyInfo info2 = null; object obj2 = null; object obj3 = null; if (callingCommand != null) { PSObject newValue = PSObject.AsPSObject(callingCommand); info = newValue.Properties["CommandInfo"]; if (info == null) { newValue.Properties.Add(new PSNoteProperty("CommandInfo", callingCommand.CommandInfo)); } else { obj2 = info.Value; info.Value = callingCommand.CommandInfo; } info2 = newValue.Properties["StackTrace"]; if (info2 == null) { newValue.Properties.Add(new PSNoteProperty("StackTrace", new StackTrace())); } else { obj3 = info2.Value; info2.Value = new StackTrace(); } this.executionContext.SetVariable(SpecialVariables.CurrentlyExecutingCommandVarPath, newValue); } this.contextStack.Push(item); this.executionContext.PSDebugTraceStep = false; this.executionContext.PSDebugTraceLevel = 0; this.executionContext.ResetShellFunctionErrorOutputPipe(); if (this.executionContext.HasRunspaceEverUsedConstrainedLanguageMode) { this.executionContext.LanguageMode = PSLanguageMode.ConstrainedLanguage; } this.Context.CurrentRunspace.UpdateRunspaceAvailability(RunspaceAvailability.AvailableForNestedCommand, true); try { this.externalHostRef.Value.EnterNestedPrompt(); } catch { this.ExitNestedPromptHelper(); throw; } finally { if (info != null) { info.Value = obj2; } if (info2 != null) { info2.Value = obj3; } } }
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; } } }