Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
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 @@ -162,7 +162,7 @@ internal override void StartOperation()
}

thread.IsBackground = true;
// thread.SetApartmentState( ApartmentState.STA);
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -395,7 +395,6 @@ private object SafeCreateInstance(Type t, object[] args)
return result;
}

#if !CORECLR
private class ComCreateInfo
{
public object objectCreated;
Expand Down Expand Up @@ -435,7 +434,6 @@ private void STAComCreateThreadProc(Object createstruct)
info.success = false;
}
}
#endif

private object CreateComObject()
{
Expand All @@ -459,13 +457,6 @@ private object CreateComObject()
// Check Error Code to see if Error is because of Com apartment Mismatch.
if (e.HResult == RPC_E_CHANGED_MODE)
{
#if CORECLR
ThrowTerminatingError(
new ErrorRecord(
new COMException(StringUtil.Format(NewObjectStrings.ApartmentNotSupported, e.Message), e),
"NoCOMClassIdentified",
ErrorCategory.ResourceUnavailable, null));
#else
createInfo = new ComCreateInfo();

Thread thread = new Thread(new ParameterizedThreadStart(STAComCreateThreadProc));
Expand All @@ -482,7 +473,6 @@ private object CreateComObject()
ThrowTerminatingError(
new ErrorRecord(createInfo.e, "NoCOMClassIdentified",
ErrorCategory.ResourceUnavailable, null));
#endif
}
else
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -173,10 +173,8 @@ internal class CommandLineParameterParser
private const int MaxPipePathLengthMacOS = 104;

internal static string[] validParameters = {
#if STAMODE
"sta",
"mta",
#endif
"command",
"configurationname",
"custompipename",
Expand Down Expand Up @@ -644,7 +642,6 @@ private void DisplayBanner()
}
}

#if STAMODE
internal bool StaMode
{
get
Expand All @@ -655,14 +652,10 @@ internal bool StaMode
}
else
{
// Nano doesn't support STA COM apartment, so on Nano powershell has to use MTA as the default.
// return false;
// Win8: 182409 PowerShell 3.0 should run in STA mode by default
return true;
}
}
}
#endif

/// <summary>
/// Processes all the command line parameters to ConsoleHost. Returns the exit code to be used to terminate the process, or
Expand Down Expand Up @@ -944,10 +937,15 @@ private void ParseHelper(string[] args)
break;
}
}
#if STAMODE
// explicit setting of the ApartmentState Not supported on NanoServer
else if (MatchSwitch(switchKey, "sta", "s"))
{
if (!Platform.IsWindowsDesktop)
{
WriteCommandLineError(
CommandLineParameterParserStrings.STANotImplemented);
break;
}

if (_staMode.HasValue)
{
// -sta and -mta are mutually exclusive.
Expand All @@ -958,10 +956,15 @@ private void ParseHelper(string[] args)

_staMode = true;
}
// Win8: 182409 PowerShell 3.0 should run in STA mode by default..so, consequently adding the switch -mta.
// Not deleting -sta for backward compatability reasons
else if (MatchSwitch(switchKey, "mta", "mta"))
{
if (!Platform.IsWindowsDesktop)
{
WriteCommandLineError(
CommandLineParameterParserStrings.MTANotImplemented);
break;
}

if (_staMode.HasValue)
{
// -sta and -mta are mutually exclusive.
Expand All @@ -972,7 +975,6 @@ private void ParseHelper(string[] args)

_staMode = false;
}
#endif
else if (MatchSwitch(switchKey, "workingdirectory", "wo") || MatchSwitch(switchKey, "wd", "wd"))
{
++i;
Expand Down Expand Up @@ -1406,15 +1408,7 @@ private bool CollectArgs(string[] args, ref int i)
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
// if true, then sta is specified on the command line.
// if false, then mta is specified on the command line.
// if null, then none is specified on the command line..use default in this case
// default is sta.
private bool? _staMode = null;
#endif
private bool _noExit = true;
private bool _explicitReadCommandsFromStdin;
private bool _noPrompt;
Expand Down
28 changes: 5 additions & 23 deletions src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1373,11 +1373,7 @@ private uint Run(CommandLineParameterParser cpp, bool isPrestartWarned)

// NTRAID#Windows Out Of Band Releases-915506-2005/09/09
// Removed HandleUnexpectedExceptions infrastructure
#if STAMODE
exitCode = DoRunspaceLoop(cpp.InitialCommand, cpp.SkipProfiles, cpp.Args, cpp.StaMode, cpp.ConfigurationName);
#else
exitCode = DoRunspaceLoop(cpp.InitialCommand, cpp.SkipProfiles, cpp.Args, false, cpp.ConfigurationName);
#endif
}
while (false);

Expand Down Expand Up @@ -1452,12 +1448,12 @@ private uint DoRunspaceLoop(string initialCommand, bool skipProfiles, Collection

_runspaceRef.Runspace.Close();
_runspaceRef = null;
#if STAMODE
if (staMode) // don't recycle the Runspace in STA mode

if (staMode)
{
// don't continue the session in STA mode
ShouldEndSession = true;
}
#endif
}

return ExitCode;
Expand Down Expand Up @@ -1496,11 +1492,7 @@ private void CreateRunspace(object runspaceCreationArgs)
{
args = runspaceCreationArgs as RunspaceCreationEventArgs;
Dbg.Assert(args != null, "Event Arguments to CreateRunspace should not be null");
#if STAMODE
DoCreateRunspace(args.InitialCommand, args.SkipProfiles, args.StaMode, args.ConfigurationName, args.InitialCommandArgs);
#else
DoCreateRunspace(args.InitialCommand, args.SkipProfiles, false, args.ConfigurationName, args.InitialCommandArgs);
#endif
}
catch (ConsoleHostStartupException startupException)
{
Expand Down Expand Up @@ -1618,17 +1610,11 @@ private void DoCreateRunspace(string initialCommand, bool skipProfiles, bool sta

private void OpenConsoleRunspace(Runspace runspace, bool staMode)
{
#if STAMODE
// staMode will have following values:
// On FullPS: 'true'/'false' = default('true'=STA) + possibility of overload through cmdline parameter '-mta'
// On NanoPS: always 'false' = default('false'=MTA) + NO possibility of overload through cmdline parameter '-mta'
// ThreadOptions should match on FullPS and NanoPS for corresponding ApartmentStates.
if (staMode)
if (staMode && Platform.IsWindowsDesktop)
{
// we can't change ApartmentStates on CoreCLR
runspace.ApartmentState = ApartmentState.STA;
}
#endif

runspace.ThreadOptions = PSThreadOptions.ReuseThread;
runspace.EngineActivityId = EtwActivity.GetActivityId();

Expand Down Expand Up @@ -2896,18 +2882,14 @@ internal RunspaceCreationEventArgs(
{
InitialCommand = initialCommand;
SkipProfiles = skipProfiles;
#if STAMODE
StaMode = staMode;
#endif
ConfigurationName = configurationName;
InitialCommandArgs = initialCommandArgs;
}

internal string InitialCommand { get; set; }
internal bool SkipProfiles { get; set; }
#if STAMODE
internal bool StaMode { get; set; }
#endif
internal string ConfigurationName { get; set; }
internal Collection<CommandParameter> InitialCommandArgs { get; set; }
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -210,4 +210,10 @@
<data name="MissingWorkingDirectoryArgument" xml:space="preserve">
<value>Cannot process the command because -WorkingDirectory requires an argument that is a directory path.</value>
</data>
<data name="MTANotImplemented" xml:space="preserve">
<value>Parameter -MTA is not supported on this platform.</value>
</data>
<data name="STANotImplemented" xml:space="preserve">
<value>Parameter -STA is not supported on this platform.</value>
</data>
</root>
Original file line number Diff line number Diff line change
Expand Up @@ -131,8 +131,8 @@ Type 'help' to get help.</value>
[-ConfigurationName &lt;string&gt;] [-CustomPipeName &lt;string&gt;]
[-EncodedCommand &lt;Base64EncodedCommand&gt;]
[-ExecutionPolicy &lt;ExecutionPolicy&gt;] [-InputFormat {Text | XML}]
[-Interactive] [-LoadProfile] [-NoExit] [-NoLogo] [-NonInteractive] [-NoProfile]
[-OutputFormat {Text | XML}] [-SettingsFile &lt;filePath&gt;] [-Version]
[-Interactive] [-LoadProfile] [-MTA] [-NoExit] [-NoLogo] [-NonInteractive] [-NoProfile]
[-OutputFormat {Text | XML}] [-SettingsFile &lt;filePath&gt;] [-STA] [-Version]
[-WindowStyle &lt;style&gt;] [-WorkingDirectory &lt;directoryPath&gt;]

pwsh[.exe] -h | -Help | -? | /?
Expand Down Expand Up @@ -298,6 +298,11 @@ All parameters are case-insensitive.</value>
Load the PowerShell profiles. This is the default behavior even if this is
not specified.

-MTA

Start the shell using a multi-threaded apartment.
Only available on Windows.

-NoExit | -noe

Does not exit after running startup commands.
Expand Down Expand Up @@ -334,6 +339,11 @@ Hides the copyright banner at startup.

Example: "pwsh -SettingsFile c:\myproject\powershell.config.json"

-STA

Start the shell using a single-threaded apartment. This is the default.
Only available on Windows.

-Version | -v

Displays the version of PowerShell. Additional parameters are ignored.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1671,9 +1671,7 @@ public InitialSessionState Clone()
ss.UseFullLanguageModeInDebugger = this.UseFullLanguageModeInDebugger;
ss.ThreadOptions = this.ThreadOptions;
ss.ThrowOnRunspaceOpenError = this.ThrowOnRunspaceOpenError;
#if !CORECLR // No ApartmentState In CoreCLR
ss.ApartmentState = this.ApartmentState;
#endif

foreach (ModuleSpecification modSpec in this.ModuleSpecificationsToImport)
{
Expand Down Expand Up @@ -1812,14 +1810,11 @@ public Microsoft.PowerShell.ExecutionPolicy ExecutionPolicy
/// </summary>
public bool UseFullLanguageModeInDebugger { get; set; } = false;

#if !CORECLR // No ApartmentState In CoreCLR
/// <summary>
/// ApartmentState of the thread used to execute commands.
/// </summary>
public ApartmentState ApartmentState { get; set; } = Runspace.DefaultApartmentState;

#endif

/// <summary>
/// This property determines whether a new thread is created for each invocation of a command.
/// </summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -582,7 +582,6 @@ public static bool CanUseDefaultRunspace
}
}

#if !CORECLR // No ApartmentState In CoreCLR
internal const ApartmentState DefaultApartmentState = ApartmentState.Unknown;

/// <summary>
Expand Down Expand Up @@ -613,7 +612,6 @@ public ApartmentState ApartmentState
}

private ApartmentState apartmentState = Runspace.DefaultApartmentState;
#endif

/// <summary>
/// This property determines whether a new thread is create for each invocation.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -77,10 +77,7 @@ protected RunspaceBase(PSHost host, InitialSessionState initialSessionState)
Host = host;
InitialSessionState = initialSessionState.Clone();
this.ThreadOptions = initialSessionState.ThreadOptions;

#if !CORECLR // No ApartmentState In CoreCLR
this.ApartmentState = initialSessionState.ApartmentState;
#endif
}

/// <summary>
Expand Down Expand Up @@ -126,10 +123,7 @@ protected RunspaceBase(PSHost host, InitialSessionState initialSessionState, boo
}

this.ThreadOptions = initialSessionState.ThreadOptions;

#if !CORECLR // No ApartmentState In CoreCLR
this.ApartmentState = initialSessionState.ApartmentState;
#endif
}

/// <summary>
Expand Down Expand Up @@ -920,7 +914,6 @@ internal bool WaitForFinishofPipelines()
waitHandles[i] = runningPipelines[i].PipelineFinishedEvent;
}

#if !CORECLR // No ApartmentState.STA In CoreCLR
// WaitAll for multiple handles on a STA (single-thread apartment) thread is not supported as WaitAll will prevent the message pump to run
if (runningPipelines.Length > 1 && Thread.CurrentThread.GetApartmentState() == ApartmentState.STA)
{
Expand All @@ -940,7 +933,7 @@ internal bool WaitForFinishofPipelines()
return waitAllIsDone.WaitOne();
}
}
#endif

return WaitHandle.WaitAll(waitHandles);
}
else
Expand Down
Loading