Пример #1
0
 static RunspaceFactory()
 {
     if (EtwActivity.GetActivityId() == Guid.Empty)
     {
         EtwActivity.SetActivityId(EtwActivity.CreateActivityId());
     }
 }
Пример #2
0
        /// <summary>
        /// Static constructor.
        /// </summary>
        static RunspaceFactory()
        {
            // Set ETW activity Id
            Guid activityId = EtwActivity.GetActivityId();

            if (activityId == Guid.Empty)
            {
                EtwActivity.SetActivityId(EtwActivity.CreateActivityId());
            }
        }
Пример #3
0
            /// <summary>
            /// EtwCorrelator Constructor.
            /// </summary>
            /// <param name="tracer"></param>
            /// <param name="callback"></param>
            public CorrelatedCallback(EtwActivity tracer, CallbackWithStateAndArgs callback)
            {
                if (callback == null)
                {
                    throw new ArgumentNullException(nameof(callback));
                }

                if (tracer == null)
                {
                    throw new ArgumentNullException(nameof(tracer));
                }

                this.tracer                   = tracer;
                this.parentActivityId         = EtwActivity.GetActivityId();
                this.callbackWithStateAndArgs = callback;
            }
Пример #4
0
 private DataServiceController(DSConfiguration settings, CustomAuthorizationHandler.ICustomContextStore customContextStore, ISchemaBuilder testSchemaBuilder)
 {
     TraceHelper.Current.CorrelateWithActivity(EtwActivity.GetActivityId());
     try
     {
         this.Configuration = settings;
         this.cmdManagers   = new Dictionary <ManagementSystemType, ICommandManager>();
         this.PerfCounters  = new PerfCounters(CurrentRequestHelper.EndPointAddress);
         this.UserDataCache = new UserDataCache(this.Configuration.Invocation.Lifetime);
         this.QuotaSystem   = new QuotaSystem();
         InitialSessionStateManager initialSessionStateManager = new InitialSessionStateManager(this.Configuration.PowerShell.SessionConfig.Assembly, this.Configuration.PowerShell.SessionConfig.Type);
         this.intialSessionStateStore = new SharedItemStore <InitialSessionState, UserContext>(initialSessionStateManager, this.Configuration.Quotas.UserSchemaTimeout, this.Configuration.Quotas.MaxUserSchemas);
         PSRunspaceFactory pSRunspaceFactory = new PSRunspaceFactory(this.intialSessionStateStore, true);
         int runspaceTimeout = this.Configuration.PowerShell.Quotas.RunspaceTimeout;
         ExclusiveItemStore <PSRunspace, UserContext> exclusiveItemStore = new ExclusiveItemStore <PSRunspace, UserContext>(pSRunspaceFactory, runspaceTimeout, this.Configuration.PowerShell.Quotas.MaxRunspaces);
         PSCommandManager pSCommandManager = new PSCommandManager(exclusiveItemStore);
         this.cmdManagers.Add(ManagementSystemType.PowerShell, pSCommandManager);
         PSRunspaceFactory pSRunspaceFactory1 = new PSRunspaceFactory(this.intialSessionStateStore, false);
         ExclusiveItemStore <PSRunspace, UserContext> exclusiveItemStore1 = new ExclusiveItemStore <PSRunspace, UserContext>(pSRunspaceFactory1, runspaceTimeout, this.Configuration.PowerShell.Quotas.MaxRunspaces);
         this.cmdManagers.Add(ManagementSystemType.GenericInvoke, new GICommandManager(exclusiveItemStore1));
         List <ISchemaBuilder> schemaBuilders = new List <ISchemaBuilder>();
         if (testSchemaBuilder != null)
         {
             schemaBuilders.Add(testSchemaBuilder);
         }
         schemaBuilders.Add(new PSSchemaBuilder(exclusiveItemStore));
         schemaBuilders.Add(new GISchemaBuilder());
         SchemaFactory schemaFactory = new SchemaFactory(this.Configuration.SchemaFileName, this.Configuration.ResourceMappingFileName, schemaBuilders, settings);
         this.schemaStore = new SharedItemStore <Microsoft.Management.Odata.Schema.Schema, UserContext>(schemaFactory, this.Configuration.Quotas.UserSchemaTimeout, this.Configuration.Quotas.MaxUserSchemas);
         this.customAuthorizationHandler = new CustomAuthorizationHandler(this.Configuration.CustomAuthorization.Assembly, this.Configuration.CustomAuthorization.Type, customContextStore);
     }
     catch (Exception exception1)
     {
         Exception exception = exception1;
         TraceHelper.Current.DataServiceControllerCreationFailedOperational(exception.Message);
         if (TraceHelper.IsEnabled(5))
         {
             TraceHelper.Current.DebugMessage(exception.ToTraceMessage("DataServiceController failed to create"));
         }
         if (this.PerfCounters != null)
         {
             this.PerfCounters.Dispose();
         }
         throw;
     }
     TraceHelper.Current.DataServiceControllerCreationSucceeded();
 }
Пример #5
0
        public static void ProcessingRequestHandler(object source, DataServiceProcessingPipelineEventArgs args)
        {
            UserData userDatum = null;

            TraceHelper.Current.DebugMessage("QuotaSystem.ProcessingRequestHandler entered");
            if (args != null && args.OperationContext != null)
            {
                TraceHelper.CorrelateWithClientRequestId(args.OperationContext);
            }
            UserContext userContext = new UserContext(CurrentRequestHelper.Identity, CurrentRequestHelper.Certificate);

            if (!DataServiceController.Current.IsRequestProcessingStarted(userContext))
            {
                UserDataCache.UserDataEnvelope userDataEnvelope = DataServiceController.Current.UserDataCache.Get(userContext);
                using (userDataEnvelope)
                {
                    UserQuota userQuota = DataServiceController.Current.GetUserQuota(userContext);
                    if (args != null)
                    {
                        Guid activityId = EtwActivity.GetActivityId();
                        args.OperationContext.ResponseHeaders.Add("request-id", activityId.ToString());
                    }
                    if (userDataEnvelope.Data.Usage.QuotaCheckAndUpdate(userContext, userQuota))
                    {
                        DataServiceController.Current.UserDataCache.TryLockKey(userContext, out userDatum);
                    }
                    else
                    {
                        throw new DataServiceException(0x193, ExceptionHelpers.GetDataServiceExceptionMessage(HttpStatusCode.Forbidden, Resources.UserQuotaExceeded, new object[0]));
                    }
                }
                DataServiceController.Current.SetRequestProcessingState(userContext, true);
                TraceHelper.Current.RequestProcessingStart();
                DataServiceController.Current.UserDataCache.Trace();
                TraceHelper.Current.DebugMessage("QuotaSystem.ProcessingRequestHandler exited");
                return;
            }
            else
            {
                TraceHelper.Current.DebugMessage("QuotaSystem.ProcessingRequestHandler IsRequestProcessingStarted returned true");
                return;
            }
        }
Пример #6
0
 private void DoCompleteCore(CommandProcessorBase commandRequestingUpstreamCommandsToStop)
 {
     for (int i = 0; i < this._commands.Count; i++)
     {
         CommandProcessorBase objB = this._commands[i];
         if (objB == null)
         {
             throw PSTraceSource.NewInvalidOperationException();
         }
         if (object.ReferenceEquals(commandRequestingUpstreamCommandsToStop, objB))
         {
             commandRequestingUpstreamCommandsToStop = null;
         }
         else if (commandRequestingUpstreamCommandsToStop == null)
         {
             try
             {
                 objB.DoComplete();
             }
             catch (PipelineStoppedException)
             {
                 StopUpstreamCommandsException firstTerminatingError = this.firstTerminatingError as StopUpstreamCommandsException;
                 if (firstTerminatingError == null)
                 {
                     throw;
                 }
                 this.firstTerminatingError = null;
                 commandRequestingUpstreamCommandsToStop = firstTerminatingError.RequestingCommandProcessor;
             }
             EtwActivity.SetActivityId(objB.PipelineActivityId);
             MshLog.LogCommandLifecycleEvent(objB.Command.Context, CommandState.Stopped, objB.Command.MyInvocation);
         }
     }
     if (this.firstTerminatingError != null)
     {
         this.LogExecutionException(this.firstTerminatingError);
         throw this.firstTerminatingError;
     }
 }
        protected override bool CheckAccessCore(OperationContext operationContext)
        {
            TraceHelper.Current.CorrelateWithActivity(EtwActivity.GetActivityId());
            TraceHelper.Current.RequestStart();
            DataServiceController.Current.PerfCounters.ActiveRequests.Increment();
            operationContext.TraceIncomingMessage();
            bool             flag        = false;
            IIdentity        identity    = CurrentRequestHelper.Identity;
            X509Certificate2 certificate = CurrentRequestHelper.Certificate;

            identity.Trace();
            if (identity == null || !identity.IsAuthenticated)
            {
                TraceHelper.Current.DebugMessage(string.Concat("Unauthenticated user tried to access", identity.ToTraceMessage()));
            }
            else
            {
                UserContext userContext = new UserContext(identity, certificate);
                userContext.Trace();
                flag = DataServiceController.Current.IsAuthorized(userContext, operationContext.IncomingMessageHeaders.To);
            }
            if (!flag)
            {
                if (identity == null)
                {
                    TraceHelper.Current.UserNotAuthorized(string.Empty, string.Empty);
                }
                else
                {
                    TraceHelper.Current.UserNotAuthorized(identity.Name, identity.AuthenticationType);
                }
                HttpResponseMessageProperty httpResponseMessageProperty = new HttpResponseMessageProperty();
                httpResponseMessageProperty.StatusCode = HttpStatusCode.Unauthorized;
                operationContext.OutgoingMessageProperties.Add(HttpResponseMessageProperty.Name, httpResponseMessageProperty);
            }
            return(flag);
        }
Пример #8
0
 private void Start(bool incomingStream)
 {
     if (this.disposed)
     {
         throw PSTraceSource.NewObjectDisposedException("PipelineProcessor");
     }
     if (this.Stopping)
     {
         throw new PipelineStoppedException();
     }
     if (!this.executionStarted)
     {
         if ((this._commands == null) || (this._commands.Count == 0))
         {
             throw PSTraceSource.NewInvalidOperationException("PipelineStrings", "PipelineExecuteRequiresAtLeastOneCommand", new object[0]);
         }
         CommandProcessorBase base2 = this._commands[0];
         if ((base2 == null) || (base2.CommandRuntime == null))
         {
             throw PSTraceSource.NewInvalidOperationException("PipelineStrings", "PipelineExecuteRequiresAtLeastOneCommand", new object[0]);
         }
         if (this.executionScope == null)
         {
             this.executionScope = base2.Context.EngineSessionState.CurrentScope;
         }
         CommandProcessorBase base3 = this._commands[this._commands.Count - 1];
         if ((base3 == null) || (base3.CommandRuntime == null))
         {
             throw PSTraceSource.NewInvalidOperationException();
         }
         if (this.ExternalSuccessOutput != null)
         {
             base3.CommandRuntime.OutputPipe.ExternalWriter = this.ExternalSuccessOutput;
         }
         this.SetExternalErrorOutput();
         if ((this.ExternalInput == null) && !incomingStream)
         {
             base2.CommandRuntime.IsClosed = true;
         }
         IDictionary variableValue = base2.Context.GetVariableValue(SpecialVariables.PSDefaultParameterValuesVarPath, false) as IDictionary;
         this.executionStarted = true;
         int[] numArray = new int[this._commands.Count + 1];
         for (int i = 0; i < this._commands.Count; i++)
         {
             CommandProcessorBase base4 = this._commands[i];
             if (base4 == null)
             {
                 throw PSTraceSource.NewInvalidOperationException();
             }
             Guid engineActivityId = base4.Context.CurrentRunspace.EngineActivityId;
             Guid activityId       = EtwActivity.CreateActivityId();
             EtwActivity.SetActivityId(activityId);
             base4.PipelineActivityId = activityId;
             MshLog.LogCommandLifecycleEvent(base4.Context, CommandState.Started, base4.Command.MyInvocation);
             InvocationInfo myInvocation = base4.Command.MyInvocation;
             myInvocation.PipelinePosition      = i + 1;
             myInvocation.PipelineLength        = this._commands.Count;
             myInvocation.PipelineIterationInfo = numArray;
             base4.DoPrepare(variableValue);
             myInvocation.ExpectingInput = base4.IsPipelineInputExpected();
         }
         this.SetupOutErrorVariable();
         for (int j = 0; j < this._commands.Count; j++)
         {
             this._commands[j].DoBegin();
         }
     }
 }
Пример #9
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);
        }
Пример #10
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
            }
        }
Пример #11
0
        private void InvokeHelper()
        {
            PipelineProcessor item = null;

            try
            {
                base.RaisePipelineStateEvents();
                this.RecordPipelineStartTime();
                try
                {
                    item = this.CreatePipelineProcessor();
                }
                catch (Exception exception)
                {
                    if (base.SetPipelineSessionState)
                    {
                        base.SetHadErrors(true);
                        this.Runspace.ExecutionContext.AppendDollarError(exception);
                    }
                    throw;
                }
                if (this.useExternalInput)
                {
                    item.ExternalInput = base.InputStream.ObjectReader;
                }
                item.ExternalSuccessOutput = base.OutputStream.ObjectWriter;
                item.ExternalErrorOutput   = base.ErrorStream.ObjectWriter;
                if (!this.IsChild)
                {
                    this.LocalRunspace.ExecutionContext.InternalHost.InternalUI.SetInformationalMessageBuffers(base.InformationalBuffers);
                }
                bool questionMarkVariableValue = true;
                bool exceptionHandlerInEnclosingStatementBlock = this.LocalRunspace.ExecutionContext.ExceptionHandlerInEnclosingStatementBlock;
                this.LocalRunspace.ExecutionContext.ExceptionHandlerInEnclosingStatementBlock = false;
                try
                {
                    this._stopper.Push(item);
                    if (!base.AddToHistory)
                    {
                        questionMarkVariableValue = this.LocalRunspace.ExecutionContext.QuestionMarkVariableValue;
                        this.LocalRunspace.ExecutionContext.IgnoreScriptDebug = true;
                    }
                    else
                    {
                        this.LocalRunspace.ExecutionContext.IgnoreScriptDebug = false;
                    }
                    if (!this.IsNested && !base.IsPulsePipeline)
                    {
                        this.LocalRunspace.ExecutionContext.ResetRedirection();
                    }
                    try
                    {
                        item.Execute();
                        base.SetHadErrors(item.ExecutionFailed);
                    }
                    catch (ExitException exception2)
                    {
                        base.SetHadErrors(item.ExecutionFailed);
                        int newValue = 1;
                        if (this.IsNested)
                        {
                            try
                            {
                                newValue = (int)exception2.Argument;
                                this.LocalRunspace.ExecutionContext.SetVariable(SpecialVariables.LastExitCodeVarPath, newValue);
                                return;
                            }
                            finally
                            {
                                try
                                {
                                    this.LocalRunspace.ExecutionContext.EngineHostInterface.ExitNestedPrompt();
                                }
                                catch (ExitNestedPromptException)
                                {
                                }
                            }
                        }
                        try
                        {
                            newValue = (int)exception2.Argument;
                        }
                        finally
                        {
                            this.LocalRunspace.ExecutionContext.EngineHostInterface.SetShouldExit(newValue);
                        }
                    }
                    catch (ExitNestedPromptException)
                    {
                    }
                    catch (FlowControlException)
                    {
                    }
                    catch (Exception)
                    {
                        base.SetHadErrors(true);
                        throw;
                    }
                }
                finally
                {
                    if ((item != null) && (item.Commands != null))
                    {
                        for (int i = 0; i < item.Commands.Count; i++)
                        {
                            CommandProcessorBase base2 = item.Commands[i];
                            EtwActivity.SetActivityId(base2.PipelineActivityId);
                            MshLog.LogCommandLifecycleEvent(base2.Context, CommandState.Terminated, base2.Command.MyInvocation);
                        }
                    }
                    PSLocalEventManager events = this.LocalRunspace.Events as PSLocalEventManager;
                    if (events != null)
                    {
                        events.ProcessPendingActions();
                    }
                    this.LocalRunspace.ExecutionContext.ExceptionHandlerInEnclosingStatementBlock = exceptionHandlerInEnclosingStatementBlock;
                    if (!this.IsChild)
                    {
                        this.LocalRunspace.ExecutionContext.InternalHost.InternalUI.SetInformationalMessageBuffers(null);
                    }
                    this._stopper.Pop(false);
                    if (!base.AddToHistory)
                    {
                        this.LocalRunspace.ExecutionContext.QuestionMarkVariableValue = questionMarkVariableValue;
                    }
                }
            }
            catch (FlowControlException)
            {
            }
            finally
            {
                if (item != null)
                {
                    item.Dispose();
                    item = null;
                }
            }
        }
Пример #12
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);
        }
Пример #13
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);
        }