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
62 changes: 5 additions & 57 deletions src/System.Management.Automation/engine/ExecutionContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -525,9 +525,7 @@ internal object GetVariableValue(VariablePath path)
/// </summary>
internal object GetVariableValue(VariablePath path, object defaultValue)
{
CmdletProviderContext context;
SessionStateScope scope;
return EngineSessionState.GetVariableValue(path, out context, out scope) ?? defaultValue;
return EngineSessionState.GetVariableValue(path, out _, out _) ?? defaultValue;
}

/// <summary>
Expand Down Expand Up @@ -612,19 +610,15 @@ private void CheckActionPreference(VariablePath preferenceVariablePath, ActionPr
/// <returns></returns>
internal bool GetBooleanPreference(VariablePath preferenceVariablePath, bool defaultPref, out bool defaultUsed)
{
CmdletProviderContext context = null;
SessionStateScope scope = null;
object val = EngineSessionState.GetVariableValue(preferenceVariablePath, out context, out scope);
if (val == null)
object val = EngineSessionState.GetVariableValue(preferenceVariablePath, out _, out _);
if (val is null)
{
defaultUsed = true;
return defaultPref;
}

bool converted = defaultPref;
defaultUsed = !LanguagePrimitives.TryConvertTo<bool>
(val, out converted);
return (defaultUsed) ? defaultPref : converted;
defaultUsed = !LanguagePrimitives.TryConvertTo(val, out bool converted);
return defaultUsed ? defaultPref : converted;
Comment thread
daxian-dbw marked this conversation as resolved.
Resolved
}
#endregion GetSetVariable methods

Expand Down Expand Up @@ -1568,23 +1562,6 @@ internal ExecutionContext(AutomationEngine engine, PSHost hostInterface, Initial
private void InitializeCommon(AutomationEngine engine, PSHost hostInterface)
{
Engine = engine;
#if !CORECLR// System.AppDomain is not in CoreCLR
// Set the assembly resolve handler if it isn't already set...
if (!_assemblyEventHandlerSet)
{
// we only want to set the event handler once for the entire app domain...
lock (lockObject)
{
// Need to check again inside the lock due to possibility of a race condition...
if (!_assemblyEventHandlerSet)
{
AppDomain currentAppDomain = AppDomain.CurrentDomain;
currentAppDomain.AssemblyResolve += new ResolveEventHandler(PowerShellAssemblyResolveHandler);
_assemblyEventHandlerSet = true;
}
}
}
#endif
Events = new PSLocalEventManager(this);
transactionManager = new PSTransactionManager();
_debugger = new ScriptDebugger(this);
Expand All @@ -1609,35 +1586,6 @@ private void InitializeCommon(AutomationEngine engine, PSHost hostInterface)
}

private static readonly object lockObject = new object();

#if !CORECLR // System.AppDomain is not in CoreCLR
private static bool _assemblyEventHandlerSet = false;

/// <summary>
/// AssemblyResolve event handler that will look in the assembly cache to see
/// if the named assembly has been loaded. This is necessary so that assemblies loaded
/// with LoadFrom, which are in a different loaded context than Load, can still be used to
/// resolve types.
/// </summary>
/// <param name="sender">The event sender.</param>
/// <param name="args">The event args.</param>
/// <returns>The resolve assembly or null if not found.</returns>
private static Assembly PowerShellAssemblyResolveHandler(object sender, ResolveEventArgs args)
{
ExecutionContext ecFromTLS = Runspaces.LocalPipeline.GetExecutionContextFromTLS();
if (ecFromTLS != null)
{
if (ecFromTLS.AssemblyCache != null)
{
Assembly assembly;
ecFromTLS.AssemblyCache.TryGetValue(args.Name, out assembly);
return assembly;
}
}

return null;
}
#endif
}

/// <summary>
Expand Down
53 changes: 16 additions & 37 deletions src/System.Management.Automation/engine/InitialSessionState.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1308,37 +1308,6 @@ private static void MakeDisallowedEntriesPrivate<T>(InitialSessionStateEntryColl
}
}

#region VariableHelper
/// <summary>
/// A helper for adding variables to session state.
/// Experimental features can be handled here.
/// </summary>
/// <param name="variables">The variables to add to session state.</param>
private void AddVariables(IEnumerable<SessionStateVariableEntry> variables)
{
Variables.Add(variables);

// If the PSNativeCommandArgumentPassing feature is enabled, create the variable which controls the behavior
// Since the BuiltInVariables list is static, and this should be done dynamically
// we need to do this here. Also, since the defaults are different based on platform we need a
// bit more logic.
if (ExperimentalFeature.IsEnabled("PSNativeCommandArgumentPassing"))
{
NativeArgumentPassingStyle style = NativeArgumentPassingStyle.Standard;
if (Platform.IsWindows) {
style = NativeArgumentPassingStyle.Windows;
}
Variables.Add(
new SessionStateVariableEntry(
SpecialVariables.NativeArgumentPassing,
style,
RunspaceInit.NativeCommandArgumentPassingDescription,
ScopedItemOptions.None,
new ArgumentTypeConverterAttribute(typeof(NativeArgumentPassingStyle))));
}
}
#endregion

/// <summary>
/// Creates an initial session state from a PSSC configuration file.
/// </summary>
Expand Down Expand Up @@ -1444,7 +1413,7 @@ private static InitialSessionState CreateRestrictedForRemoteServer()
}

// Add built-in variables.
iss.AddVariables(BuiltInVariables);
iss.Variables.Add(BuiltInVariables);

// wrap some commands in a proxy function to restrict their parameters
foreach (KeyValuePair<string, CommandMetadata> proxyFunction in CommandMetadata.GetRestrictedCommands(SessionCapabilities.RemoteServer))
Expand Down Expand Up @@ -1531,7 +1500,7 @@ public static InitialSessionState CreateDefault()

InitialSessionState ss = new InitialSessionState();

ss.AddVariables(BuiltInVariables);
ss.Variables.Add(BuiltInVariables);
ss.Commands.Add(new SessionStateApplicationEntry("*"));
ss.Commands.Add(new SessionStateScriptEntry("*"));
ss.Commands.Add(BuiltInFunctions);
Expand Down Expand Up @@ -1598,7 +1567,7 @@ public static InitialSessionState CreateDefault2()
{
InitialSessionState ss = new InitialSessionState();

ss.AddVariables(BuiltInVariables);
ss.Variables.Add(BuiltInVariables);
ss.Commands.Add(new SessionStateApplicationEntry("*"));
ss.Commands.Add(new SessionStateScriptEntry("*"));
ss.Commands.Add(BuiltInFunctions);
Expand Down Expand Up @@ -1639,7 +1608,7 @@ public InitialSessionState Clone()
{
InitialSessionState ss = new InitialSessionState();

ss.AddVariables(this.Variables.Clone());
ss.Variables.Add(this.Variables.Clone());
ss.EnvironmentVariables.Add(this.EnvironmentVariables.Clone());
ss.Commands.Add(this.Commands.Clone());
ss.Assemblies.Add(this.Assemblies.Clone());
Expand Down Expand Up @@ -4471,7 +4440,6 @@ .ForwardHelpCategory Cmdlet
internal const ActionPreference DefaultInformationPreference = ActionPreference.SilentlyContinue;

internal const ErrorView DefaultErrorView = ErrorView.ConciseView;
internal const bool DefaultPSNativeCommandUseErrorActionPreference = false;
internal const bool DefaultWhatIfPreference = false;
internal const ConfirmImpact DefaultConfirmPreference = ConfirmImpact.High;

Expand Down Expand Up @@ -4628,12 +4596,23 @@ static InitialSessionState()
builtinVariables.Add(
new SessionStateVariableEntry(
SpecialVariables.PSNativeCommandUseErrorActionPreference,
DefaultPSNativeCommandUseErrorActionPreference,
value: false,
RunspaceInit.PSNativeCommandUseErrorActionPreferenceDescription,
ScopedItemOptions.None,
new ArgumentTypeConverterAttribute(typeof(bool))));
}

if (ExperimentalFeature.IsEnabled(ExperimentalFeature.PSNativeCommandArgumentPassingFeatureName))
{
builtinVariables.Add(
new SessionStateVariableEntry(
SpecialVariables.NativeArgumentPassing,
Platform.IsWindows ? NativeArgumentPassingStyle.Windows : NativeArgumentPassingStyle.Standard,
RunspaceInit.NativeCommandArgumentPassingDescription,
ScopedItemOptions.None,
new ArgumentTypeConverterAttribute(typeof(NativeArgumentPassingStyle))));
}

BuiltInVariables = builtinVariables.ToArray();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3250,8 +3250,7 @@ internal SwitchParameter WhatIf
{
if (!IsWhatIfFlagSet && !_isWhatIfPreferenceCached)
{
bool defaultUsed = false;
_whatIfFlag = Context.GetBooleanPreference(SpecialVariables.WhatIfPreferenceVarPath, _whatIfFlag, out defaultUsed);
_whatIfFlag = Context.GetBooleanPreference(SpecialVariables.WhatIfPreferenceVarPath, _whatIfFlag, out _);
_isWhatIfPreferenceCached = true;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,6 @@ namespace System.Management.Automation
/// </summary>
internal class NativeCommandParameterBinder : ParameterBinderBase
{
private readonly VariablePath s_nativeArgumentPassingVarPath = new VariablePath(SpecialVariables.NativeArgumentPassing);

#region ctor

/// <summary>
Expand Down Expand Up @@ -193,13 +191,13 @@ internal NativeArgumentPassingStyle ArgumentPassingStyle
{
get
{
if (ExperimentalFeature.IsEnabled("PSNativeCommandArgumentPassing"))
if (ExperimentalFeature.IsEnabled(ExperimentalFeature.PSNativeCommandArgumentPassingFeatureName))
{
try
{
// This will default to the new behavior if it is set to anything other than Legacy
var preference = LanguagePrimitives.ConvertTo<NativeArgumentPassingStyle>(
Context.GetVariableValue(s_nativeArgumentPassingVarPath, NativeArgumentPassingStyle.Standard));
Context.GetVariableValue(SpecialVariables.NativeArgumentPassingVarPath, NativeArgumentPassingStyle.Standard));
return preference;
}
catch
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -865,7 +865,7 @@ internal override void Complete()
this.commandRuntime.PipelineProcessor.ExecutionFailed = true;

if (!ExperimentalFeature.IsEnabled(ExperimentalFeature.PSNativeCommandErrorActionPreferenceFeatureName)
|| !(bool)Command.Context.GetVariableValue(SpecialVariables.PSNativeCommandUseErrorActionPreferenceVarPath, defaultValue: false))
|| !Command.Context.GetBooleanPreference(SpecialVariables.PSNativeCommandUseErrorActionPreferenceVarPath, defaultPref: false, out _))
{
return;
}
Expand Down
6 changes: 4 additions & 2 deletions src/System.Management.Automation/engine/SpecialVariables.cs
Original file line number Diff line number Diff line change
Expand Up @@ -204,6 +204,7 @@ internal static class SpecialVariables
internal static readonly VariablePath PSModuleAutoLoadingPreferenceVarPath = new VariablePath("global:" + PSModuleAutoLoading);

#region Platform Variables

internal const string IsLinux = "IsLinux";

internal static readonly VariablePath IsLinuxPath = new VariablePath("IsLinux");
Expand All @@ -221,6 +222,7 @@ internal static class SpecialVariables
internal static readonly VariablePath IsCoreCLRPath = new VariablePath("IsCoreCLR");

#endregion

#region Preference Variables

internal const string DebugPreference = "DebugPreference";
Expand Down Expand Up @@ -255,13 +257,13 @@ internal static class SpecialVariables

internal static readonly VariablePath InformationPreferenceVarPath = new VariablePath(InformationPreference);

#endregion Preference Variables

internal const string PSNativeCommandUseErrorActionPreference = nameof(PSNativeCommandUseErrorActionPreference);

internal static readonly VariablePath PSNativeCommandUseErrorActionPreferenceVarPath =
new(PSNativeCommandUseErrorActionPreference);

#endregion Preference Variables

// Native command argument passing style
internal const string NativeArgumentPassing = "PSNativeCommandArgumentPassing";

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,19 @@ Describe 'Native command error handling tests' -Tags 'CI' {
$stderr[1].Exception.Message | Should -BeExactly "Program `"$exeName`" ended with non-zero exit code: 1."
}

It "Non-boolean value should not cause type casting error when the native command exited with non-zero code" {
$ErrorActionPreference = 'Continue'

$PSNativeCommandUseErrorActionPreference = 'Yeah'
$PSNativeCommandUseErrorActionPreference | Should -BeExactly 'Yeah'

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this a good thing - that the original value is retained? It seems odd to me that $WhatIfPreference accepts any value and does not coerce it to a boolean value during assignment. I'm sensing there is a PS design principle here for pref vars that I'm not aware of.

@daxian-dbw Dongbo Wang (daxian-dbw) Aug 25, 2021 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This happens to all powershell action preference variable, and actually, all other automatic variables that don't have the "AllScope" option.

For variables that are not 'AllScope', they are not copied to a new local scope and thus an assignment to the same variable in a nested scope actually create a new variable in that scope, which doesn't have the argument transformation attribute as the one declared in the global scope.

BTW, we want to avoid 'AllScope' variables as much as possible because it's expensive.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

But for $WhatIfPreference, it's missing the argument transformation attribute, so you can assign arbitrary value to it even in the global scope ... 🤷

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This happens to all powershell action preference variable, and actually, all other automatic variables that don't have the "AllScope" option.

I'm not seeing that:
image

But also, is there an actual reason for that behaviour to persist with this variable? Surely we want to eagerly convert it to a boolean, since the only thing that can happen is that it becomes a landmine later...

@daxian-dbw Dongbo Wang (daxian-dbw) Aug 25, 2021 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

image

This is from 7.2.0-preview.9. The key is a new local scope.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So is this desirable behaviour though? Or is there no way around it and we just need to prevent the error that happens later?

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

To me it looks like an accidental inconsistency that we should eliminate (but possibly can't because it's a breaking change...?)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So is this desirable behaviour though?

Absolutely not desirable :)

is there no way around it and we just need to prevent the error that happens later?

Making the variable 'AllScope' will prevent it, because 'AllScope' means copy the same variable to every new scope you created. But that's expensive (cost is not necessarily worth the gain), and it may cause breaking changes when it comes to action preference variables considering the existing optimization on those variables.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There could be other ways to improve it, for example, by making those variables aware to PowerShell when creating a new one in a local scope, so the transformation attribute can be automatically added. This is out scope for this PR, but we surely can discuss more about it.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok, I'm happy with the changes in here then and will merge


$stderr = testexe -returncode 1 2>&1

$error[0].FullyQualifiedErrorId | Should -BeExactly 'ProgramExitedWithNonZeroCode'
$error[0].TargetObject | Should -BeExactly $exeName
$stderr[1].Exception.Message | Should -BeExactly "Program `"$exeName`" ended with non-zero exit code: 1."
}

It 'Non-zero exit code generates a non-teminating error for $ErrorActionPreference = ''SilentlyContinue''' {
$ErrorActionPreference = 'SilentlyContinue'

Expand Down Expand Up @@ -174,5 +187,18 @@ Describe 'Native command error handling tests' -Tags 'CI' {
$LASTEXITCODE | Should -Be 1
$Error.Count | Should -Be 0
}

It "Non-boolean value should not cause type casting error when the native command exited with non-zero code" {
$ErrorActionPreference = 'Continue'

$PSNativeCommandUseErrorActionPreference = 0
$PSNativeCommandUseErrorActionPreference | Should -Be 0
$PSNativeCommandUseErrorActionPreference | Should -BeOfType 'System.Int32'

testexe -returncode 1 > $null

$LASTEXITCODE | Should -Be 1
$Error.Count | Should -Be 0
}
}
}