Skip to content
Closed
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 @@ -1621,12 +1621,25 @@ public sealed class StartProcessCommand : PSCmdlet, IDisposable
public string FilePath { get; set; }

/// <summary>
/// Arguments for the process.
/// Arguments for the process (non-escaped).
/// </summary>
/// <remarks>
/// This option accepts an array of strings due to legacy concerns.
/// The use of multiple elements in the array is deprecated. Any
/// additional parameter is joined by space.
/// Use ArgumentArray instead for properly-escaped arguments.
/// </remarks>
[Parameter(Position = 1)]
[Alias("Args")]
[Alias("Args", "ArgumentList")]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public string[] ArgumentList { get; set; }
public string[] ArgumentString { get; set; }

/// <summary>
/// Arguments for the process (escaped).
/// </summary>
[Parameter]
[Alias("Argv")]
public string[] ArgumentArray { get; set; }

/// <summary>
/// Credentials for the process.
Expand Down Expand Up @@ -1869,13 +1882,19 @@ protected override void BeginProcessing()

// Linux relies on `xdg-open` and macOS relies on `open` which behave differently than Windows ShellExecute when running console commands
// as a new console will be opened. So to avoid that, we only use ShellExecute on non-Windows if the filename is not an actual command (like a URI)
startInfo.UseShellExecute = (ArgumentList == null);
startInfo.UseShellExecute = (ArgumentString == null);
#endif
}

if (ArgumentList != null)
if (ArgumentString != null)
{
// FIXME: make a warning for non-one size?
startInfo.Arguments = string.Join(' ', ArgumentString);
}
else if (ArgumentArray != null)
{
startInfo.Arguments = string.Join(' ', ArgumentList);
// FIXME: make NativeCommandParameterBinder magic public?
startInfo.Arguments = PasteArguments.Paste(ArgumentString, forceQuote: false);
}

if (WorkingDirectory != null)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,9 @@ static ExperimentalFeature()
new ExperimentalFeature(
name: "PSSubsystemPluginModel",
description: "A plugin model for registering and un-registering PowerShell subsystems"),
new ExperimentalFeature(
name: "PSEscapeForNativeExecutables",
description: "Alternative approach for escaping when calling a native executable"),
};
EngineExperimentalFeatures = new ReadOnlyCollection<ExperimentalFeature>(engineFeatures);

Expand Down
192 changes: 135 additions & 57 deletions src/System.Management.Automation/engine/NativeCommandParameterBinder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -188,62 +188,84 @@ private void AppendOneNativeArgument(ExecutionContext context, object obj, Array
}
}

if (!string.IsNullOrEmpty(arg))
// New behavior 1. Allow empty params.
if (!ExperimentalFeature.IsEnabled("PSEscapeForNativeExecutables") &&
!string.IsNullOrEmpty(arg))
{
_arguments.Append(separator);
continue;
}

_arguments.Append(separator);

if (sawVerbatimArgumentMarker)
if (sawVerbatimArgumentMarker)
{
arg = Environment.ExpandEnvironmentVariables(arg);
_arguments.Append(arg);
}
else if (ExperimentalFeature.IsEnabled("PSEscapeForNativeExecutables"))
{
// Only try to glob BareWords.
if (stringConstantType == StringConstantType.BareWord)
{
arg = Environment.ExpandEnvironmentVariables(arg);
_arguments.Append(arg);
PossiblyGlobArg(arg, stringConstantType);
}
else if (stringConstantType == StringConstantType.DoubleQuoted)
{
// We want to retain double quotes for good measure.
AppendArgument(ResolvePath(arg, Context), true);
}
else
{
// We need to add quotes if the argument has unquoted spaces. The
// quotes could appear anywhere inside the string, not just at the start,
// e.g.
// $a = 'a"b c"d'
// echoargs $a 'a"b c"d' a"b c"d
//
// The above should see 3 identical arguments in argv (the command line will
// actually have quotes in different places, but the Win32 command line=>argv parser
// erases those differences.
//
// We need to check quotes that the win32 argument parser checks which is currently
// just the normal double quotes, no other special quotes. Also note that mismatched
// quotes are supported
if (NeedQuotes(arg))
{
_arguments.Append('"');

if (stringConstantType == StringConstantType.DoubleQuoted)
{
_arguments.Append(ResolvePath(arg, Context));
}
else
{
_arguments.Append(arg);
}

// need to escape all trailing backslashes so the native command receives it correctly
// according to http://www.daviddeley.com/autohotkey/parameters/parameters.htm#WINCRULESDOC
for (int i = arg.Length - 1; i >= 0 && arg[i] == '\\'; i--)
{
_arguments.Append('\\');
}
AppendArgument(arg, false);
}
}
else
{
// We need to add quotes if the argument has unquoted spaces. The
// quotes could appear anywhere inside the string, not just at the start,
// e.g.
// $a = 'a"b c"d'
// echoargs $a 'a"b c"d' a"b c"d
//
// The above should see 3 identical arguments in argv (the command line will
// actually have quotes in different places, but the Win32 command line=>argv parser
// erases those differences.
//
// We need to check quotes that the win32 argument parser checks which is currently
// just the normal double quotes, no other special quotes. Also note that mismatched
// quotes are supported
if (NeedQuotes(arg))
{
_arguments.Append('"');

_arguments.Append('"');
if (stringConstantType == StringConstantType.DoubleQuoted)
{
_arguments.Append(ResolvePath(arg, Context));
}
else
{
PossiblyGlobArg(arg, stringConstantType);
_arguments.Append(arg);
}

// need to escape all trailing backslashes so the native command receives it correctly
// according to http://www.daviddeley.com/autohotkey/parameters/parameters.htm#WINCRULESDOC
for (int i = arg.Length - 1; i >= 0 && arg[i] == '\\'; i--)
{
_arguments.Append('\\');
}

_arguments.Append('"');
}
else
{
PossiblyGlobArg(arg, stringConstantType);
}
}
}
while (list != null);
}


/// <summary>
/// On Windows, just append <paramref name="arg"/>.
/// On Unix, do globbing as appropriate, otherwise just append <paramref name="arg"/>.
Expand All @@ -253,11 +275,9 @@ private void AppendOneNativeArgument(ExecutionContext context, object obj, Array
private void PossiblyGlobArg(string arg, StringConstantType stringConstantType)
{
var argExpanded = false;

#if UNIX
// On UNIX systems, we expand arguments containing wildcard expressions against
// the file system just like bash, etc.

if (stringConstantType == StringConstantType.BareWord)
{
if (WildcardPattern.ContainsWildcardCharacters(arg))
Expand Down Expand Up @@ -286,6 +306,7 @@ private void PossiblyGlobArg(string arg, StringConstantType stringConstantType)
// Expand paths, but only from the file system.
if (paths?.Count > 0 && paths.All(p => p.BaseObject is FileSystemInfo))
{
argExpanded = true;
var sep = string.Empty;
foreach (var path in paths)
{
Expand All @@ -297,20 +318,9 @@ private void PossiblyGlobArg(string arg, StringConstantType stringConstantType)
expandedPath =
Context.SessionState.Path.NormalizeRelativePath(expandedPath, cwdinfo.ProviderPath);
}
// If the path contains spaces, then add quotes around it.
if (NeedQuotes(expandedPath))
{
_arguments.Append("\"");
_arguments.Append(expandedPath);
_arguments.Append("\"");
}
else
{
_arguments.Append(expandedPath);
}

argExpanded = true;
AppendArgument(expandedPath, null);
}

}
}
}
Expand All @@ -328,7 +338,7 @@ private void PossiblyGlobArg(string arg, StringConstantType stringConstantType)
else if (arg.StartsWith("~/", StringComparison.OrdinalIgnoreCase))
{
var replacementString = home + arg.Substring(1);
_arguments.Append(replacementString);
AppendArgument(replacementString, false);
argExpanded = true;
}
}
Expand All @@ -342,7 +352,7 @@ private void PossiblyGlobArg(string arg, StringConstantType stringConstantType)

if (!argExpanded)
{
_arguments.Append(arg);
AppendArgument(arg, false);
}
}

Expand Down Expand Up @@ -408,9 +418,13 @@ internal static string ResolvePath(string path, ExecutionContext context)
return path;
}


/// <summary>
/// Check to see if the string contains spaces and therefore must be quoted.
/// See if the string contains unquoted spaces and therefore must be quoted.
/// </summary>
/// <remarks>
/// Very simple check that breaks down with (2n+1) backslashes. Kept for compatibility.
/// </remarks>
/// <param name="stringToCheck">The string to check for spaces.</param>
internal static bool NeedQuotes(string stringToCheck)
{
Expand Down Expand Up @@ -458,12 +472,76 @@ private static string GetEnumerableArgSeparator(ArrayLiteralAst arrayLiteralAst,
return " , ";
}

/// <summary>
/// Append an argument to the internal buffer, without separator.
/// </summary>
/// <param name="arg">The string to append.</param>
/// <param name="doQuote">For legacy mode, whether quotes should be used; for modern escape, whether to force quotes.</param>
private void AppendArgument(string arg, bool? doQuote)
{
if (ExperimentalFeature.IsEnabled("PSEscapeForNativeExecutables"))
{
// Split into two parts by = or : to appease msiexec et al.
bool forceQuote = doQuote ?? false;
(string[] pieces, string sep) = splitOption(arg);
bool first = true;

foreach (string piece in pieces)
{
if (!first)
{
_arguments.Append(sep);
if (piece.Length == 0)
{
// No need to turn `abc:` into `abc:""`
continue;
}
}

PasteArguments.AppendArgument(_arguments, piece, forceQuote: forceQuote);
first = false;
}
}
else
{
bool quote = doQuote ?? NeedQuotes(arg);
_arguments.Append(quote ? arg : $"\"{arg}\"");
}
}

/// <summary>
/// Split an argument into parts that can be appended separately.
/// </summary>
private (string[], string) splitOption(string arg)
{
string[] pieces = arg.Split(OptionDeliminators, 2);
string sep = "";

// Contains separator?
if (pieces.Length > 1)
{
sep = arg[pieces[0].Length].ToString();
}

// Special case: only accept : when starting with [/-].
// (Just to make C:\Program Files look better.)
// The better solution might be using a different set of delims?
if (sep == ":" && !ColonInitials.Contains(arg[0]))
{
return (new[] { arg }, "");
}

return (pieces, sep);
}

/// <summary>
/// The native command to bind to.
/// </summary>
private NativeCommand _nativeCommand;
private static readonly string TildeDirectorySeparator = $"~{Path.DirectorySeparatorChar}";
private static readonly string TildeAltDirectorySeparator = $"~{Path.AltDirectorySeparatorChar}";
private static readonly char[] OptionDeliminators = { ':', '=' };
private const string ColonInitials = "-/";

#endregion private members
}
Expand Down
Loading