Skip to content
Open
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
Original file line number Diff line number Diff line change
Expand Up @@ -487,10 +487,22 @@ internal static object DecodeObject(object obj, Type type)
}
else if (obj is PSObject && IsGenericIEnumerableOfInt(type))
{
// we cannot create an instance of interface type like IEnumerable
// Since a Collection implements IEnumerable, falling back to use
// that.
return DecodeCollection((PSObject)obj, typeof(Collection<int>));
// We cannot create an instance of an interface type like IEnumerable<int>,
// so decode into a concrete type that implements it. EncodeObject picks
// the wire format from the runtime type so older servers that send an int[]
// using the array format while a Collection<int> uses the ArrayList format.
PSObject psObject = (PSObject)obj;
if (psObject.BaseObject is ArrayList)
{
return DecodeCollection(psObject, typeof(Collection<int>));
}
else if (psObject.Properties[RemoteDataNameStrings.MethodArrayElements] is not null &&
psObject.Properties[RemoteDataNameStrings.MethodArrayLengths] is not null)
{
return DecodeArray(psObject, typeof(int[]));
}

throw RemoteHostExceptions.NewRemoteHostDataDecodingNotSupportedException(type);
}
else if (obj is PSObject && type == typeof(RemoteHostCall))
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -76,8 +76,22 @@ public Collection<int> PromptForChoice(string caption,
Collection<ChoiceDescription> choices,
IEnumerable<int> defaultChoices)
{
// The remote host encoder picks the wire format from the runtime
// type while the client decodes IEnumerable<int> as a
// Collection<int>. Normalize to Collection<int> so that arrays,
// lists, or any other IEnumerable<int> can round trip.
Collection<int> defaultChoicesCollection = null;
if (defaultChoices is not null)
{
defaultChoicesCollection = new Collection<int>();
foreach (int choice in defaultChoices)
{
defaultChoicesCollection.Add(choice);
}
Comment on lines +86 to +90

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.

Suggested change
defaultChoicesCollection = new Collection<int>();
foreach (int choice in defaultChoices)
{
defaultChoicesCollection.Add(choice);
}
defaultChoicesCollection = new Collection<int>(new List<int>(defaultChoices));

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Is that not going to add the items to a list then go through it again to add to the collection? I don't know much about the internal details here but with the current implementation it only enumerates and adds once. Most likely a moot point because this enumerable is going to be so small.

}

return _serverMethodExecutor.ExecuteMethod<Collection<int>>(RemoteHostMethodId.PromptForChoiceMultipleSelection,
new object[] { caption, message, choices, defaultChoices });
new object[] { caption, message, choices, defaultChoicesCollection });
}

/// <summary>
Expand Down
133 changes: 133 additions & 0 deletions test/powershell/engine/Remoting/RemoteHostCalls.Tests.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.

Describe "Remote host method call tests" -Tag Feature {
BeforeAll {
if (-not ('RemoteHostCallsTest.TestHost' -as [type])) {
Add-Type -TypeDefinition @'
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Management.Automation;
using System.Management.Automation.Host;
using System.Security;

namespace RemoteHostCallsTest
{
public class TestHostUserInterface : PSHostUserInterface, IHostUISupportsMultipleChoiceSelection
{
public int[] ReceivedDefaultChoices;
public Collection<int> ChoicesToReturn = new Collection<int>();

public override PSHostRawUserInterface RawUI => null;
public override string ReadLine() => throw new NotImplementedException();
public override SecureString ReadLineAsSecureString() => throw new NotImplementedException();
public override void Write(string value) { }
public override void Write(ConsoleColor foregroundColor, ConsoleColor backgroundColor, string value) { }
public override void WriteLine(string value) { }
public override void WriteErrorLine(string value) { }
public override void WriteDebugLine(string message) { }
public override void WriteProgress(long sourceId, ProgressRecord record) { }
public override void WriteVerboseLine(string message) { }
public override void WriteWarningLine(string message) { }

public override Dictionary<string, PSObject> Prompt(string caption, string message, Collection<FieldDescription> descriptions)
=> throw new NotImplementedException();

public override PSCredential PromptForCredential(string caption, string message, string userName, string targetName)
=> throw new NotImplementedException();

public override PSCredential PromptForCredential(string caption, string message, string userName, string targetName, PSCredentialTypes allowedCredentialTypes, PSCredentialUIOptions options)
=> throw new NotImplementedException();

public override int PromptForChoice(string caption, string message, Collection<ChoiceDescription> choices, int defaultChoice)
=> throw new NotImplementedException();

public Collection<int> PromptForChoice(string caption, string message, Collection<ChoiceDescription> choices, IEnumerable<int> defaultChoices)
{
ReceivedDefaultChoices = defaultChoices == null ? null : new List<int>(defaultChoices).ToArray();
return ChoicesToReturn;
}
}

public class TestHost : PSHost
{
private readonly TestHostUserInterface _ui = new TestHostUserInterface();
private readonly Guid _instanceId = Guid.NewGuid();

public override CultureInfo CurrentCulture => CultureInfo.CurrentCulture;
public override CultureInfo CurrentUICulture => CultureInfo.CurrentUICulture;
public override Guid InstanceId => _instanceId;
public override string Name => "RemoteHostCallsTest";
public override PSHostUserInterface UI => _ui;
public override Version Version => new Version(1, 0);
public override void EnterNestedPrompt() => throw new NotImplementedException();
public override void ExitNestedPrompt() => throw new NotImplementedException();
public override void NotifyBeginApplication() { }
public override void NotifyEndApplication() { }
public override void SetShouldExit(int exitCode) { }
}
}
'@
}

$testHost = [RemoteHostCallsTest.TestHost]::new()

# Connecting to the current process over the named pipe gives a remote
# runspace whose host calls are marshalled back to our custom host.
$connInfo = [System.Management.Automation.Runspaces.NamedPipeConnectionInfo]::new($PID)
$runspace = [runspacefactory]::CreateRunspace($testHost, $connInfo)
$runspace.Open()
}

AfterAll {
if ($runspace) {
$runspace.Dispose()
}
}

Context "IHostUISupportsMultipleChoiceSelection.PromptForChoice" {
BeforeEach {
$testHost.UI.ReceivedDefaultChoices = $null
$testHost.UI.ChoicesToReturn.Clear()
}

It "Passes default choices as <Name>" -TestCases @(
@{ Name = 'int[]'; DefaultChoices = '[int[]]@(0, 2)'; Expected = @(0, 2) }
@{ Name = 'List[int]'; DefaultChoices = '[System.Collections.Generic.List[int]]@(0, 2)'; Expected = @(0, 2) }
@{ Name = 'Collection[int]'; DefaultChoices = '[System.Collections.ObjectModel.Collection[int]]@(0, 2)'; Expected = @(0, 2) }
@{ Name = 'empty int[]'; DefaultChoices = '[int[]]@()'; Expected = @() }
@{ Name = 'null'; DefaultChoices = '$null'; Expected = $null }
) {
param ($DefaultChoices, $Expected)

$testHost.UI.ChoicesToReturn.Add(1)
$testHost.UI.ChoicesToReturn.Add(2)

$ps = [PowerShell]::Create()
try {
$ps.Runspace = $runspace
$null = $ps.AddScript(@"
`$choices = [System.Collections.ObjectModel.Collection[System.Management.Automation.Host.ChoiceDescription]]@('&a', '&b', '&c')
`$Host.UI.PromptForChoice('caption', 'message', `$choices, $DefaultChoices)
"@)
$actual = $ps.Invoke()

$ps.Streams.Error | Should -BeNullOrEmpty
$actual | Should -Be @(1, 2)

if ($null -eq $Expected) {
$null -eq $testHost.UI.ReceivedDefaultChoices | Should -BeTrue
}
else {
$null -eq $testHost.UI.ReceivedDefaultChoices | Should -BeFalse
$testHost.UI.ReceivedDefaultChoices -join ',' | Should -BeExactly ($Expected -join ',')
}
}
finally {
$ps.Dispose()
}
}
}
}
74 changes: 74 additions & 0 deletions test/xUnit/csharp/test_RemoteHostEncoder.cs

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

This is a unit test, with the patched PowerShell it can no longer emit such objects. The test is here to ensure that the decode logic does not regress and PowerShell can continue to receive the serialized array value from older PowerShell versions.

Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Management.Automation;
using System.Management.Automation.Host;
using System.Management.Automation.Remoting;
using Xunit;

namespace PSTests.Parallel
{
public static class RemoteHostEncoderTests
{
public static TheoryData<IEnumerable<int>> MultipleChoiceDefaultChoices => new()
{
new int[] { 0, 2 },
Array.Empty<int>(),
new Collection<int> { 0, 2 },
new Collection<int>(),
};

[Theory]
[MemberData(nameof(MultipleChoiceDefaultChoices))]
public static void PromptForChoiceMultipleSelectionDefaultChoicesRoundTrip(IEnumerable<int> defaultChoices)
{
// Older servers pass the defaultChoices value through as is so the
// client needs to be able to decode both the array and collection
// wire formats.
Collection<ChoiceDescription> choices = new()
{
new ChoiceDescription("&a"),
new ChoiceDescription("&b"),
new ChoiceDescription("&c"),
};
RemoteHostCall call = new(
1,
RemoteHostMethodId.PromptForChoiceMultipleSelection,
new object[] { "caption", "message", choices, defaultChoices });

RemoteHostCall decoded = RemoteHostCall.Decode(SerializeForRemoting(call.Encode()));

Assert.Equal(RemoteHostMethodId.PromptForChoiceMultipleSelection, decoded.MethodId);
IEnumerable<int> actual = Assert.IsAssignableFrom<IEnumerable<int>>(decoded.Parameters[3]);
Assert.Equal(defaultChoices.ToArray(), actual.ToArray());
}

[Fact]
public static void DecodeEnumerableOfIntWithUnknownFormatFails()
{
PSObject data = new();
data.Properties.Add(new PSNoteProperty("Foo", "Bar"));

PSRemotingDataStructureException exc = Assert.Throws<PSRemotingDataStructureException>(
() => RemoteHostEncoder.DecodeObject(data, typeof(IEnumerable<int>)));
Assert.Equal(
string.Format(RemotingErrorIdStrings.RemoteHostDataDecodingNotSupported, typeof(IEnumerable<int>)),
exc.Message);
}

private static PSObject SerializeForRemoting(PSObject data)
{
Fragmentor fragmentor = new(32 * 1024, null);
using MemoryStream stream = new();
fragmentor.SerializeToBytes(data, stream);
stream.Position = 0;

return fragmentor.DeserializeToPSObject(stream);
}
}
}
Loading