Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
91 changes: 89 additions & 2 deletions ParallelKit.Harness.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -5274,10 +5274,11 @@ function Get-HarnessSectionLeaks([string]$Source) {
switch ($node.GetType().Name) {
'AssignmentStatementAst' {
# $x = 1, [int]$x = 1 and $x, $y = 1, 2; not $x.Key = 1.
# (A convert is an AttributedExpressionAst.)
$targets = @($node.Left)
if ($node.Left -is [System.Management.Automation.Language.ArrayLiteralAst]) { $targets = @($node.Left.Elements) }
foreach ($target in $targets) {
while ($target -is [System.Management.Automation.Language.ConvertExpressionAst]) { $target = $target.Child }
while ($target -is [System.Management.Automation.Language.AttributedExpressionAst]) { $target = $target.Child }
if ($target -is [System.Management.Automation.Language.VariableExpressionAst]) { $null = $defines[$id].Add((& $bare $target)) }
}
}
Expand All @@ -5297,7 +5298,7 @@ function Get-HarnessSectionLeaks([string]$Source) {
foreach ($id in $defines.Keys) { $elsewhere.UnionWith($defines[$id]) }
foreach ($id in $uses.Keys) {
foreach ($name in $uses[$id]) {
if ($name -eq '$null' -or -not $elsewhere.Contains($name) -or $defines[$id].Contains($name) -or $defines['A'].Contains($name)) { continue }
if ($name -in '$null', '$OFS' -or -not $elsewhere.Contains($name) -or $defines[$id].Contains($name) -or $defines['A'].Contains($name)) { continue }
$id + ' uses ' + $name
}
}
Expand Down Expand Up @@ -5623,6 +5624,92 @@ try {
Write-Host ""
}

# ==============================================================================
if (Test-HarnessSection 'BL' "a worker that reads a variable it never declares is flagged") {
# A worker is rebuilt from its text in a runspace that starts empty, so a
# variable of the script's (or one a closure captured) reads as empty there.
Reset-Harness
function Get-HarnessUndeclared([scriptblock]$Worker, [string[]]$Shared = @()) {
# The names the check flags, in order.
$names = foreach ($f in (Test-PkWorkerSafety -WorkerScript $Worker -SharedFunctionNames $Shared)) {
if ($f.Rule -ne 'UndeclaredVariable') { $f.Rule; continue }
[regex]::Match($f.Text, 'reads \$(\S+?),').Groups[1].Value
}
return (@($names) -join ',')
}
# Each worker here declares or assigns all it reads.
$blClean = [ordered]@{
'its own parameters, and ones of blocks and functions inside it' = { param($Id) function Add-One { param([int]$n, [int]$step = 1) $n + $step } $sb = { param($x) $x * $Id }; & $sb (Add-One 1) }
'a function''s parameters written after its name' = { param($Id) function Add-Two($n) { $n + 2 }; Add-Two $Id }
'assignments: plain, typed, an attribute, several at once, in parentheses, += and ++' = { $a = 1; [int]$b = 2; [ValidateNotNull()]$c = 3; $d, [string]$e = 4, 5; ($g) = 6; $h += 7; $i++; --$j; "$a$b$c$d$e$g$h$i$j" }
'a variable assigned after the line that reads it' = { param($Id) if ($seen) { 'again' }; $seen = $Id }
'foreach and for variables' = { foreach ($f in 1..2) { $f }; for ($n = 0; $n -lt 2; $n++) { $n } }
'the common parameters that fill a variable' = { Get-Item 'x' -OutVariable ov1 -ErrorVariable +ev1 -WarningVariable 'wv1' -InformationVariable:iv1 -PipelineVariable pv1 | ForEach-Object { "$ov1$ev1$wv1$iv1$pv1" } }
'their aliases, and a shortened name' = { Get-Item 'x' -ov ov2 -ev ev2 -wv wv2 -iv iv2 -pv pv2 -ErrorVar ev3 | ForEach-Object { "$ov2$ev2$wv2$iv2$pv2$ev3" } }
'Set-Variable and New-Variable with a literal name' = { Set-Variable sv1 1; Set-Variable -Value 2 -Name sv2; New-Variable -Force 'nv1' 3; Set-Variable -Name sv3, sv4 -Value 1; sv sv5 1; Set-Variable -ErrorAction Stop -OutVariable sv6 sv7 1; Microsoft.PowerShell.Utility\Set-Variable sv8 1; "$sv1$sv2$nv1$sv3$sv4$sv5$sv6$sv7$sv8" }
'Tee-Object, -SessionVariable, -ResponseHeadersVariable and -StatusCodeVariable' = { 1 | Tee-Object -Variable tee1; Invoke-RestMethod 'x' -SessionVariable se1 -ResponseHeadersVariable rh1 -StatusCodeVariable st1; "$tee1$se1$rh1$st1" }
'Import-LocalizedData, by name and by position, and a data block' = { Import-LocalizedData -BindingVariable text1; Import-LocalizedData text2; data text3 { 'x' }; "$text1$text2$text3" }
'[ref]' = { param($Id) $null = [int]::TryParse($Id, [ref]$number); $number }
'automatic variables' = { param($Id) @($Id) | ForEach-Object { $_; $PSItem }; if ('a' -match 'a') { $Matches[0] }; cmd /c exit 0; $LASTEXITCODE; $args; $input; $PSBoundParameters.Count; $MyInvocation; $Error; $PID; $HOME; $Host; $PSVersionTable; $?; $^; $$; $null; $true; $false; $switch; $foreach; $this; $PSCmdlet; $OFS; $PROFILE; $Event; $EventArgs; $Sender; $EventSubscriber; $SourceIdentifier; $ExecutionContext; $PSScriptRoot; $NestedPromptLevel; $StackTrace }
'preference variables' = { $ErrorActionPreference; $VerbosePreference; $ProgressPreference; $InformationPreference; $ConfirmPreference; $WhatIfPreference; $OutputEncoding; $PSDefaultParameterValues; $PSModuleAutoLoadingPreference }
'automatic variables only one of 5.1 and 7 has' = { if ($IsWindows -or $IsLinux -or $IsMacOS -or $IsCoreCLR) { $PSStyle }; $PSNativeCommandUseErrorActionPreference; $PSNativeCommandArgumentPassing; $EnabledExperimentalFeatures; $ConsoleFileName; $MaximumErrorCount }
'drive-qualified names, $global: ones and the kit''s own' = { $env:TEMP; ${function:prompt}; $variable:x; $global:shared; $PkCancelToken; $global:PkWorkerQueue }
'$script: and $local: names the worker assigns itself' = { $script:top = 1; $script:top; $top; $local:here = 2; $here }
'a method and a static member' = { param($Id) $Id.ToString(); [Environment]::NewLine; $h = @{}; $h.Key = 1; $h['x'] = 2; $h }
}
foreach ($blName in $blClean.Keys) {
$blFound = Get-HarnessUndeclared $blClean[$blName]
Test-Assert ($blFound -eq '') ("not flagged: " + $blName + " (flagged: '" + $blFound + "')")
}
# And these read something they don't.
$blFlagged = [ordered]@{
'a plain read' = @('prefix', { param($Id) $prefix + $Id })
'in a string' = @('prefix', { param($Id) "[$prefix$Id] $($Id)" })
'in a nested block and a function' = @('blOuter,blInner', { param($Id) $sb = { $blOuter }; function Get-It { $blInner }; & $sb; Get-It })
'a splat' = @('options', { param($Id) Get-Item @options })
'a member or an element of one' = @('cfg,list,map', { param($Id) $cfg.Path; $list[0]; $map['x'] = $Id })
'a default value' = @('fallback', { param($Id, $Name = $fallback) $Name })
'each name once, at its first line' = @('blOne,blTwo', { param($Id) $blOne; $blTwo; $blOne; $BLONE })
'a name set by a name that isn''t literal' = @('made', { param($Id) Set-Variable -Name $Id -Value 1; $made })
'the value given to Set-Variable, not its name' = @('val', { param($Id) Set-Variable -Name x -Value 'val'; $x; $val })
}
foreach ($blName in $blFlagged.Keys) {
$blFound = Get-HarnessUndeclared $blFlagged[$blName][1]
Test-Assert ($blFound -eq $blFlagged[$blName][0]) ("flagged: " + $blName + " (flagged: '" + $blFound + "', expected '" + $blFlagged[$blName][0] + "')")
}

# '# pk:ignore' accepts the line; another line's read of it is still flagged.
$blFound = Get-HarnessUndeclared ([scriptblock]::Create("param(`$Id)`n. `$env:PK_HELPER`n`$fromHelper + `$Id # pk:ignore"))
Test-Assert ($blFound -eq '') ("'# pk:ignore' on the line accepts it (flagged: '" + $blFound + "')")
$blFound = Test-PkWorkerSafety -WorkerScript ([scriptblock]::Create("param(`$Id)`n`$fromHelper # pk:ignore`n`$fromHelper"))
Test-Assert ($blFound.Count -eq 1 -and $blFound[0].Line -eq 3 -and $blFound[0].Where -eq 'worker script') ("but not the same name on another line (" + $blFound.Count + " finding(s))")
# A shared function reading its caller's variables is ordinary PowerShell.
function Get-HarnessReadsCaller { return $callersVariable }
$blFound = Get-HarnessUndeclared { param($Id) Get-HarnessReadsCaller } @('Get-HarnessReadsCaller')
Test-Assert ($blFound -eq '') ("shared functions aren't checked for it (flagged: '" + $blFound + "')")
# $script: in a nested block is flagged once, by its own rule.
$blFound = Get-HarnessUndeclared { param($Id) $sb = { $script:blNested }; & $sb }
Test-Assert ($blFound -eq 'ScriptVariable') ("`$script: in a nested block is one finding, not two ('" + $blFound + "')")

# A closure gets the reason, and the run is refused.
$blPrefix = 'P'
$blPlain = { param($Id) "[$blPrefix$Id]" }
$blFound = Test-PkWorkerSafety -WorkerScript $blPlain
$blPlainText = @($blFound | ForEach-Object { $_.Text }) -join '; '
$blFound = Test-PkWorkerSafety -WorkerScript $blPlain.GetNewClosure()
$blClosureText = @($blFound | ForEach-Object { $_.Text }) -join '; '
Test-Assert ($blPlainText -like '*$blPrefix*job value*' -and $blPlainText -notlike '*GetNewClosure*') ("the message says to pass it as a job value (" + $blPlainText + ")")
Test-Assert ($blClosureText -like '*$blPrefix*GetNewClosure() doesn''t carry*job value*') ("and for a closure, that .GetNewClosure() doesn't carry variables into a worker (" + $blClosureText + ")")
$blResults = [System.Collections.Generic.List[object]]::new(); $blThrew = ''
try { $null = Invoke-PkRunspaceJobs -MaxParallel 1 -JobParams @{ Id = 1 } -WorkerScript $blPlain.GetNewClosure() -ResultHandler { param($r) $blResults.Add($r) }.GetNewClosure() } catch { $blThrew = [string]$_ }
Test-Assert ($blThrew -like '*worker-safety rules*$blPrefix*' -and $blResults.Count -eq 0) ("a closure worker that would lose its variable is refused before anything runs (results " + ($blResults -join ',') + ", error: " + $blThrew + ")")
$blResults.Clear()
$null = Invoke-PkRunspaceJobs -MaxParallel 1 -JobParams @{ Id = 1 } -WorkerScript $blPlain -CheckWorkerSafety:$false -ResultHandler { param($r) $blResults.Add($r) }.GetNewClosure()
Test-Assert ($blResults.Count -eq 1 -and $blResults[0] -eq '[1]') ("with the check off it runs, and reads it as empty (" + ($blResults -join ',') + ")")
Reset-Harness
Write-Host ""
}

Set-PkMessageHandler -Handler $null
Reset-PkAbortState

Expand Down
Loading
Loading