Beispiel #1
0
        // Keep in sync:
        // S.M.A.CommandProcessorBase.CheckForSevereException
        // S.M.A.Internal.ConsoleHost.CheckForSevereException
        // S.M.A.Commands.CommandsCommon.CheckForSevereException
        // S.M.A.Commands.UtilityCommon.CheckForSevereException
        /// <summary>
        /// Checks whether the exception is a severe exception which should
        /// cause immediate process failure.
        /// </summary>
        /// <param name="cmdlet"></param>
        /// <param name="e"></param>
        /// <remarks>
        /// CB says 02/23/2005: I personally would err on the side
        /// of treating OOM like an application exception, rather than
        /// a critical system failure.I think this will be easier to justify
        /// in Orcas, if we tease apart the two cases of OOM better.
        /// But even in Whidbey, how likely is it that we couldnt JIT
        /// some backout code?  At that point, the process or possibly
        /// the machine is likely to stop executing soon no matter
        /// what you do in this routine.  So I would just consider
        /// AccessViolationException.  (I understand why you have SO here,
        /// at least temporarily).
        /// </remarks>
        internal static void CheckForSevereException(Cmdlet cmdlet, Exception e)
        {
            if (e is AccessViolationException || e is StackOverflowException)
            {
                try
                {
                    if (!alreadyFailing)
                    {
                        alreadyFailing = true;

                        // Log a command health event for this critical error.
                        MshLog.LogCommandHealthEvent(
                            cmdlet.Context,
                            e,
                            Severity.Critical);
                    }
                }
                finally
                {
                    if (!designForTestability_SkipFailFast)
                    {
                        WindowsErrorReporting.FailFast(e);
                    }
                }
            }
        }
Beispiel #2
0
 internal void FlushLog()
 {
     if (((this._commands != null) && (this._commands.Count > 0)) && (this.logBuffer.Count != 0))
     {
         MshLog.LogPipelineExecutionDetailEvent(this._commands[0].Command.Context, this.logBuffer, this._commands[0].Command.MyInvocation);
     }
 }
Beispiel #3
0
        internal bool RecordFailure(Exception e, InternalCommand command)
        {
            bool stopping = false;

            lock (this.StopReasonLock)
            {
                if (this.firstTerminatingError == null)
                {
                    RuntimeException.LockStackTrace(e);
                    this.firstTerminatingError = e;
                }
                else if ((!(this.firstTerminatingError is PipelineStoppedException) && (command != null)) && (command.Context != null))
                {
                    Exception innerException = e;
                    while (((innerException is TargetInvocationException) || (innerException is CmdletInvocationException)) && (innerException.InnerException != null))
                    {
                        innerException = innerException.InnerException;
                    }
                    if (!(innerException is PipelineStoppedException))
                    {
                        InvalidOperationException exception = new InvalidOperationException(StringUtil.Format(PipelineStrings.SecondFailure, new object[] { this.firstTerminatingError.GetType().Name, this.firstTerminatingError.StackTrace, innerException.GetType().Name, innerException.StackTrace }), innerException);
                        MshLog.LogCommandHealthEvent(command.Context, exception, Severity.Warning);
                    }
                }
                stopping      = this.stopping;
                this.stopping = true;
            }
            return(!stopping);
        }
 internal void Initialize(ExecutionContext executionContext)
 {
     lock (this._syncObject)
     {
         if (!this._initialized)
         {
             this._initialized      = true;
             this.Types.OnUpdate   += new RunspaceConfigurationEntryUpdateEventHandler(this.UpdateTypes);
             this.Formats.OnUpdate += new RunspaceConfigurationEntryUpdateEventHandler(this.UpdateFormats);
             runspaceInitTracer.WriteLine("initializing types information", new object[0]);
             try
             {
                 this.UpdateTypes(true);
             }
             catch (RuntimeException exception)
             {
                 runspaceInitTracer.WriteLine("type information initialization failed", new object[0]);
                 MshLog.LogEngineHealthEvent(executionContext, 0x67, exception, Severity.Warning);
                 executionContext.ReportEngineStartupError(exception.Message);
             }
             runspaceInitTracer.WriteLine("initializing format information", new object[0]);
             try
             {
                 this.UpdateFormats(true);
             }
             catch (RuntimeException exception2)
             {
                 runspaceInitTracer.WriteLine("format information initialization failed", new object[0]);
                 MshLog.LogEngineHealthEvent(executionContext, 0x67, exception2, Severity.Warning);
                 executionContext.ReportEngineStartupError(exception2.Message);
             }
         }
     }
 }
        protected override void ProcessRecord()
        {
            string shellID         = base.Context.ShellID;
            string executionPolicy = SecuritySupport.GetExecutionPolicy(this.ExecutionPolicy);

            if (this.ShouldProcessPolicyChange(executionPolicy))
            {
                SecuritySupport.SetExecutionPolicy(this.executionPolicyScope, this.ExecutionPolicy, shellID);
                if (this.ExecutionPolicy != ExecutionPolicy.Undefined)
                {
                    string str = SecuritySupport.GetExecutionPolicy(shellID).ToString();
                    if (!string.Equals(str, executionPolicy, StringComparison.OrdinalIgnoreCase))
                    {
                        string      str1 = StringUtil.Format(ExecutionPolicyCommands.ExecutionPolicyOverridden, str);
                        string      executionPolicyOverriddenRecommendedAction = ExecutionPolicyCommands.ExecutionPolicyOverriddenRecommendedAction;
                        ErrorRecord errorRecord = new ErrorRecord(new SecurityException(), "ExecutionPolicyOverride", ErrorCategory.PermissionDenied, null);
                        errorRecord.ErrorDetails = new ErrorDetails(str1);
                        errorRecord.ErrorDetails.RecommendedAction = executionPolicyOverriddenRecommendedAction;
                        base.ThrowTerminatingError(errorRecord);
                    }
                }
                PSSQMAPI.UpdateExecutionPolicy(shellID, this.ExecutionPolicy);
                PSEtwLog.LogSettingsEvent(MshLog.GetLogContext(base.Context, base.MyInvocation), EtwLoggingStrings.ExecutionPolicyName, executionPolicy, null);
            }
        }
Beispiel #6
0
        /// <summary>
        /// Seeks to the end of the writer stream in each of the writers in the
        /// content holders.
        /// </summary>
        ///
        /// <param name="contentHolders">
        /// The content holders that contain the writers to be moved.
        /// </param>
        ///
        /// <exception cref="ProviderInvocationException">
        /// If calling Seek on the content writer throws an exception.
        /// </exception>
        ///
        internal override void SeekContentPosition(List <ContentHolder> contentHolders)
        {
            foreach (ContentHolder holder in contentHolders)
            {
                if (holder.Writer != null)
                {
                    try
                    {
                        holder.Writer.Seek(0, System.IO.SeekOrigin.End);
                    }
                    catch (Exception e) // Catch-all OK, 3rd party callout
                    {
                        ProviderInvocationException providerException =
                            new ProviderInvocationException(
                                "ProviderSeekError",
                                SessionStateStrings.ProviderSeekError,
                                holder.PathInfo.Provider,
                                holder.PathInfo.Path,
                                e);


                        // Log a provider health event

                        MshLog.LogProviderHealthEvent(
                            this.Context,
                            holder.PathInfo.Provider.Name,
                            providerException,
                            Severity.Warning);

                        throw providerException;
                    }
                }
            }
        } // SeekContentPosition
        /// <summary>
        /// End processing
        /// </summary>
        protected override void EndProcessing()
        {
            foreach (UpdatableHelpExceptionContext exception in _exceptions.Values)
            {
                UpdatableHelpExceptionContext e = exception;

                if ((exception.Exception.FullyQualifiedErrorId == "HelpCultureNotSupported") &&
                    ((exception.Cultures != null && exception.Cultures.Count > 1) ||
                     (exception.Modules != null && exception.Modules.Count > 1)))
                {
                    // Win8: 744749 Rewriting the error message only in the case where either
                    // multiple cultures or multiple modules are involved.
                    e = new UpdatableHelpExceptionContext(new UpdatableHelpSystemException(
                                                              "HelpCultureNotSupported", StringUtil.Format(HelpDisplayStrings.CannotMatchUICulturePattern,
                                                                                                           string.Join(", ", exception.Cultures)),
                                                              ErrorCategory.InvalidArgument, exception.Cultures, null));
                    e.Modules  = exception.Modules;
                    e.Cultures = exception.Cultures;
                }

                WriteError(e.CreateErrorRecord(_commandType));

                LogContext context = MshLog.GetLogContext(Context, MyInvocation);

                context.Severity = "Error";

                PSEtwLog.LogOperationalError(PSEventId.Pipeline_Detail, PSOpcode.Exception, PSTask.ExecutePipeline,
                                             context, e.GetExceptionMessage(_commandType));
            }
        }
Beispiel #8
0
        // Keep in sync:
        // S.M.A.CommandProcessorBase.CheckForSevereException
        // S.M.A.Internal.ConsoleHost.CheckForSevereException
        // S.M.A.Commands.CommandsCommon.CheckForSevereException
        // S.M.A.Commands.UtilityCommon.CheckForSevereException
        /// <summary>
        /// Checks whether the exception is a severe exception which should
        /// cause immediate process failure.
        /// </summary>
        /// <param name="cmdlet">can be null</param>
        /// <param name="e"></param>
        /// <remarks>
        /// CB says 02/23/2005: I personally would err on the side
        /// of treating OOM like an application exception, rather than
        /// a critical system failure.I think this will be easier to justify
        /// in Orcas, if we tease apart the two cases of OOM better.
        /// But even in Whidbey, how likely is it that we couldnt JIT
        /// some backout code?  At that point, the process or possibly
        /// the machine is likely to stop executing soon no matter
        /// what you do in this routine.  So I would just consider
        /// AccessViolationException.  (I understand why you have SO here,
        /// at least temporarily).
        /// </remarks>
        internal static void CheckForSevereException(PSCmdlet cmdlet, Exception e)
        {
            if (e is AccessViolationException || e is StackOverflowException)
            {
                try
                {
                    if (!alreadyFailing)
                    {
                        alreadyFailing = true;

                        // Get the ExecutionContext from the thread.
                        ExecutionContext context =
                            (null != cmdlet)
                                ? cmdlet.Context
                                : LocalPipeline.GetExecutionContextFromTLS();

                        // Log a command health event for this critical error.
                        MshLog.LogCommandHealthEvent(context, e, Severity.Critical);
                    }
                }
                finally
                {
                    if (!designForTestability_SkipFailFast)
                    {
                        WindowsErrorReporting.FailFast(e);
                    }
                }
            }
        }
Beispiel #9
0
 private void DisposeCommands()
 {
     this.stopping = true;
     this.FlushLog();
     if (this._commands != null)
     {
         for (int i = 0; i < this._commands.Count; i++)
         {
             CommandProcessorBase base2 = this._commands[i];
             if (base2 != null)
             {
                 try
                 {
                     base2.CommandRuntime.RemoveVariableListsInPipe();
                     base2.Dispose();
                 }
                 catch (Exception exception)
                 {
                     CommandProcessorBase.CheckForSevereException(exception);
                     InvocationInfo myInvocation = null;
                     if (base2.Command != null)
                     {
                         myInvocation = base2.Command.MyInvocation;
                     }
                     ProviderInvocationException innerException = exception as ProviderInvocationException;
                     if (innerException != null)
                     {
                         exception = new CmdletProviderInvocationException(innerException, myInvocation);
                     }
                     else
                     {
                         exception = new CmdletInvocationException(exception, myInvocation);
                         MshLog.LogCommandHealthEvent(base2.Command.Context, exception, Severity.Warning);
                     }
                     this.RecordFailure(exception, base2.Command);
                 }
             }
         }
     }
     this._commands = null;
     if (this._redirectionPipes != null)
     {
         foreach (PipelineProcessor processor in this._redirectionPipes)
         {
             try
             {
                 if (processor != null)
                 {
                     processor.Dispose();
                 }
             }
             catch (Exception exception3)
             {
                 CommandProcessorBase.CheckForSevereException(exception3);
             }
         }
     }
     this._redirectionPipes = null;
 }
        internal void LogMessage(string message)
        {
            List <string> pipelineExecutionDetail = new List <string> {
                message
            };

            PSEtwLog.LogPipelineExecutionDetailEvent(MshLog.GetLogContext(base.Context, base.Context.CurrentCommandProcessor.Command.MyInvocation), pipelineExecutionDetail);
        }
Beispiel #11
0
 internal void Bind(ExecutionContext executionContext)
 {
     this._host = (PSHost)executionContext.EngineHostInterface;
     this.Initialize(executionContext);
     this.Assemblies.OnUpdate += new RunspaceConfigurationEntryUpdateEventHandler(executionContext.UpdateAssemblyCache);
     RunspaceConfiguration.runspaceInitTracer.WriteLine("initializing assembly list", new object[0]);
     try
     {
         this.Assemblies.Update(true);
     }
     catch (RuntimeException ex)
     {
         RunspaceConfiguration.runspaceInitTracer.WriteLine("assembly list initialization failed", new object[0]);
         RunspaceConfiguration.runspaceInitTracer.TraceException((Exception)ex);
         RunspaceConfiguration.tracer.TraceException((Exception)ex);
         MshLog.LogEngineHealthEvent(executionContext, 103, (Exception)ex, Severity.Error);
         executionContext.ReportEngineStartupError(ex.Message);
         throw;
     }
     if (executionContext.CommandDiscovery != null)
     {
         this.Cmdlets.OnUpdate += new RunspaceConfigurationEntryUpdateEventHandler(executionContext.CommandDiscovery.UpdateCmdletCache);
         RunspaceConfiguration.runspaceInitTracer.WriteLine("initializing cmdlet list", new object[0]);
         try
         {
             this.Cmdlets.Update(true);
         }
         catch (PSNotSupportedException ex)
         {
             RunspaceConfiguration.runspaceInitTracer.WriteLine("cmdlet list initialization failed", new object[0]);
             RunspaceConfiguration.runspaceInitTracer.TraceException((Exception)ex);
             RunspaceConfiguration.tracer.TraceException((Exception)ex);
             MshLog.LogEngineHealthEvent(executionContext, 103, (Exception)ex, Severity.Error);
             executionContext.ReportEngineStartupError(ex.Message);
             throw;
         }
     }
     if (executionContext.EngineSessionState == null)
     {
         return;
     }
     this.Providers.OnUpdate += new RunspaceConfigurationEntryUpdateEventHandler(executionContext.EngineSessionState.UpdateProviders);
     RunspaceConfiguration.runspaceInitTracer.WriteLine("initializing provider list", new object[0]);
     try
     {
         this.Providers.Update(true);
     }
     catch (PSNotSupportedException ex)
     {
         RunspaceConfiguration.runspaceInitTracer.WriteLine("provider list initialization failed", new object[0]);
         RunspaceConfiguration.runspaceInitTracer.TraceException((Exception)ex);
         RunspaceConfiguration.tracer.TraceException((Exception)ex);
         MshLog.LogEngineHealthEvent(executionContext, 103, (Exception)ex, Severity.Error);
         executionContext.ReportEngineStartupError(ex.Message);
         throw;
     }
 }
Beispiel #12
0
        /// <summary>
        /// Logs a command message.
        /// </summary>
        /// <param name="message">Message to log.</param>
        internal void LogMessage(string message)
        {
            List <string> details = new List <string>()
            {
                message
            };

            PSEtwLog.LogPipelineExecutionDetailEvent(MshLog.GetLogContext(Context, Context.CurrentCommandProcessor.Command.MyInvocation), details);
        }
        /// <summary>
        /// Logs a command message
        /// </summary>
        /// <param name="message">Message to log.</param>
        internal void LogMessage(string message)
        {
            List <string> details = new List <string>();

            details.Add(message);
#if !CORECLR // TODO:CORECLR Uncomment when we add PSEtwLog support
            PSEtwLog.LogPipelineExecutionDetailEvent(MshLog.GetLogContext(Context, Context.CurrentCommandProcessor.Command.MyInvocation), details);
#endif
        }
Beispiel #14
0
 internal void CloseContent(List <ContentCommandBase.ContentHolder> contentHolders, bool disposing)
 {
     if (contentHolders != null)
     {
         foreach (ContentCommandBase.ContentHolder contentHolder in contentHolders)
         {
             try
             {
                 if (contentHolder.Writer != null)
                 {
                     contentHolder.Writer.Close();
                 }
             }
             catch (Exception exception1)
             {
                 Exception exception = exception1;
                 CommandsCommon.CheckForSevereException(this, exception);
                 ProviderInvocationException providerInvocationException = new ProviderInvocationException("ProviderContentCloseError", SessionStateStrings.ProviderContentCloseError, contentHolder.PathInfo.Provider, contentHolder.PathInfo.Path, exception);
                 MshLog.LogProviderHealthEvent(base.Context, contentHolder.PathInfo.Provider.Name, providerInvocationException, Severity.Warning);
                 if (!disposing)
                 {
                     base.WriteError(new ErrorRecord(providerInvocationException.ErrorRecord, providerInvocationException));
                 }
             }
             try
             {
                 if (contentHolder.Reader != null)
                 {
                     contentHolder.Reader.Close();
                 }
             }
             catch (Exception exception3)
             {
                 Exception exception2 = exception3;
                 CommandsCommon.CheckForSevereException(this, exception2);
                 ProviderInvocationException providerInvocationException1 = new ProviderInvocationException("ProviderContentCloseError", SessionStateStrings.ProviderContentCloseError, contentHolder.PathInfo.Provider, contentHolder.PathInfo.Path, exception2);
                 MshLog.LogProviderHealthEvent(base.Context, contentHolder.PathInfo.Provider.Name, providerInvocationException1, Severity.Warning);
                 if (!disposing)
                 {
                     base.WriteError(new ErrorRecord(providerInvocationException1.ErrorRecord, providerInvocationException1));
                 }
             }
         }
         return;
     }
     else
     {
         throw PSTraceSource.NewArgumentNullException("contentHolders");
     }
 }
Beispiel #15
0
        internal void Initialize(ExecutionContext executionContext)
        {
#pragma warning disable 56517

            lock (_syncObject)
            {
                if (!_initialized)
                {
                    _initialized = true;

                    this.Types.OnUpdate   += this.UpdateTypes;
                    this.Formats.OnUpdate += this.UpdateFormats;

                    s_runspaceInitTracer.WriteLine("initializing types information");
                    try
                    {
                        this.UpdateTypes();
                    }
                    catch (RuntimeException e)
                    {
                        s_runspaceInitTracer.WriteLine("type information initialization failed");
                        MshLog.LogEngineHealthEvent(
                            executionContext,
                            MshLog.EVENT_ID_CONFIGURATION_FAILURE,
                            e,
                            Severity.Warning);
                        executionContext.ReportEngineStartupError(e.Message);
                    }

                    s_runspaceInitTracer.WriteLine("initializing format information");
                    try
                    {
                        this.UpdateFormats(true);
                    }
                    catch (RuntimeException e)
                    {
                        s_runspaceInitTracer.WriteLine("format information initialization failed");
                        MshLog.LogEngineHealthEvent(
                            executionContext,
                            MshLog.EVENT_ID_CONFIGURATION_FAILURE,
                            e,
                            Severity.Warning);
                        executionContext.ReportEngineStartupError(e.Message);
                    }
                }
            }

#pragma warning restore 56517
        }
Beispiel #16
0
 public void WriteError(ErrorRecord errorRecord)
 {
     using (PSTransactionManager.GetEngineProtectionScope())
     {
         if (errorRecord == null)
         {
             throw CmdletProvider.providerBaseTracer.NewArgumentNullException(nameof(errorRecord));
         }
         if (errorRecord.ErrorDetails != null && errorRecord.ErrorDetails.TextLookupError != null)
         {
             MshLog.LogProviderHealthEvent(this.Context.ExecutionContext, this.ProviderInfo.Name, errorRecord.ErrorDetails.TextLookupError, Severity.Warning);
         }
         this.Context.WriteError(errorRecord);
     }
 }
Beispiel #17
0
 private void ValidateAndThrowRunspaceOpenModuleLoadException(PowerShell pse, List <ErrorRecord> errors, bool startLifeCycleEventWritten, string moduleName, RunspaceOpenModuleLoadException exception)
 {
     if (this.InitialSessionState.ThrowOnRunspaceOpenError)
     {
         RunspaceOpenModuleLoadException exception2 = null;
         if (exception != null)
         {
             exception2 = exception;
         }
         else if ((pse.Streams.Error.Count > 0) || (errors.Count > 0))
         {
             ErrorRecord record;
             Exception   exception3;
             PSDataCollection <ErrorRecord> datas = new PSDataCollection <ErrorRecord>();
             if (errors.Count > 0)
             {
                 record     = errors[0];
                 exception3 = record.Exception;
                 foreach (ErrorRecord record2 in errors)
                 {
                     datas.Add(record2);
                 }
             }
             else
             {
                 record     = pse.Streams.Error[0];
                 exception3 = record.Exception;
                 foreach (ErrorRecord record3 in pse.Streams.Error)
                 {
                     datas.Add(record3);
                 }
             }
             runspaceInitTracer.WriteLine("Runspace open failed while loading module '{0}': First error {1}", new object[] { moduleName, exception3 });
             exception2 = new RunspaceOpenModuleLoadException(moduleName, datas);
         }
         if (exception2 != null)
         {
             this.LogEngineHealthEvent(exception2);
             if (startLifeCycleEventWritten)
             {
                 MshLog.LogEngineLifecycleEvent(this._engine.Context, EngineState.Stopped);
             }
             base.SetRunspaceState(RunspaceState.Broken, exception2);
             base.RaiseRunspaceStateEvents();
             throw exception2;
         }
     }
 }
Beispiel #18
0
        /// <summary>
        /// Set the desired execution policy.
        /// </summary>
        protected override void ProcessRecord()
        {
            string shellId         = base.Context.ShellID;
            string executionPolicy = SecuritySupport.GetExecutionPolicy(ExecutionPolicy);

            if (ShouldProcessPolicyChange(executionPolicy))
            {
                try
                {
                    SecuritySupport.SetExecutionPolicy(_executionPolicyScope, ExecutionPolicy, shellId);
                }
                catch (UnauthorizedAccessException exception)
                {
                    OnAccessDeniedError(exception);
                }
                catch (System.Security.SecurityException exception)
                {
                    OnAccessDeniedError(exception);
                }

                // Ensure it is now the effective execution policy
                if (ExecutionPolicy != ExecutionPolicy.Undefined)
                {
                    string effectiveExecutionPolicy = SecuritySupport.GetExecutionPolicy(shellId).ToString();
                    if (!string.Equals(effectiveExecutionPolicy, executionPolicy, StringComparison.OrdinalIgnoreCase))
                    {
                        string message           = StringUtil.Format(ExecutionPolicyCommands.ExecutionPolicyOverridden, effectiveExecutionPolicy);
                        string recommendedAction = ExecutionPolicyCommands.ExecutionPolicyOverriddenRecommendedAction;

                        ErrorRecord errorRecord = new ErrorRecord(
                            new System.Security.SecurityException(),
                            "ExecutionPolicyOverride",
                            ErrorCategory.PermissionDenied,
                            null);

                        errorRecord.ErrorDetails = new ErrorDetails(message);
                        errorRecord.ErrorDetails.RecommendedAction = recommendedAction;
                        ThrowTerminatingError(errorRecord);
                    }
                }

#if !CORECLR
                PSEtwLog.LogSettingsEvent(MshLog.GetLogContext(Context, MyInvocation),
                                          EtwLoggingStrings.ExecutionPolicyName, executionPolicy, null);
#endif
            }
        }//End ProcessRecord()
Beispiel #19
0
 public void ThrowTerminatingError(ErrorRecord errorRecord)
 {
     using (PSTransactionManager.GetEngineProtectionScope())
     {
         if (errorRecord == null)
         {
             throw CmdletProvider.providerBaseTracer.NewArgumentNullException(nameof(errorRecord));
         }
         if (errorRecord.ErrorDetails != null && errorRecord.ErrorDetails.TextLookupError != null)
         {
             Exception textLookupError = errorRecord.ErrorDetails.TextLookupError;
             errorRecord.ErrorDetails.TextLookupError = (Exception)null;
             MshLog.LogProviderHealthEvent(this.Context.ExecutionContext, this.ProviderInfo.Name, textLookupError, Severity.Warning);
         }
         ProviderInvocationException invocationException = new ProviderInvocationException(this.ProviderInfo, errorRecord);
         MshLog.LogProviderHealthEvent(this.Context.ExecutionContext, this.ProviderInfo.Name, (Exception)invocationException, Severity.Warning);
         throw invocationException;
     }
 }
Beispiel #20
0
 public void ThrowTerminatingError(ErrorRecord errorRecord)
 {
     using (PSTransactionManager.GetEngineProtectionScope())
     {
         if (errorRecord == null)
         {
             throw PSTraceSource.NewArgumentNullException("errorRecord");
         }
         if ((errorRecord.ErrorDetails != null) && (errorRecord.ErrorDetails.TextLookupError != null))
         {
             Exception textLookupError = errorRecord.ErrorDetails.TextLookupError;
             errorRecord.ErrorDetails.TextLookupError = null;
             MshLog.LogProviderHealthEvent(this.Context.ExecutionContext, this.ProviderInfo.Name, textLookupError, Severity.Warning);
         }
         ProviderInvocationException exception2 = new ProviderInvocationException(this.ProviderInfo, errorRecord);
         MshLog.LogProviderHealthEvent(this.Context.ExecutionContext, this.ProviderInfo.Name, exception2, Severity.Warning);
         throw exception2;
     }
 }
 protected override void EndProcessing()
 {
     foreach (UpdatableHelpExceptionContext context in this.exceptions.Values)
     {
         UpdatableHelpExceptionContext context2 = context;
         if ((context.Exception.FullyQualifiedErrorId == "HelpCultureNotSupported") && (((context.Cultures != null) && (context.Cultures.Count > 1)) || ((context.Modules != null) && (context.Modules.Count > 1))))
         {
             context2 = new UpdatableHelpExceptionContext(new UpdatableHelpSystemException("HelpCultureNotSupported", StringUtil.Format(HelpDisplayStrings.CannotMatchUICulturePattern, string.Join(", ", context.Cultures)), ErrorCategory.InvalidArgument, context.Cultures, null))
             {
                 Modules  = context.Modules,
                 Cultures = context.Cultures
             };
         }
         base.WriteError(context2.CreateErrorRecord(this._commandType));
         LogContext logContext = MshLog.GetLogContext(base.Context, base.MyInvocation);
         logContext.Severity = "Error";
         PSEtwLog.LogOperationalError(PSEventId.Pipeline_Detail, PSOpcode.Exception, PSTask.ExecutePipeline, logContext, context2.GetExceptionMessage(this._commandType));
     }
 }
Beispiel #22
0
 private void DoCloseHelper()
 {
     base.StopPipelines();
     this.StopOrDisconnectAllJobs();
     this.CloseOrDisconnectAllRemoteRunspaces(delegate {
         List <RemoteRunspace> list = new List <RemoteRunspace>();
         foreach (PSSession session in this.RunspaceRepository.Runspaces)
         {
             list.Add(session.Runspace as RemoteRunspace);
         }
         return(list);
     });
     this._engine.Context.RunspaceClosingNotification();
     MshLog.LogEngineLifecycleEvent(this._engine.Context, EngineState.Stopped);
     this._engine         = null;
     this._commandFactory = null;
     base.SetRunspaceState(RunspaceState.Closed);
     base.RaiseRunspaceStateEvents();
 }
Beispiel #23
0
        internal void LogEngineHealthEvent(Exception exception, Severity severity, int id, Dictionary <string, string> additionalInfo)
        {
            LogContext logContext = new LogContext {
                EngineVersion = this.Version.ToString(),
                HostId        = base.Host.InstanceId.ToString(),
                HostName      = base.Host.Name,
                HostVersion   = base.Host.Version.ToString(),
                RunspaceId    = base.InstanceId.ToString(),
                Severity      = severity.ToString()
            };

            if (this.RunspaceConfiguration == null)
            {
                logContext.ShellId = Utils.DefaultPowerShellShellID;
            }
            else
            {
                logContext.ShellId = this.RunspaceConfiguration.ShellId;
            }
            MshLog.LogEngineHealthEvent(logContext, id, exception, additionalInfo);
        }
Beispiel #24
0
 internal static void CheckForSevereException(Cmdlet cmdlet, Exception e)
 {
     if (e as AccessViolationException != null || e as StackOverflowException != null)
     {
         try
         {
             if (!CommandsCommon.alreadyFailing)
             {
                 CommandsCommon.alreadyFailing = true;
                 MshLog.LogCommandHealthEvent(cmdlet.Context, e, Severity.Critical);
             }
         }
         finally
         {
             if (!CommandsCommon.designForTestability_SkipFailFast)
             {
                 WindowsErrorReporting.FailFast(e);
             }
         }
     }
 }
Beispiel #25
0
 internal override void SeekContentPosition(List <ContentCommandBase.ContentHolder> contentHolders)
 {
     foreach (ContentCommandBase.ContentHolder contentHolder in contentHolders)
     {
         if (contentHolder.Writer == null)
         {
             continue;
         }
         try
         {
             contentHolder.Writer.Seek((long)0, SeekOrigin.End);
         }
         catch (Exception exception1)
         {
             Exception exception = exception1;
             CommandsCommon.CheckForSevereException(this, exception);
             ProviderInvocationException providerInvocationException = new ProviderInvocationException("ProviderSeekError", SessionStateStrings.ProviderSeekError, contentHolder.PathInfo.Provider, contentHolder.PathInfo.Path, exception);
             MshLog.LogProviderHealthEvent(base.Context, contentHolder.PathInfo.Provider.Name, providerInvocationException, Severity.Warning);
             throw providerInvocationException;
         }
     }
 }
Beispiel #26
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;
     }
 }
Beispiel #27
0
 internal static void CheckForSevereException(PSCmdlet cmdlet, Exception e)
 {
     if ((e is AccessViolationException) || (e is StackOverflowException))
     {
         try
         {
             if (!alreadyFailing)
             {
                 alreadyFailing = true;
                 ExecutionContext executionContext = (cmdlet != null) ? cmdlet.Context : LocalPipeline.GetExecutionContextFromTLS();
                 MshLog.LogCommandHealthEvent(executionContext, e, Severity.Critical);
             }
         }
         finally
         {
             if (!designForTestability_SkipFailFast)
             {
                 WindowsErrorReporting.FailFast(e);
             }
         }
     }
 }
Beispiel #28
0
        /// <summary>
        /// Appends the content to the specified item.
        /// </summary>
        protected override void ProcessRecord()
        {
            CmdletProviderContext currentContext = GetCurrentContext();

            // Initialize the content

            if (_content == null)
            {
                _content = Array.Empty <object>();
            }

            if (_pipingPaths)
            {
                // Make sure to clean up the content writers that are already there

                if (contentStreams != null && contentStreams.Count > 0)
                {
                    CloseContent(contentStreams, false);
                    _contentWritersOpen = false;
                    contentStreams      = new List <ContentHolder>();
                }
            }

            if (!_contentWritersOpen)
            {
                // Since the paths are being pipelined in, we have
                // to get new content writers for the new paths
                string[] paths = GetAcceptedPaths(Path, currentContext);

                if (paths.Length > 0)
                {
                    BeforeOpenStreams(paths);
                    contentStreams = GetContentWriters(paths, currentContext);
                    SeekContentPosition(contentStreams);
                }

                _contentWritersOpen = true;
            }

            // Now write the content to the item
            try
            {
                foreach (ContentHolder holder in contentStreams)
                {
                    if (holder.Writer != null)
                    {
                        IList result = null;
                        try
                        {
                            result = holder.Writer.Write(_content);
                        }
                        catch (Exception e) // Catch-all OK. 3rd party callout
                        {
                            ProviderInvocationException providerException =
                                new(
                                    "ProviderContentWriteError",
                                    SessionStateStrings.ProviderContentWriteError,
                                    holder.PathInfo.Provider,
                                    holder.PathInfo.Path,
                                    e);

                            // Log a provider health event

                            MshLog.LogProviderHealthEvent(
                                this.Context,
                                holder.PathInfo.Provider.Name,
                                providerException,
                                Severity.Warning);

                            WriteError(
                                new ErrorRecord(
                                    providerException.ErrorRecord,
                                    providerException));
                            continue;
                        }

                        if (result != null && result.Count > 0 && PassThru)
                        {
                            WriteContentObject(result, result.Count, holder.PathInfo, currentContext);
                        }
                    }
                }
            }
            finally
            {
                // Need to close all the writers if the paths are being pipelined

                if (_pipingPaths)
                {
                    CloseContent(contentStreams, false);
                    _contentWritersOpen = false;
                    contentStreams      = new List <ContentHolder>();
                }
            }
        }
Beispiel #29
0
        /// <summary>
        /// Closes the content readers and writers in the content holder array
        /// </summary>
        internal void CloseContent(List <ContentHolder> contentHolders, bool disposing)
        {
            if (contentHolders == null)
            {
                throw PSTraceSource.NewArgumentNullException("contentHolders");
            }

            foreach (ContentHolder holder in contentHolders)
            {
                try
                {
                    if (holder.Writer != null)
                    {
                        holder.Writer.Close();
                    }
                }
                catch (Exception e) // Catch-all OK. 3rd party callout
                {
                    // Catch all the exceptions caused by closing the writer
                    // and write out an error.

                    ProviderInvocationException providerException =
                        new ProviderInvocationException(
                            "ProviderContentCloseError",
                            SessionStateStrings.ProviderContentCloseError,
                            holder.PathInfo.Provider,
                            holder.PathInfo.Path,
                            e);

                    // Log a provider health event

                    MshLog.LogProviderHealthEvent(
                        this.Context,
                        holder.PathInfo.Provider.Name,
                        providerException,
                        Severity.Warning);

                    if (!disposing)
                    {
                        WriteError(
                            new ErrorRecord(
                                providerException.ErrorRecord,
                                providerException));
                    }
                }

                try
                {
                    if (holder.Reader != null)
                    {
                        holder.Reader.Close();
                    }
                }
                catch (Exception e) // Catch-all OK. 3rd party callout
                {
                    // Catch all the exceptions caused by closing the writer
                    // and write out an error.

                    ProviderInvocationException providerException =
                        new ProviderInvocationException(
                            "ProviderContentCloseError",
                            SessionStateStrings.ProviderContentCloseError,
                            holder.PathInfo.Provider,
                            holder.PathInfo.Path,
                            e);

                    // Log a provider health event

                    MshLog.LogProviderHealthEvent(
                        this.Context,
                        holder.PathInfo.Provider.Name,
                        providerException,
                        Severity.Warning);

                    if (!disposing)
                    {
                        WriteError(
                            new ErrorRecord(
                                providerException.ErrorRecord,
                                providerException));
                    }
                }
            }
        }
Beispiel #30
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();
         }
     }
 }