Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
44 commits
Select commit Hold shift + click to select a range
51efb81
Add DebugPipeName capability
TylerLeonhardt Feb 13, 2019
37f0956
[feature] minor fix for Windows
TylerLeonhardt Feb 13, 2019
a27b6b5
[feature] misc code factor fixes
TylerLeonhardt Feb 13, 2019
6689e89
[feature] add more tests and pass command down to ServerMode
TylerLeonhardt Feb 13, 2019
6e7578c
[feature] fix path for Windows
TylerLeonhardt Feb 13, 2019
5d03cb6
[feature] add erroraction stop and rely on a better way to wait
TylerLeonhardt Feb 14, 2019
7fa9459
refactor to a static public method
TylerLeonhardt Feb 15, 2019
d7df174
[feature] change test casing
TylerLeonhardt Feb 15, 2019
79eabb2
dispose of the server if we recall the function
TylerLeonhardt Feb 16, 2019
f8ab953
address all feedback
TylerLeonhardt Feb 20, 2019
25fbad7
[feature] add test for API and help text
TylerLeonhardt Feb 20, 2019
646bbd6
[feature] address dongbo's feedback
TylerLeonhardt Feb 20, 2019
730f73e
[feature] add more tests and address Steve's feedback
TylerLeonhardt Feb 20, 2019
3944254
[feature] Steve's feedback
TylerLeonhardt Feb 20, 2019
8b4ac8f
[feature] missed if !windows
TylerLeonhardt Feb 20, 2019
2eb4ee7
[feature] a command that will never fail
TylerLeonhardt Feb 21, 2019
a98573e
Add DebugPipeName capability
TylerLeonhardt Feb 13, 2019
f2fa1c4
[feature] minor fix for Windows
TylerLeonhardt Feb 13, 2019
4da3a72
[feature] misc code factor fixes
TylerLeonhardt Feb 13, 2019
72d76ab
[feature] add more tests and pass command down to ServerMode
TylerLeonhardt Feb 13, 2019
64ebaa8
[feature] fix path for Windows
TylerLeonhardt Feb 13, 2019
11d6e74
[feature] add erroraction stop and rely on a better way to wait
TylerLeonhardt Feb 14, 2019
ea81cb3
refactor to a static public method
TylerLeonhardt Feb 15, 2019
8909814
[feature] change test casing
TylerLeonhardt Feb 15, 2019
d02170f
dispose of the server if we recall the function
TylerLeonhardt Feb 16, 2019
2ba7604
address all feedback
TylerLeonhardt Feb 20, 2019
f264743
[feature] add test for API and help text
TylerLeonhardt Feb 20, 2019
dff15c7
[feature] address dongbo's feedback
TylerLeonhardt Feb 20, 2019
1795fb7
[feature] add more tests and address Steve's feedback
TylerLeonhardt Feb 20, 2019
aecf00e
[feature] Steve's feedback
TylerLeonhardt Feb 20, 2019
6ad9763
[feature] missed if !windows
TylerLeonhardt Feb 20, 2019
78136f9
[feature] a command that will never fail
TylerLeonhardt Feb 21, 2019
c0a0050
Merge branch 'debugpipename-enterpshostprocess' of github.com:TylerLe…
TylerLeonhardt Feb 21, 2019
19ce341
[feature]switch to querying for the pid and remove unneed Wait-UntilTrue
TylerLeonhardt Feb 21, 2019
c8e59a5
[feature] use exit code
TylerLeonhardt Feb 21, 2019
69621ca
[feature] fix log message and Codacy and Code Factor fixes
TylerLeonhardt Feb 21, 2019
73cd2ce
Change DebugPipeName to CustomPipeName
TylerLeonhardt Feb 21, 2019
636c401
[feature] touch up summary
TylerLeonhardt Feb 21, 2019
f8260cf
move API tests to xUnit
TylerLeonhardt Feb 21, 2019
d79da98
[feature] Add ParallelXUnitResults.xml
TylerLeonhardt Feb 21, 2019
5549bd8
[feature] remove debug log
TylerLeonhardt Feb 21, 2019
d9d1779
[feature] switch to Start-Process
TylerLeonhardt Feb 22, 2019
1edba6c
misc codacy fixes
TylerLeonhardt Feb 22, 2019
9c3dfb3
[feature] address Ilya's comments
TylerLeonhardt Feb 22, 2019
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
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ Temporary Items

# TestsResults
TestsResults*.xml
ParallelXUnitResults.xml

# Resharper settings
PowerShell.sln.DotSettings.user
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,9 @@ public override void WriteWarningLine(string message)

internal class CommandLineParameterParser
{
private const int MaxPipePathLengthLinux = 108;
private const int MaxPipePathLengthMacOS = 104;

internal static string[] validParameters = {
"version",
"nologo",
Expand All @@ -189,7 +192,8 @@ internal class CommandLineParameterParser
"settingsfile",
"help",
"workingdirectory",
"removeworkingdirectorytrailingcharacter"
"removeworkingdirectorytrailingcharacter",
"custompipename"
};

internal CommandLineParameterParser(PSHostUserInterface hostUI, string bannerText, string helpText)
Expand Down Expand Up @@ -341,6 +345,14 @@ internal bool ShowVersion
}
}

internal string CustomPipeName
{
get
{
return _customPipeName;
}
}

internal Serialization.DataFormat OutputFormat
{
get
Expand Down Expand Up @@ -773,6 +785,33 @@ private void ParseHelper(string[] args)

_configurationName = args[i];
}
else if (MatchSwitch(switchKey, "custompipename", "cus"))
{
++i;
if (i >= args.Length)
{
WriteCommandLineError(
CommandLineParameterParserStrings.MissingCustomPipeNameArgument);
break;
}

if (!Platform.IsWindows)
{
int maxNameLength = (Platform.IsLinux ? MaxPipePathLengthLinux : MaxPipePathLengthMacOS) - Path.GetTempPath().Length;
if (args[i].Length > maxNameLength)
{
WriteCommandLineError(
Comment thread
SteveL-MSFT marked this conversation as resolved.
Resolved
string.Format(
CommandLineParameterParserStrings.CustomPipeNameTooLong,
maxNameLength,
args[i],
args[i].Length));
break;
}
}

_customPipeName = args[i];
}
else if (MatchSwitch(switchKey, "command", "c"))
{
if (!ParseCommand(args, ref i, noexitSeen, false))
Expand Down Expand Up @@ -1375,6 +1414,7 @@ private bool CollectArgs(string[] args, ref int i)
private string _helpText;
private bool _abortStartup;
private bool _skipUserInit;
private string _customPipeName;
#if STAMODE
// Win8: 182409 PowerShell 3.0 should run in STA mode by default
// -sta and -mta are mutually exclusive..so tracking them using nullable boolean
Expand Down
22 changes: 12 additions & 10 deletions src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1369,6 +1369,12 @@ private uint Run(CommandLineParameterParser cpp, bool isPrestartWarned)
}
#endif

// If the debug pipe name was specified, create the custom IPC channel.
if (!string.IsNullOrEmpty(cpp.CustomPipeName))
{
RemoteSessionNamedPipeServer.CreateCustomNamedPipeServer(cpp.CustomPipeName);
}

// NTRAID#Windows Out Of Band Releases-915506-2005/09/09
// Removed HandleUnexpectedExceptions infrastructure
#if STAMODE
Expand Down Expand Up @@ -2884,16 +2890,12 @@ internal sealed class RunspaceCreationEventArgs : EventArgs
/// <summary>
/// Constructs RunspaceCreationEventArgs.
/// </summary>
/// <param name="initialCommand"></param>
/// <param name="skipProfiles"></param>
/// <param name="staMode"></param>
/// <param name="configurationName"></param>
/// <param name="initialCommandArgs"></param>
internal RunspaceCreationEventArgs(string initialCommand,
bool skipProfiles,
bool staMode,
string configurationName,
Collection<CommandParameter> initialCommandArgs)
internal RunspaceCreationEventArgs(
string initialCommand,
bool skipProfiles,
bool staMode,
string configurationName,
Collection<CommandParameter> initialCommandArgs)
{
InitialCommand = initialCommand;
SkipProfiles = skipProfiles;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,12 @@
<data name="MissingConfigurationNameArgument" xml:space="preserve">
<value>Cannot process the command because -Configuration requires an argument that is a remote endpoint configuration name. Specify this argument and try again.</value>
</data>
<data name="MissingCustomPipeNameArgument" xml:space="preserve">
<value>Cannot process the command because -CustomPipeName requires an argument that is a name of the pipe you want to use. Specify this argument and try again.</value>
</data>
<data name="CustomPipeNameTooLong" xml:space="preserve">
<value>Cannot process the command because -CustomPipeName specified is too long. Pipe names on this platform can be up to {0} characters long. Your pipe name '{1}' is {2} characters.</value>
</data>
<data name="MissingSettingsFileArgument" xml:space="preserve">
<value>Cannot process the command because -SettingsFile requires an argument that is a file path.</value>
</data>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,8 @@ Type 'help' to get help.</value>
<value>Usage: pwsh[.exe] [[-File] &lt;filePath&gt; [args]]
[-Command { - | &lt;script-block&gt; [-args &lt;arg-array&gt;]
| &lt;string&gt; [&lt;CommandParameters&gt;] } ]
[-ConfigurationName &lt;string&gt;] [-EncodedCommand &lt;Base64EncodedCommand&gt;]
[-ConfigurationName &lt;string&gt;] [-CustomPipeName &lt;string&gt;]
[-EncodedCommand &lt;Base64EncodedCommand&gt;]
[-ExecutionPolicy &lt;ExecutionPolicy&gt;] [-InputFormat {Text | XML}]
[-Interactive] [-NoExit] [-NoLogo] [-NonInteractive] [-NoProfile]
[-OutputFormat {Text | XML}] [-Version] [-WindowStyle &lt;style&gt;]
Expand Down Expand Up @@ -174,6 +175,17 @@ All parameters are case-insensitive.</value>

Example: pwsh -ConfigurationName AdminRoles

-CustomPipeName
Specifies the name to use for an additional IPC server (named pipe) used for debugging
and other cross-process communication. This offers a predictable mechanism for connecting
to other PowerShell instances. Typically used with the CustomPipeName parameter on Enter-PSHostProcess.

Example:
# PowerShell instance 1
pwsh -CustomPipeName mydebugpipe
# PowerShell instance 2
Enter-PSHostProcess -CustomPipeName mydebugpipe

-EncodedCommand | -e | -ec
Accepts a base64 encoded string version of a command. Use this parameter to submit
commands to PowerShell that require complex quotation marks or curly braces.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
using System.Management.Automation.Internal;
using System.Management.Automation.Remoting;
using System.Management.Automation.Runspaces;
using System.Text;

namespace Microsoft.PowerShell.Commands
{
Expand All @@ -37,6 +38,7 @@ public sealed class EnterPSHostProcessCommand : PSCmdlet
private const string ProcessParameterSet = "ProcessParameterSet";
private const string ProcessNameParameterSet = "ProcessNameParameterSet";
private const string ProcessIdParameterSet = "ProcessIdParameterSet";
private const string PipeNameParameterSet = "PipePipeNameParameterSet";
private const string PSHostProcessInfoParameterSet = "PSHostProcessInfoParameterSet";

private const string NamedPipeRunspaceName = "PSAttachRunspace";
Expand Down Expand Up @@ -91,6 +93,16 @@ public PSHostProcessInfo HostProcessInfo
set;
}

/// <summary>
/// Gets or sets the custom named pipe name to connect to. This is usually used in conjunction with `pwsh -CustomPipeName`.
/// </summary>
[Parameter(Mandatory = true, ParameterSetName = EnterPSHostProcessCommand.PipeNameParameterSet)]
public string CustomPipeName
{
get;
set;
}

/// <summary>
/// Optional name of AppDomain in process to enter. If not specified then the default AppDomain is used.
/// </summary>
Expand Down Expand Up @@ -129,25 +141,34 @@ protected override void EndProcessing()
}

// Check selected process for existence, and whether it hosts PowerShell.
Runspace namedPipeRunspace = null;
switch (ParameterSetName)
{
case ProcessIdParameterSet:
Process = GetProcessById(Id);
VerifyProcess(Process);
namedPipeRunspace = CreateNamedPipeRunspace(Process.Id, AppDomainName);

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.

Interesting, do we really need the VerifyProcess() check (that is File.Exist())? Perhaps the runtime error is informative enough.

@TylerLeonhardt TylerLeonhardt Feb 21, 2019 •

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.

I'm not quite sure what you're saying. This VerifyProcess is to keep the behavior consistent with the current behavior for Process parameter sets.

break;

case ProcessNameParameterSet:
Process = GetProcessByName(Name);
VerifyProcess(Process);
namedPipeRunspace = CreateNamedPipeRunspace(Process.Id, AppDomainName);
break;

case PSHostProcessInfoParameterSet:
Process = GetProcessByHostProcessInfo(HostProcessInfo);
break;
}
VerifyProcess(Process);

VerifyProcess(Process);
// Create named pipe runspace for selected process and open.
namedPipeRunspace = CreateNamedPipeRunspace(Process.Id, AppDomainName);
break;

// Create named pipe runspace for selected process and open.
Runspace namedPipeRunspace = CreateNamedPipeRunspace(Process.Id, AppDomainName);
case PipeNameParameterSet:
VerifyPipeName(CustomPipeName);
namedPipeRunspace = CreateNamedPipeRunspace(CustomPipeName);
break;
}

// Set runspace prompt. The runspace is closed on pop so we don't
// have to reverse this change.
Expand Down Expand Up @@ -187,9 +208,20 @@ protected override void StopProcessing()

#region Private Methods

private Runspace CreateNamedPipeRunspace(string customPipeName)
{
NamedPipeConnectionInfo connectionInfo = new NamedPipeConnectionInfo(customPipeName);
return CreateNamedPipeRunspace(connectionInfo);
}

private Runspace CreateNamedPipeRunspace(int procId, string appDomainName)
{
NamedPipeConnectionInfo connectionInfo = new NamedPipeConnectionInfo(procId, appDomainName);
return CreateNamedPipeRunspace(connectionInfo);
}

private Runspace CreateNamedPipeRunspace(NamedPipeConnectionInfo connectionInfo)
{
TypeTable typeTable = TypeTable.LoadDefaultTypeFiles();
RemoteRunspace remoteRunspace = RunspaceFactory.CreateRunspace(connectionInfo, this.Host, typeTable) as RemoteRunspace;
remoteRunspace.Name = NamedPipeRunspaceName;
Expand All @@ -203,20 +235,40 @@ private Runspace CreateNamedPipeRunspace(int procId, string appDomainName)
}
catch (RuntimeException e)
{
string msgAppDomainName = (!string.IsNullOrEmpty(appDomainName)) ? appDomainName : NamedPipeUtils.DefaultAppDomainName;

// Unwrap inner exception for original error message, if any.
string errorMessage = (e.InnerException != null) ? (e.InnerException.Message ?? string.Empty) : string.Empty;

ThrowTerminatingError(
new ErrorRecord(
new RuntimeException(
StringUtil.Format(RemotingErrorIdStrings.EnterPSHostProcessCannotConnectToProcess,
msgAppDomainName, procId, errorMessage),
e.InnerException),
"EnterPSHostProcessCannotConnectToProcess",
ErrorCategory.OperationTimeout,
this));
if (connectionInfo.CustomPipeName != null)
{
ThrowTerminatingError(
new ErrorRecord(
new RuntimeException(
StringUtil.Format(
RemotingErrorIdStrings.EnterPSHostProcessCannotConnectToPipe,
connectionInfo.CustomPipeName,
errorMessage),
e.InnerException),
"EnterPSHostProcessCannotConnectToPipe",
ErrorCategory.OperationTimeout,
this));
}
else
{
string msgAppDomainName = connectionInfo.AppDomainName ?? NamedPipeUtils.DefaultAppDomainName;

ThrowTerminatingError(
new ErrorRecord(
new RuntimeException(
StringUtil.Format(
RemotingErrorIdStrings.EnterPSHostProcessCannotConnectToProcess,
msgAppDomainName,
connectionInfo.ProcessId,
errorMessage),
e.InnerException),
"EnterPSHostProcessCannotConnectToProcess",
ErrorCategory.OperationTimeout,
this));
}
}
finally
{
Expand Down Expand Up @@ -345,6 +397,33 @@ private void VerifyProcess(Process process)
}
}

private void VerifyPipeName(string customPipeName)
{
// Named Pipes are represented differently on Windows vs macOS & Linux
var sb = new StringBuilder(customPipeName.Length);
if (Platform.IsWindows)
{
sb.Append(@"\\.\pipe\");
}
else
{
sb.Append(Path.GetTempPath()).Append("CoreFxPipe_");
}

sb.Append(customPipeName);

string pipePath = sb.ToString();
if (!File.Exists(pipePath))
{
ThrowTerminatingError(
new ErrorRecord(
new PSArgumentException(StringUtil.Format(RemotingErrorIdStrings.EnterPSHostProcessNoNamedPipeFound, customPipeName)),
"EnterPSHostProcessNoNamedPipeFound",
ErrorCategory.InvalidArgument,
this));
}
}

#endregion
}

Expand Down
Loading