From c43e4a2f57298007552beed21fe663569987e917 Mon Sep 17 00:00:00 2001 From: "Alexey Petrov (Ext)" Date: Fri, 20 Nov 2026 16:46:00 +0000 Subject: [PATCH] Resolve the parameters of Export-ModuleMember without the runspace of the cached command (#1351) GetExportedFunction called CommandInfo.ResolveParameter on the cached CommandInfo of Export-ModuleMember. ResolveParameter always runs on the runspace that the command came from: directly when that runspace is idle, or through one shared engine event when a pipeline runs there. The rules AvoidReservedCharInCmdlet and ProvideCommentHelp call GetExportedFunction on parallel threads, while other rules run Get-Command in the same runspace pool. Two callers then take each other's event, and ResolveParameter throws a NullReferenceException. Export-ModuleMember has no dynamic parameters, so its static parameter metadata gives the same names and aliases without a runspace. GetExportedFunction now resolves a full, shortened or aliased parameter name against that metadata. A name that matches no parameter, or more than one, is skipped as the code intended, and no longer throws a ParameterBindingException. The new test starts 16 callers of GetExportedFunction at one barrier while 16 threads look up commands. On 1.25.0 it fails in Windows PowerShell 5.1 and in PowerShell 7 with the stack of #1351. Co-Authored-By: Claude Opus 5.5 --- Engine/Helper.cs | 35 +++++- Tests/Engine/GetExportedFunction.tests.ps1 | 127 +++++++++++++++++++++ 2 files changed, 158 insertions(+), 4 deletions(-) create mode 100644 Tests/Engine/GetExportedFunction.tests.ps1 diff --git a/Engine/Helper.cs b/Engine/Helper.cs index f36d17433..363a7ae30 100644 --- a/Engine/Helper.cs +++ b/Engine/Helper.cs @@ -404,14 +404,19 @@ public HashSet GetExportedFunction(Ast ast) CommandInfo exportMM = Helper.Instance.GetCommandInfo("export-modulemember", CommandTypes.Cmdlet); - // switch parameters - IEnumerable switchParams = (exportMM != null) ? exportMM.Parameters.Values.Where(pm => pm.SwitchParameter) : Enumerable.Empty(); - if (exportMM == null) { return exportedFunctions; } + // Export-ModuleMember has no dynamic parameters, so its static parameter metadata needs + // no runspace. CommandInfo.ResolveParameter would run on the runspace of the cached + // command, which other rule threads use at the same time. + Dictionary parameters = exportMM.Parameters; + + // switch parameters + IEnumerable switchParams = parameters.Values.Where(pm => pm.SwitchParameter); + foreach (CommandAst cmdAst in cmdAsts) { if (cmdAst.CommandElements == null || cmdAst.CommandElements.Count < 2) @@ -429,7 +434,7 @@ public HashSet GetExportedFunction(Ast ast) if (ceAst is CommandParameterAst) { var paramAst = ceAst as CommandParameterAst; - var param = exportMM.ResolveParameter(paramAst.ParameterName); + var param = ResolveParameter(parameters, paramAst.ParameterName); if (param == null) { @@ -489,6 +494,28 @@ public HashSet GetExportedFunction(Ast ast) return exportedFunctions; } + /// + /// Resolves a full, shortened or aliased parameter name against the parameters of a command, + /// as CommandInfo.ResolveParameter does for a command without dynamic parameters. + /// + /// The parameter, or null when no parameter or more than one parameter matches. + private static ParameterMetadata ResolveParameter(Dictionary parameters, string name) + { + ParameterMetadata exactMatch = parameters.Values.FirstOrDefault(pm => + string.Equals(pm.Name, name, StringComparison.OrdinalIgnoreCase) + || pm.Aliases.Contains(name, StringComparer.OrdinalIgnoreCase)); + if (exactMatch != null) + { + return exactMatch; + } + + ParameterMetadata[] prefixMatches = parameters.Values.Where(pm => + pm.Name.StartsWith(name, StringComparison.OrdinalIgnoreCase) + || pm.Aliases.Any(alias => alias.StartsWith(name, StringComparison.OrdinalIgnoreCase))) + .Take(2).ToArray(); + return prefixMatches.Length == 1 ? prefixMatches[0] : null; + } + /// /// Given a filePath. Returns true if it is a powershell help file /// diff --git a/Tests/Engine/GetExportedFunction.tests.ps1 b/Tests/Engine/GetExportedFunction.tests.ps1 new file mode 100644 index 000000000..dbbccc72c --- /dev/null +++ b/Tests/Engine/GetExportedFunction.tests.ps1 @@ -0,0 +1,127 @@ +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. + +BeforeAll { + # Sets Helper.Instance as a run of Invoke-ScriptAnalyzer does. + $null = Invoke-ScriptAnalyzer -ScriptDefinition 'Get-ChildItem' + + function Get-ExportedFunction([string] $ScriptDefinition) { + $ast = [System.Management.Automation.Language.Parser]::ParseInput($ScriptDefinition, [ref] $null, [ref] $null) + , [Microsoft.Windows.PowerShell.ScriptAnalyzer.Helper]::Instance.GetExportedFunction($ast) + } + + # The rules AvoidReservedCharInCmdlet and ProvideCommentHelp call GetExportedFunction at the + # same time, on the threads of one analysis, while other rules look up commands in the + # runspaces of the command cache. The type starts its callers at one barrier, and keeps the + # runspaces busy with lookups until the callers end. + $references = @([Microsoft.Windows.PowerShell.ScriptAnalyzer.Helper].Assembly.Location) + if ($PSVersionTable.PSEdition -eq 'Core') { + $references += [psobject].Assembly.Location, 'System.Runtime', 'System.Collections', 'System.Collections.Concurrent', 'System.Threading', 'System.Threading.Thread' + } + Add-Type -IgnoreWarnings -WarningAction SilentlyContinue -ReferencedAssemblies $references -TypeDefinition @' +using System; +using System.Collections.Concurrent; +using System.Management.Automation.Language; +using System.Threading; +using Microsoft.Windows.PowerShell.ScriptAnalyzer; + +public static class GetExportedFunctionStress +{ + public static string[] Run(Ast ast, string expectedFunction, int callerCount, int callsPerCaller, int lookupCount) + { + var failures = new ConcurrentQueue(); + var start = new Barrier(callerCount + lookupCount); + int runningCallers = callerCount; + var threads = new Thread[callerCount + lookupCount]; + for (int t = 0; t < callerCount; t++) + { + threads[t] = new Thread(() => + { + start.SignalAndWait(); + for (int i = 0; i < callsPerCaller; i++) + { + try + { + if (!Helper.Instance.GetExportedFunction(ast).Contains(expectedFunction)) + { + failures.Enqueue("The exported functions miss " + expectedFunction); + } + } + catch (Exception e) + { + failures.Enqueue(e.GetType().FullName + ": " + e.Message + " " + TopFrame(e)); + } + } + + Interlocked.Decrement(ref runningCallers); + }); + } + + for (int t = callerCount; t < threads.Length; t++) + { + threads[t] = new Thread(() => + { + start.SignalAndWait(); + while (Volatile.Read(ref runningCallers) > 0) + { + try + { + Helper.Instance.GetCommandInfo("Get-ChildItem", null, true); + } + catch (Exception e) + { + failures.Enqueue("Lookup: " + e.GetType().FullName + ": " + e.Message + " " + TopFrame(e)); + } + } + }); + } + + foreach (var thread in threads) + { + thread.Start(); + } + + foreach (var thread in threads) + { + thread.Join(); + } + + return failures.ToArray(); + } + + private static string TopFrame(Exception e) + { + string trace = e.StackTrace ?? string.Empty; + int end = trace.IndexOf((char)10); + return (end < 0 ? trace : trace.Substring(0, end)).Trim(); + } +} +'@ +} + +Describe 'GetExportedFunction' { + It 'reads the functions of ' -TestCases @( + @{ Call = 'Export-ModuleMember -Function Get-Widget' } + @{ Call = 'Export-ModuleMember -Function:Get-Widget' } + @{ Call = 'Export-ModuleMember -Fun Get-Widget' } + @{ Call = 'Export-ModuleMember Get-Widget' } + @{ Call = 'Export-ModuleMember -Alias gw -Function Get-Widget' } + @{ Call = 'Export-ModuleMember -Verbose -Function Get-Widget' } + @{ Call = 'Export-ModuleMember -NoSuchParameter -Function Get-Widget' } + ) { + Get-ExportedFunction "function Get-Widget {}`n$Call" | Should -Be @('Get-Widget') + } + + It 'gives each of many parallel callers the exported functions' { + $ast = [System.Management.Automation.Language.Parser]::ParseInput( + "function Get-Widget {}`nExport-ModuleMember -Function Get-Widget", + [ref] $null, [ref] $null) + + # A round can end before the race occurs, so the test runs several. + $failures = foreach ($round in 1..5) { + [GetExportedFunctionStress]::Run($ast, 'Get-Widget', 16, 1000, 16) + } + + $failures | Select-Object -Unique | Should -BeNullOrEmpty + } +}