Skip to content

Concurrently invoking a ScriptBlock in two runspaces causes InvalidOperationException and pwsh.exe termination #7626

@alx9r

Description

@alx9r

This came up during #7593 and #7530. I think the circumstances where this can occur is wherever all of the following happen:

  1. A scriptblock from one runspace is passed into another instance of the PowerShell class.
  2. The two PowerShell instances are invoked concurrently.
  3. Each PowerShell instance invokes the scriptblock.

I'm not sure exactly what should happen when invoking a scriptblock that is bound to a SessionState from another runspace. I guess I expected it to be cloned and bound to the session state that it found itself in, similar to scriptblocks produced using ScriptBlock.Create().

This is a rather easy scenario to run into wherever there is interaction between runspaces within a process, though. It seems like at least the crash should be prevented.

Steps to reproduce

$scriptblock = {
    function fibonacci {
        param([int]$n)
        [bigint]$a=0
        [bigint]$b=1
        foreach ($x in 0..$n)
        {
            $a,$b = $b,($a+$b)
        }
        $b
    }
    fibonacci 100000 | % {'complete'}
}

$invocations = 1..2 |
    % {
        $powershell = [powershell]::Create().
            AddScript({. $args[0]}).
            AddArgument($scriptblock)
        @{
            PowerShell = $powershell
            Invocation = $powershell.BeginInvoke()
        }
    }
$invocations |
    %{ $_.PowerShell.EndInvoke($_.Invocation)}

Expected behavior

complete
complete

Actual behavior

This is the most verbose output I have witnessed. The run ended in a "PowerShell Core 6 has stopped working" message box.

complete
% : Stack empty.
At C:\users\un1\Desktop\test.ps1:26 char:5
+     %{ $_.PowerShell.EndInvoke($_.Invocation)}
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : NotSpecified: (:) [ForEach-Object], InvalidOperationEx
ception
+ FullyQualifiedErrorId : System.InvalidOperationException,Microsoft.PowerShell.
Commands.ForEachObjectCommand


An error has occurred that was not properly handled. Additional information is s
hown below. The PowerShell process will exit.

Unhandled Exception: System.InvalidOperationException: Stack empty.
   at System.Collections.Generic.Stack`1.ThrowForEmptyStack()
   at System.Collections.Generic.Stack`1.Pop()
   at System.Management.Automation.DlrScriptCommandProcessor.OnRestorePreviousSc
ope()
   at System.Management.Automation.CommandProcessorBase.DoComplete()
   at System.Management.Automation.Internal.PipelineProcessor.DoCompleteCore(Com
mandProcessorBase commandRequestingUpstreamCommandsToStop)
   at System.Management.Automation.Internal.PipelineProcessor.SynchronousExecute
Enumerate(Object input)
   at System.Management.Automation.Runspaces.LocalPipeline.InvokeHelper()
   at System.Management.Automation.Runspaces.LocalPipeline.InvokeThreadProc()
   at System.Management.Automation.Runspaces.PipelineThread.WorkerProc()
   at System.Threading.Thread.ThreadMain_ThreadStart()
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionCo
ntext, ContextCallback callback, Object state)
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()

Environment data

> $PSVersionTable

Name                           Value
----                           -----
PSVersion                      6.1.0-preview.4
PSEdition                      Core
GitCommitId                    6.1.0-preview.4
OS                             Microsoft Windows 6.3.9600 
Platform                       Win32NT
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1
WSManStackVersion              3.0

Metadata

Metadata

Assignees

No one assigned

    Labels

    Issue-Enhancementthe issue is more of a feature request than a bugResolution-No ActivityIssue has had no activity for 6 months or moreWG-Enginecore PowerShell engine, interpreter, and runtime

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions