Exemplo n.º 1
0
        /// <summary>
        /// Starts managed MSH
        /// </summary>
        /// <param name="consoleFilePath">
        /// Deprecated: Console file used to create a runspace configuration to start MSH
        /// </param>
        /// <param name="args">
        /// Command line arguments to the managed MSH
        /// </param>
#pragma warning disable 1573
        public static int Start(string consoleFilePath, [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.LPWStr, SizeParamIndex = 2)] string[] args, int argc)
#pragma warning restore 1573
        {
            System.Management.Automation.Runspaces.EarlyStartup.Init();

            // Set ETW activity Id
            Guid activityId = EtwActivity.GetActivityId();

            if (activityId == Guid.Empty)
            {
                EtwActivity.SetActivityId(EtwActivity.CreateActivityId());
            }

            PSEtwLog.LogOperationalInformation(PSEventId.Perftrack_ConsoleStartupStart, PSOpcode.WinStart,
                                               PSTask.PowershellConsoleStartup, PSKeyword.UseAlwaysOperational);

            // Windows Vista and later support non-traditional UI fallback ie., a
            // user on an Arabic machine can choose either French or English(US) as
            // UI fallback language.
            // CLR does not support this (non-traditional) fallback mechanism.
            // The currentUICulture returned NativeCultureResolver supports this non
            // traditional fallback on Vista. So it is important to set currentUICulture
            // in the beginning before we do anything.
            Thread.CurrentThread.CurrentUICulture = NativeCultureResolver.UICulture;
            Thread.CurrentThread.CurrentCulture   = NativeCultureResolver.Culture;

#if DEBUG
            if (args.Length > 0 && !String.IsNullOrEmpty(args[0]) && args[0].Equals("-isswait", StringComparison.OrdinalIgnoreCase))
            {
                Console.WriteLine("Attach the debugger to continue...");
                while (!System.Diagnostics.Debugger.IsAttached)
                {
                    Thread.Sleep(100);
                }
                System.Diagnostics.Debugger.Break();
            }
#endif
            ConsoleHost.DefaultInitialSessionState = InitialSessionState.CreateDefault2();

            int exitCode = 0;
            try
            {
                var banner          = ManagedEntranceStrings.ShellBannerNonWindowsPowerShell;
                var formattedBanner = string.Format(CultureInfo.InvariantCulture, banner, PSVersionInfo.GitCommitId);
                exitCode = Microsoft.PowerShell.ConsoleShell.Start(
                    formattedBanner,
                    ManagedEntranceStrings.UsageHelp,
                    args);
            }
            catch (System.Management.Automation.Host.HostException e)
            {
                if (e.InnerException != null && e.InnerException.GetType() == typeof(System.ComponentModel.Win32Exception))
                {
                    System.ComponentModel.Win32Exception win32e = e.InnerException as System.ComponentModel.Win32Exception;

                    // These exceptions are caused by killing conhost.exe
                    // 1236, network connection aborted by local system
                    // 0x6, invalid console handle
                    if (win32e.NativeErrorCode == 0x6 || win32e.NativeErrorCode == 1236)
                    {
                        return(exitCode);
                    }
                }
                System.Environment.FailFast(e.Message, e);
            }
            catch (Exception e)
            {
                System.Environment.FailFast(e.Message, e);
            }
            return(exitCode);
        }
Exemplo n.º 2
0
        private void ProcessListeningThread(object state)
        {
            string processId     = System.Diagnostics.Process.GetCurrentProcess().Id.ToString(CultureInfo.InvariantCulture);
            string appDomainName = NamedPipeUtils.GetCurrentAppDomainName();

            // Logging.
            _tracer.WriteMessage("RemoteSessionNamedPipeServer", "StartListening", Guid.Empty,
                                 "Listener thread started on Process {0} in AppDomainName {1}.", processId, appDomainName);
            PSEtwLog.LogOperationalInformation(
                PSEventId.NamedPipeIPC_ServerListenerStarted, PSOpcode.Open, PSTask.NamedPipe,
                PSKeyword.UseAlwaysOperational,
                processId, appDomainName);

            Exception ex       = null;
            string    userName = string.Empty;
            bool      restartListenerThread = true;

            // Wait for connection.
            try
            {
                // Begin listening for a client connect.
                this.WaitForConnection();

                try
                {
                    userName = WindowsIdentity.GetCurrent().Name;
                }
                catch (System.Security.SecurityException) { }

                // Logging.
                _tracer.WriteMessage("RemoteSessionNamedPipeServer", "StartListening", Guid.Empty,
                                     "Client connection started on Process {0} in AppDomainName {1} for User {2}.", processId, appDomainName, userName);
                PSEtwLog.LogOperationalInformation(
                    PSEventId.NamedPipeIPC_ServerConnect, PSOpcode.Connect, PSTask.NamedPipe,
                    PSKeyword.UseAlwaysOperational,
                    processId, appDomainName, userName);

                // Create reader/writer streams.
                TextReader           = new StreamReader(Stream);
                TextWriter           = new StreamWriter(Stream);
                TextWriter.AutoFlush = true;
            }
            catch (Exception e)
            {
                CommandProcessorBase.CheckForSevereException(e);
                ex = e;
            }
            if (ex != null)
            {
                // Error during connection handling.  Don't try to restart listening thread.
                string errorMessage = !string.IsNullOrEmpty(ex.Message) ? ex.Message : string.Empty;
                _tracer.WriteMessage("RemoteSessionNamedPipeServer", "StartListening", Guid.Empty,
                                     "Unexpected error in listener thread on process {0} in AppDomainName {1}.  Error Message: {2}", processId, appDomainName, errorMessage);
                PSEtwLog.LogOperationalError(PSEventId.NamedPipeIPC_ServerListenerError, PSOpcode.Exception, PSTask.NamedPipe,
                                             PSKeyword.UseAlwaysOperational,
                                             processId, appDomainName, errorMessage);

                Dispose();
                return;
            }

            // Start server session on new connection.
            ex = null;
            try
            {
                Action <RemoteSessionNamedPipeServer> clientConnectCallback = state as Action <RemoteSessionNamedPipeServer>;
                Dbg.Assert(clientConnectCallback != null, "Client callback should never be null.");

                // Handle a new client connect by making the callback.
                // The callback must handle all exceptions except
                // for a named pipe disposed or disconnected exception
                // which propagates up to the thread listener loop.
                clientConnectCallback(this);
            }
            catch (IOException)
            {
                // Expected connection terminated.
            }
            catch (ObjectDisposedException)
            {
                // Expected from PS transport close/dispose.
            }
            catch (Exception e)
            {
                CommandProcessorBase.CheckForSevereException(e);
                ex = e;
                restartListenerThread = false;
            }

            // Logging.
            _tracer.WriteMessage("RemoteSessionNamedPipeServer", "StartListening", Guid.Empty,
                                 "Client connection ended on process {0} in AppDomainName {1} for User {2}.", processId, appDomainName, userName);
            PSEtwLog.LogOperationalInformation(
                PSEventId.NamedPipeIPC_ServerDisconnect, PSOpcode.Close, PSTask.NamedPipe,
                PSKeyword.UseAlwaysOperational,
                processId, appDomainName, userName);

            if (ex == null)
            {
                // Normal listener exit.
                _tracer.WriteMessage("RemoteSessionNamedPipeServer", "StartListening", Guid.Empty,
                                     "Listener thread ended on process {0} in AppDomainName {1}.", processId, appDomainName);
                PSEtwLog.LogOperationalInformation(PSEventId.NamedPipeIPC_ServerListenerEnded, PSOpcode.Close, PSTask.NamedPipe,
                                                   PSKeyword.UseAlwaysOperational,
                                                   processId, appDomainName);
            }
            else
            {
                // Unexpected error.
                string errorMessage = !string.IsNullOrEmpty(ex.Message) ? ex.Message : string.Empty;
                _tracer.WriteMessage("RemoteSessionNamedPipeServer", "StartListening", Guid.Empty,
                                     "Unexpected error in listener thread on process {0} in AppDomainName {1}.  Error Message: {2}", processId, appDomainName, errorMessage);
                PSEtwLog.LogOperationalError(PSEventId.NamedPipeIPC_ServerListenerError, PSOpcode.Exception, PSTask.NamedPipe,
                                             PSKeyword.UseAlwaysOperational,
                                             processId, appDomainName, errorMessage);
            }

            lock (_syncObject)
            {
                IsListenerRunning = false;
            }

            // Ensure this named pipe server object is disposed.
            Dispose();

            ListenerEnded.SafeInvoke(
                this,
                new ListenerEndedEventArgs(ex, restartListenerThread));
        }
Exemplo n.º 3
0
        public int Start(string consoleFilePath, string[] args)
        {
            int    num;
            string message;
            Guid   activityId = EtwActivity.GetActivityId();

            if (activityId == Guid.Empty)
            {
                EtwActivity.SetActivityId(EtwActivity.CreateActivityId());
            }
            PSEtwLog.LogOperationalInformation(PSEventId.Perftrack_ConsoleStartupStart, PSOpcode.WinStart, PSTask.PowershellConsoleStartup, PSKeyword.UseAlwaysOperational, new object[0]);
            WindowsErrorReporting.RegisterWindowsErrorReporting(false);
            try
            {
                Thread.CurrentThread.CurrentUICulture = NativeCultureResolver.UICulture;
                Thread.CurrentThread.CurrentCulture   = NativeCultureResolver.Culture;
                RunspaceConfigForSingleShell runspaceConfigForSingleShell = null;
                PSConsoleLoadException       pSConsoleLoadException       = null;
                if (!string.IsNullOrEmpty(consoleFilePath))
                {
                    runspaceConfigForSingleShell = RunspaceConfigForSingleShell.Create(consoleFilePath, out pSConsoleLoadException);
                }
                else
                {
                    ConsoleHost.DefaultInitialSessionState = InitialSessionState.CreateDefault2();
                    runspaceConfigForSingleShell           = null;
                    if (Process.GetCurrentProcess().MainWindowHandle != IntPtr.Zero)
                    {
                        ConsoleHost.DefaultInitialSessionState.WarmUpTabCompletionOnIdle = true;
                    }
                }
                int num1 = 0;
                try
                {
                    RunspaceConfigForSingleShell runspaceConfigForSingleShell1 = runspaceConfigForSingleShell;
                    string shellBanner = ManagedEntranceStrings.ShellBanner;
                    string shellHelp   = ManagedEntranceStrings.ShellHelp;
                    if (pSConsoleLoadException == null)
                    {
                        message = null;
                    }
                    else
                    {
                        message = pSConsoleLoadException.Message;
                    }
                    num1 = ConsoleShell.Start(runspaceConfigForSingleShell1, shellBanner, shellHelp, message, args);
                }
                catch (HostException hostException1)
                {
                    HostException hostException = hostException1;
                    if (hostException.InnerException != null && hostException.InnerException.GetType() == typeof(Win32Exception))
                    {
                        Win32Exception innerException = hostException.InnerException as Win32Exception;
                        if (innerException.NativeErrorCode == 6 || innerException.NativeErrorCode == 0x4d4)
                        {
                            num = num1;
                            return(num);
                        }
                    }
                    WindowsErrorReporting.FailFast(hostException);
                }
                catch (Exception exception1)
                {
                    Exception exception = exception1;
                    WindowsErrorReporting.FailFast(exception);
                }
                num = num1;
            }
            finally
            {
                WindowsErrorReporting.WaitForPendingReports();
            }
            return(num);
        }
Exemplo n.º 4
0
#pragma warning restore 1573
#else
        public int Start(string consoleFilePath, string[] args)
#endif
        {
#if !CORECLR
            // For long-path support, Full .NET requires some AppContext switches;
            // (for CoreCLR this is Not needed, because CoreCLR supports long paths by default)
            // internally in .NET they are cached once retrieved and are typically hit very early during an application run;
            // so per .NET team's recommendation, we are setting them as soon as we enter managed code.
            EnableLongPathsInDotNetIfAvailable();
#endif
            System.Management.Automation.Runspaces.EarlyStartup.Init();

            // Set ETW activity Id
            Guid activityId = EtwActivity.GetActivityId();

            if (activityId == Guid.Empty)
            {
                EtwActivity.SetActivityId(EtwActivity.CreateActivityId());
            }

            PSEtwLog.LogOperationalInformation(PSEventId.Perftrack_ConsoleStartupStart, PSOpcode.WinStart,
                                               PSTask.PowershellConsoleStartup, PSKeyword.UseAlwaysOperational);

#if !CORECLR
            // Register crash reports in non-server mode
            WindowsErrorReporting.RegisterWindowsErrorReporting(false);
#endif

            try
            {
                // Windows Vista and later support non-traditional UI fallback ie., a
                // user on an Arabic machine can choose either French or English(US) as
                // UI fallback language.
                // CLR does not support this (non-traditional) fallback mechanism.
                // The currentUICulture returned NativeCultureResolver supports this non
                // traditional fallback on Vista. So it is important to set currentUICulture
                // in the beginning before we do anything.
                ClrFacade.SetCurrentThreadUiCulture(NativeCultureResolver.UICulture);
                ClrFacade.SetCurrentThreadCulture(NativeCultureResolver.Culture);

                RunspaceConfigForSingleShell configuration = null;
                PSConsoleLoadException       warning       = null;
                //      PSSnapInException will cause the control to return back to the native code
                //      and stuff the EXCEPINFO field with the message of the exception.
                //      The native code will print this out and exit the process.
                if (string.IsNullOrEmpty(consoleFilePath))
                {
#if DEBUG
                    // Special switches for debug mode to allow self-hosting on InitialSessionState instead
                    // of runspace configuration...
                    if (args.Length > 0 && !String.IsNullOrEmpty(args[0]) && args[0].Equals("-iss", StringComparison.OrdinalIgnoreCase))
                    {
                        ConsoleHost.DefaultInitialSessionState = InitialSessionState.CreateDefault2();
                        configuration = null;
                    }
                    else if (args.Length > 0 && !String.IsNullOrEmpty(args[0]) && args[0].Equals("-isswait", StringComparison.OrdinalIgnoreCase))
                    {
                        Console.WriteLine("Attach the debugger and hit enter to continue:");
                        Console.ReadLine();
                        ConsoleHost.DefaultInitialSessionState = InitialSessionState.CreateDefault2();
                        configuration = null;
                    }
                    else
                    {
                        ConsoleHost.DefaultInitialSessionState = InitialSessionState.CreateDefault2();
                        configuration = null;
                    }
#else
                    ConsoleHost.DefaultInitialSessionState = InitialSessionState.CreateDefault2();
                    configuration = null;
#endif
                }
                else
                {
                    //TODO : Deprecate RunspaceConfiguration and use InitialSessionState
                    configuration =
                        RunspaceConfigForSingleShell.Create(consoleFilePath, out warning);
                }
                int exitCode = 0;
                try
                {
#if CORECLR
                    var banner = ManagedEntranceStrings.ShellBannerNonWindowsPowerShell;
#else
                    var banner = ManagedEntranceStrings.ShellBanner;
#endif
                    exitCode = Microsoft.PowerShell.ConsoleShell.Start(
                        configuration,
                        banner,
                        ManagedEntranceStrings.ShellHelp,
                        warning == null ? null : warning.Message,
                        args);
                }
                catch (System.Management.Automation.Host.HostException e)
                {
                    if (e.InnerException != null && e.InnerException.GetType() == typeof(System.ComponentModel.Win32Exception))
                    {
                        System.ComponentModel.Win32Exception win32e = e.InnerException as System.ComponentModel.Win32Exception;

                        // These exceptions are caused by killing conhost.exe
                        // 1236, network connection aborted by local system
                        // 0x6, invalid console handle
                        if (win32e.NativeErrorCode == 0x6 || win32e.NativeErrorCode == 1236)
                        {
                            return(exitCode);
                        }
                    }
#if CORECLR
                    System.Environment.FailFast(e.Message);
#else
                    WindowsErrorReporting.FailFast(e);
#endif
                }
                catch (Exception e)
                {
#if CORECLR
                    System.Management.Automation.Environment.FailFast(e.Message);
#else
                    // exceptions caught here should cause Watson.
                    // Must call FailFast; otherwise the exception will be returned to the native code
                    // which will just print out the exception message without Watson
                    WindowsErrorReporting.FailFast(e);
#endif
                }
                return(exitCode);
            }
            finally
            {
#if !CORECLR
                WindowsErrorReporting.WaitForPendingReports();
#endif
            }
        }
Exemplo n.º 5
0
        /// <summary>
        /// Starts managed MSH
        /// </summary>
        /// <param name="consoleFilePath">
        /// Console file used to create a runspace configuration to start MSH
        /// </param>
        /// <param name="args">
        /// Command line arguments to the managed MSH
        /// </param>
#pragma warning disable 1573
        public static int Start(string consoleFilePath, [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.LPWStr, SizeParamIndex = 2)] string[] args, int argc)
#pragma warning restore 1573
        {
            System.Management.Automation.Runspaces.EarlyStartup.Init();

            // Set ETW activity Id
            Guid activityId = EtwActivity.GetActivityId();

            if (activityId == Guid.Empty)
            {
                EtwActivity.SetActivityId(EtwActivity.CreateActivityId());
            }

            PSEtwLog.LogOperationalInformation(PSEventId.Perftrack_ConsoleStartupStart, PSOpcode.WinStart,
                                               PSTask.PowershellConsoleStartup, PSKeyword.UseAlwaysOperational);

            // Windows Vista and later support non-traditional UI fallback ie., a
            // user on an Arabic machine can choose either French or English(US) as
            // UI fallback language.
            // CLR does not support this (non-traditional) fallback mechanism.
            // The currentUICulture returned NativeCultureResolver supports this non
            // traditional fallback on Vista. So it is important to set currentUICulture
            // in the beginning before we do anything.
            Thread.CurrentThread.CurrentUICulture = NativeCultureResolver.UICulture;
            Thread.CurrentThread.CurrentCulture   = NativeCultureResolver.Culture;

            RunspaceConfigForSingleShell configuration = null;
            PSConsoleLoadException       warning       = null;

            //      PSSnapInException will cause the control to return back to the native code
            //      and stuff the EXCEPINFO field with the message of the exception.
            //      The native code will print this out and exit the process.
            if (string.IsNullOrEmpty(consoleFilePath))
            {
#if DEBUG
// Special switches for debug mode to allow self-hosting on InitialSessionState instead
// of runspace configuration...
                if (args.Length > 0 && !String.IsNullOrEmpty(args[0]) && args[0].Equals("-iss", StringComparison.OrdinalIgnoreCase))
                {
                    ConsoleHost.DefaultInitialSessionState = InitialSessionState.CreateDefault2();
                    configuration = null;
                }
                else if (args.Length > 0 && !String.IsNullOrEmpty(args[0]) && args[0].Equals("-isswait", StringComparison.OrdinalIgnoreCase))
                {
                    Console.WriteLine("Attach the debugger and hit enter to continue:");
                    Console.ReadLine();
                    ConsoleHost.DefaultInitialSessionState = InitialSessionState.CreateDefault2();
                    configuration = null;
                }
                else
                {
                    ConsoleHost.DefaultInitialSessionState = InitialSessionState.CreateDefault2();
                    configuration = null;
                }
#else
                ConsoleHost.DefaultInitialSessionState = InitialSessionState.CreateDefault2();
                configuration = null;
#endif
            }
            else
            {
                //TODO : Deprecate RunspaceConfiguration and use InitialSessionState
                configuration =
                    RunspaceConfigForSingleShell.Create(consoleFilePath, out warning);
            }
            int exitCode = 0;
            try
            {
                var banner          = ManagedEntranceStrings.ShellBannerNonWindowsPowerShell;
                var formattedBanner = string.Format(CultureInfo.InvariantCulture, banner, PSVersionInfo.GitCommitId);
                exitCode = Microsoft.PowerShell.ConsoleShell.Start(
                    configuration,
                    formattedBanner,
                    ManagedEntranceStrings.ShellHelp,
                    warning == null ? null : warning.Message,
                    args);
            }
            catch (System.Management.Automation.Host.HostException e)
            {
                if (e.InnerException != null && e.InnerException.GetType() == typeof(System.ComponentModel.Win32Exception))
                {
                    System.ComponentModel.Win32Exception win32e = e.InnerException as System.ComponentModel.Win32Exception;

                    // These exceptions are caused by killing conhost.exe
                    // 1236, network connection aborted by local system
                    // 0x6, invalid console handle
                    if (win32e.NativeErrorCode == 0x6 || win32e.NativeErrorCode == 1236)
                    {
                        return(exitCode);
                    }
                }
                System.Environment.FailFast(e.Message, e);
            }
            catch (Exception e)
            {
                System.Environment.FailFast(e.Message, e);
            }
            return(exitCode);
        }