Skip to content

Commit a0ab8e9

Browse files
committed
Fix null dereference bug in PopPowerShell()
1 parent a5d3a97 commit a0ab8e9

File tree

1 file changed

+20
-8
lines changed

1 file changed

+20
-8
lines changed

src/PowerShellEditorServices/Services/PowerShell/Host/PsesInternalHost.cs

Lines changed: 20 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
// Copyright (c) Microsoft Corporation.
1+
// Copyright (c) Microsoft Corporation.
22
// Licensed under the MIT License.
33

44
using System;
@@ -502,15 +502,27 @@ private void PopPowerShell(RunspaceChangeAction runspaceChangeAction = RunspaceC
502502
PowerShellContextFrame frame = _psFrameStack.Pop();
503503
try
504504
{
505-
// If we're changing runspace, make sure we move the handlers over
506-
RunspaceFrame previousRunspaceFrame = _runspaceStack.Peek();
507-
if (previousRunspaceFrame.Runspace != CurrentPowerShell.Runspace)
505+
// If we're changing runspace, make sure we move the handlers over. If we just
506+
// popped the last frame, then we're exiting and should pop the runspace too.
507+
if (_psFrameStack.Count == 0
508+
|| _runspaceStack.Peek().Runspace != _psFrameStack.Peek().PowerShell.Runspace)
508509
{
509-
_runspaceStack.Pop();
510-
RunspaceFrame currentRunspaceFrame = _runspaceStack.Peek();
510+
RunspaceFrame previousRunspaceFrame = _runspaceStack.Pop();
511511
RemoveRunspaceEventHandlers(previousRunspaceFrame.Runspace);
512-
AddRunspaceEventHandlers(currentRunspaceFrame.Runspace);
513-
RunspaceChanged?.Invoke(this, new RunspaceChangedEventArgs(runspaceChangeAction, previousRunspaceFrame.RunspaceInfo, currentRunspaceFrame.RunspaceInfo));
512+
513+
// If there is still a runspace on the stack, then we need to re-register the
514+
// handlers. Otherwise we're exiting and so don't need to run 'RunspaceChanged'.
515+
if (_runspaceStack.Count > 0)
516+
{
517+
RunspaceFrame newRunspaceFrame = _runspaceStack.Peek();
518+
AddRunspaceEventHandlers(newRunspaceFrame.Runspace);
519+
RunspaceChanged?.Invoke(
520+
this,
521+
new RunspaceChangedEventArgs(
522+
runspaceChangeAction,
523+
previousRunspaceFrame.RunspaceInfo,
524+
newRunspaceFrame.RunspaceInfo));
525+
}
514526
}
515527
}
516528
finally

0 commit comments

Comments
 (0)