diff --git a/ParallelKit.Harness.ps1 b/ParallelKit.Harness.ps1 index f0ce80d..34deb12 100644 --- a/ParallelKit.Harness.ps1 +++ b/ParallelKit.Harness.ps1 @@ -980,6 +980,27 @@ $f = Test-PkWorkerSafety -WorkerScript { param($Id) $h = { 1 }; $m = [System.Col Test-Assert ($f.Count -eq 0) ("storing a scriptblock in a collection (.Add/.Enqueue) is not flagged (got " + $f.Count + ")") $f = Test-PkWorkerSafety -WorkerScript { param($Id) $h = { 1 }; $d = [System.Collections.Concurrent.ConcurrentDictionary[string,object]]::new(); $null = $d.GetOrAdd('a', $h) } Test-Assert ($f.Count -eq 1 -and $f[0].Rule -eq 'DelegateCast') "a scriptblock variable passed as a GetOrAdd factory is still flagged" +# Parentheses, a [scriptblock] cast or .GetNewClosure() around the scriptblock +# don't hide it, in the call or where its variable was assigned. +$wrapMissed = [System.Collections.Generic.List[string]]::new() +$wrapped = @('({ 1 })', '(({ 1 }))', '{ 1 }.GetNewClosure()', '({ 1 }).GetNewClosure()', '({ 1 }.GetNewClosure())', '[scriptblock]{ 1 }', '([scriptblock]({ 1 })).GetNewClosure()', '[System.Management.Automation.ScriptBlock]{ 1 }') +foreach ($w in $wrapped) { + $f = Test-PkWorkerSafety -WorkerScript ([scriptblock]::Create('param($Id) $null = [System.Threading.Tasks.Task]::Run(' + $w + ')')) + if ($f.Count -ne 1 -or $f[0].Rule -ne 'DelegateCast' -or $f[0].Text -notlike '*passes a scriptblock to .Run()*') { $wrapMissed.Add('passed ' + $w) } + $f = Test-PkWorkerSafety -WorkerScript ([scriptblock]::Create('param($Id) $sb = ' + $w + '; $null = [System.Threading.Tasks.Task]::Run($sb)')) + if ($f.Count -ne 1 -or $f[0].Rule -ne 'DelegateCast' -or $f[0].Text -notlike '*$sb*') { $wrapMissed.Add('assigned ' + $w) } +} +foreach ($w in @('($sb)', '$sb.GetNewClosure()', '[scriptblock]$sb', '($sb.GetNewClosure())')) { + $f = Test-PkWorkerSafety -WorkerScript ([scriptblock]::Create('param($Id) $sb = { 1 }; $null = [System.Threading.Tasks.Task]::Run(' + $w + ')')) + if ($f.Count -ne 1 -or $f[0].Rule -ne 'DelegateCast' -or $f[0].Text -notlike '*$sb*') { $wrapMissed.Add('passed ' + $w) } +} +Test-Assert ($wrapMissed.Count -eq 0) ("a wrapped scriptblock passed to .NET is flagged, written in the call or through a variable (missed: " + ($wrapMissed -join ' | ') + ")") +$wrapWrong = [System.Collections.Generic.List[string]]::new() +foreach ($w in @('$n = (1); $null = [Math]::Abs(($n))', '$s = [string]({ 1 }.ToString()); $null = [Math]::Abs($s.Length)', '$sb = ({ 1 }); $null = @(1).ForEach(($sb))', '$sb = ({ 1 }); $l = [System.Collections.Generic.List[object]]::new(); $l.Add(($sb))', '$r = (& { 1 }); $null = [Math]::Abs($r)', '$sb = { 1 }; $n = $sb.ToString(); $null = [Math]::Abs($n.Length)', '$null = [System.Threading.Tasks.Task]::Run(({ 1 })) # pk:ignore')) { + $f = Test-PkWorkerSafety -WorkerScript ([scriptblock]::Create("param(`$Id) " + $w + "`n")) + if ($f.Count -ne 0) { $wrapWrong.Add($w + ' -> ' + $f[0].Text) } +} +Test-Assert ($wrapWrong.Count -eq 0) ("and other parenthesized or cast values aren't (" + ($wrapWrong -join ' | ') + ")") # MissingFunction through an alias, and for a module a worker can't load. Set-Alias -Name hdbl -Value Get-HarnessDouble -Scope Global diff --git a/ParallelKit.ps1 b/ParallelKit.ps1 index b1af98b..4357ef3 100644 --- a/ParallelKit.ps1 +++ b/ParallelKit.ps1 @@ -4168,6 +4168,20 @@ function Get-PkUndeclaredVariables { } } +function Get-PkUnwrappedExpression { + # What's left of an expression without the parentheses, [scriptblock] casts + # and .GetNewClosure() calls around it, for finding a scriptblock inside. + param($Ast) + while ($true) { + if ($Ast -is [System.Management.Automation.Language.ParenExpressionAst]) { $Ast = $Ast.Pipeline; continue } + if ($Ast -is [System.Management.Automation.Language.PipelineAst] -and $Ast.PipelineElements.Count -eq 1) { $Ast = $Ast.PipelineElements[0]; continue } + if ($Ast -is [System.Management.Automation.Language.CommandExpressionAst]) { $Ast = $Ast.Expression; continue } + if ($Ast -is [System.Management.Automation.Language.ConvertExpressionAst] -and $Ast.Type.TypeName.Name -match '^(System\.Management\.Automation\.)?scriptblock$') { $Ast = $Ast.Child; continue } + if ($Ast -is [System.Management.Automation.Language.InvokeMemberExpressionAst] -and [string]$Ast.Member.Extent.Text -eq 'GetNewClosure') { $Ast = $Ast.Expression; continue } + return $Ast + } +} + function Test-PkWorkerSafety { # .SYNOPSIS # Checks worker code against the worker rules without running it. @@ -4317,10 +4331,10 @@ function Test-PkWorkerSafetyCore { } # The implicit form: a scriptblock literal, or a variable assigned one - # ({ }.GetNewClosure() included) anywhere in this code, passed to a - # method or constructor: $dict.GetOrAdd($k, { }), - # [System.Lazy[object]]::new($factory). .NET gets a delegate all the - # same. Matched by variable name, not flow. .ForEach()/.Where() take + # anywhere in this code, passed to a method or constructor: + # $dict.GetOrAdd($k, { }), [System.Lazy[object]]::new($factory). .NET + # gets a delegate all the same. Either can be wrapped (see + # Get-PkUnwrappedExpression). Matched by variable name, not flow. .ForEach()/.Where() take # real scriptblocks. Storage methods ($list.Add($sb), # $queue.Enqueue($sb)) make no delegate and aren't flagged, so a # collection typed to hold delegates (List[Func[object]]) isn't caught. @@ -4330,10 +4344,7 @@ function Test-PkWorkerSafetyCore { $target = $assign.Left if ($target -is [System.Management.Automation.Language.ConvertExpressionAst]) { $target = $target.Child } if ($target -isnot [System.Management.Automation.Language.VariableExpressionAst]) { continue } - $rhs = $assign.Right - if ($rhs -is [System.Management.Automation.Language.PipelineAst] -and $rhs.PipelineElements.Count -eq 1) { $rhs = $rhs.PipelineElements[0] } - if ($rhs -is [System.Management.Automation.Language.CommandExpressionAst]) { $rhs = $rhs.Expression } - if ($rhs -is [System.Management.Automation.Language.InvokeMemberExpressionAst] -and [string]$rhs.Member.Extent.Text -eq 'GetNewClosure') { $rhs = $rhs.Expression } + $rhs = Get-PkUnwrappedExpression -Ast $assign.Right if ($rhs -is [System.Management.Automation.Language.ScriptBlockExpressionAst]) { $null = $scriptBlockVars.Add($target.VariablePath.UserPath) } } foreach ($call in $ast.FindAll({ param($node) $node -is [System.Management.Automation.Language.InvokeMemberExpressionAst] }, $true)) { @@ -4343,6 +4354,7 @@ function Test-PkWorkerSafetyCore { if ($memberName -in $storageMethods) { continue } $passed = $null foreach ($argument in $call.Arguments) { + $argument = Get-PkUnwrappedExpression -Ast $argument if ($argument -is [System.Management.Automation.Language.ScriptBlockExpressionAst]) { $passed = 'a scriptblock' } elseif ($argument -is [System.Management.Automation.Language.VariableExpressionAst] -and $scriptBlockVars.Contains($argument.VariablePath.UserPath)) { $passed = ("the scriptblock in `$" + $argument.VariablePath.UserPath) diff --git a/README.md b/README.md index 70dd329..ac20a16 100644 --- a/README.md +++ b/README.md @@ -428,7 +428,7 @@ Everything else is fine in a worker, cmdlets included. Callbacks that run on the
How the kit checks them -`Invoke-PkRunspaceJobs` checks both rules before it starts anything, and refuses to launch code that breaks them, naming the line or the job key. Pass `-CheckWorkerSafety:$false` to turn that off. The code check is also available on its own as `Test-PkWorkerSafety -WorkerScript $w -SharedFunctionNames $names`, which returns a list of findings (including functions the worker calls but you didn't share), for use in your own tests. For rule 2 it flags written casts, and scriptblocks passed into a .NET method or constructor, either written in the call or through a variable they were assigned to. `# pk:ignore` on a line accepts a finding. Storing a scriptblock in a collection (`$list.Add($sb)`, `$queue.Enqueue($sb)`) isn't flagged, since that makes no delegate. The check also refuses a worker that reads a variable it never declares or assigns anywhere (`UndeclaredVariable`), since it would read as empty: one of your script's, or one a `.GetNewClosure()` captured. Parameters, assignments, loop variables, `[ref]`, `-OutVariable` and its kind, `Set-Variable` with a literal name, and PowerShell's own variables all count as declared. `$global:` names and drive-qualified ones (`$env:`) aren't checked, and neither are shared functions, which may read their caller's variables. If something the worker runs sets the variable (a helper file it dot-sources, a module it imports), put `# pk:ignore` on the line that reads it. It can't see commands run through a variable (`& $cmd`), a collection typed to hold delegates (`List[Func[object]]`, whose `.Add` converts), or a scriptblock buried more than three levels deep in a job value. +`Invoke-PkRunspaceJobs` checks both rules before it starts anything, and refuses to launch code that breaks them, naming the line or the job key. Pass `-CheckWorkerSafety:$false` to turn that off. The code check is also available on its own as `Test-PkWorkerSafety -WorkerScript $w -SharedFunctionNames $names`, which returns a list of findings (including functions the worker calls but you didn't share), for use in your own tests. For rule 2 it flags written casts, and scriptblocks passed into a .NET method or constructor, either written in the call or through a variable they were assigned to, parentheses, a `[scriptblock]` cast or `.GetNewClosure()` around them included. `# pk:ignore` on a line accepts a finding. Storing a scriptblock in a collection (`$list.Add($sb)`, `$queue.Enqueue($sb)`) isn't flagged, since that makes no delegate. The check also refuses a worker that reads a variable it never declares or assigns anywhere (`UndeclaredVariable`), since it would read as empty: one of your script's, or one a `.GetNewClosure()` captured. Parameters, assignments, loop variables, `[ref]`, `-OutVariable` and its kind, `Set-Variable` with a literal name, and PowerShell's own variables all count as declared. `$global:` names and drive-qualified ones (`$env:`) aren't checked, and neither are shared functions, which may read their caller's variables. If something the worker runs sets the variable (a helper file it dot-sources, a module it imports), put `# pk:ignore` on the line that reads it. It can't see commands run through a variable (`& $cmd`), a collection typed to hold delegates (`List[Func[object]]`, whose `.Add` converts), or a scriptblock buried more than three levels deep in a job value.