internal RuntimeException(ErrorCategory errorCategory,
                                  InvocationInfo invocationInfo,
                                  IScriptExtent errorPosition,
                                  string errorIdAndResourceId,
                                  string message,
                                  Exception innerException)
            : base(message, innerException)
        {
            SetErrorCategory(errorCategory);
            SetErrorId(errorIdAndResourceId);

            if ((errorPosition == null) && (invocationInfo != null))
            {
                errorPosition = invocationInfo.ScriptPosition;
            }

            if (invocationInfo == null)
            {
                return;
            }
            _errorRecord = new ErrorRecord(
                new ParentContainsErrorRecordException(this),
                _errorId,
                _errorCategory,
                _targetObject);
            _errorRecord.SetInvocationInfo(new InvocationInfo(invocationInfo.MyCommand, errorPosition));
        }
 /// <summary>
 /// Ensures that the provided script block is compatible with the current language mode - to
 /// be used when a script block is being dotted.
 /// </summary>
 /// <param name="scriptBlock">The script block being dotted</param>
 /// <param name="languageMode">The current language mode</param>
 /// <param name="invocationInfo">The invocation info about the command</param>
 protected static void ValidateCompatibleLanguageMode(ScriptBlock scriptBlock,
                                                      PSLanguageMode languageMode,
                                                      InvocationInfo invocationInfo)
 {
     // If we are in a constrained language mode (Core or Restricted), block it.
     // This goes both ways:
     //    - Can't dot something from a more permissive mode, since that would probably expose
     //      functions that were never designed to handle untrusted data.
     //    - Can't dot something from a less permissive mode, since that might introduce tainted
     //      data into the current scope.
     if ((scriptBlock.LanguageMode.HasValue) &&
         (scriptBlock.LanguageMode != languageMode) &&
         ((languageMode == PSLanguageMode.RestrictedLanguage) ||
          (languageMode == PSLanguageMode.ConstrainedLanguage)))
     {
         ErrorRecord errorRecord = new ErrorRecord(
             new NotSupportedException(
                 DiscoveryExceptions.DotSourceNotSupported),
             "DotSourceNotSupported",
             ErrorCategory.InvalidOperation,
             null);
         errorRecord.SetInvocationInfo(invocationInfo);
         throw new CmdletInvocationException(errorRecord);
     }
 }
Beispiel #3
0
        /// <summary>
        /// Writes an ErrorRecord to the commands error pipe because the specified
        /// input object was not bound to the command.
        /// </summary>
        /// <param name="inputObject">
        /// The pipeline input object that was not bound.
        /// </param>
        /// <param name="resourceString">
        /// The error message.
        /// </param>
        /// <param name="errorId">
        /// The resource ID of the error message is also used as error ID
        /// of the ErrorRecord.
        /// </param>
        /// <param name="args">
        /// Additional arguments to be formatted into the error message that represented in <paramref name="resourceString"/>.
        /// </param>
        private void WriteInputObjectError(
            object inputObject,
            string resourceString,
            string errorId,
            params object[] args)
        {
            Type inputObjectType = inputObject?.GetType();

            ParameterBindingException bindingException = new ParameterBindingException(
                ErrorCategory.InvalidArgument,
                this.Command.MyInvocation,
                null,
                null,
                null,
                inputObjectType,
                resourceString,
                errorId,
                args);

            ErrorRecord errorRecord =
                new ErrorRecord(
                    bindingException,
                    errorId,
                    ErrorCategory.InvalidArgument,
                    inputObject);

            errorRecord.SetInvocationInfo(this.Command.MyInvocation);

            this.commandRuntime._WriteErrorSkipAllowCheck(errorRecord);
        }
Beispiel #4
0
        private void WriteInputObjectError(object inputObject, string resourceAndErrorId, params object[] args)
        {
            Type typeSpecified = (inputObject == null) ? null : inputObject.GetType();
            ParameterBindingException exception = new ParameterBindingException(ErrorCategory.InvalidArgument, base.Command.MyInvocation, null, null, null, typeSpecified, "ParameterBinderStrings", resourceAndErrorId, args);
            ErrorRecord errorRecord             = new ErrorRecord(exception, resourceAndErrorId, ErrorCategory.InvalidArgument, inputObject);

            errorRecord.SetInvocationInfo(base.Command.MyInvocation);
            base.commandRuntime._WriteErrorSkipAllowCheck(errorRecord, null);
        }
Beispiel #5
0
        private void WriteInputObjectError(
            object inputObject,
            string resourceAndErrorId,
            params object[] args)
        {
            ErrorRecord errorRecord = new ErrorRecord((Exception) new ParameterBindingException(ErrorCategory.InvalidArgument, this.Command.MyInvocation, this.Command.MyInvocation.ScriptToken, (string)null, (Type)null, inputObject == null ? (Type)null : inputObject.GetType(), "ParameterBinderStrings", resourceAndErrorId, args), resourceAndErrorId, ErrorCategory.InvalidArgument, inputObject);

            errorRecord.SetInvocationInfo(this.Command.MyInvocation);
            this.commandRuntime._WriteErrorSkipAllowCheck(errorRecord);
        }
 private void ProcessOutputHelper()
 {
     for (object obj = this.outputReader.Read(); obj != AutomationNull.Value; obj = this.outputReader.Read())
     {
         ProcessOutputObject processOutputObject = obj as ProcessOutputObject;
         if (processOutputObject.Stream == MinishellStream.Error)
         {
             ErrorRecord data = processOutputObject.Data as ErrorRecord;
             data.SetInvocationInfo(this.Command.MyInvocation);
             this.commandRuntime._WriteErrorSkipAllowCheck(data);
         }
         else if (processOutputObject.Stream == MinishellStream.Output)
         {
             this.commandRuntime._WriteObjectSkipAllowCheck(processOutputObject.Data);
         }
         else if (processOutputObject.Stream == MinishellStream.Debug)
         {
             this.Command.PSHostInternal.UI.WriteDebugLine(processOutputObject.Data as string);
         }
         else if (processOutputObject.Stream == MinishellStream.Verbose)
         {
             this.Command.PSHostInternal.UI.WriteVerboseLine(processOutputObject.Data as string);
         }
         else if (processOutputObject.Stream == MinishellStream.Warning)
         {
             this.Command.PSHostInternal.UI.WriteWarningLine(processOutputObject.Data as string);
         }
         else if (processOutputObject.Stream == MinishellStream.Progress && processOutputObject.Data is PSObject data)
         {
             long         sourceId  = 0;
             PSMemberInfo property1 = (PSMemberInfo)data.Properties["SourceId"];
             if (property1 != null)
             {
                 sourceId = (long)property1.Value;
             }
             PSMemberInfo   property2 = (PSMemberInfo)data.Properties["Record"];
             ProgressRecord record    = (ProgressRecord)null;
             if (property2 != null)
             {
                 record = property2.Value as ProgressRecord;
             }
             if (record != null)
             {
                 this.Command.PSHostInternal.UI.WriteProgress(sourceId, record);
             }
         }
         if (this.Command.Context.CurrentPipelineStopping)
         {
             this.StopProcessing();
             break;
         }
     }
 }
Beispiel #7
0
        internal PipelineStoppedException ManageInvocationException(Exception e)
        {
            PipelineStoppedException exception4;

            try
            {
                if (this.Command != null)
                {
                    ProviderInvocationException innerException = e as ProviderInvocationException;
                    if (innerException != null)
                    {
                        e = new CmdletProviderInvocationException(innerException, this.Command.MyInvocation);
                    }
                    else if (((!(e is PipelineStoppedException) && !(e is CmdletInvocationException)) && (!(e is ActionPreferenceStopException) && !(e is HaltCommandException))) && (!(e is FlowControlException) && !(e is ScriptCallDepthException)))
                    {
                        RuntimeException exception2 = e as RuntimeException;
                        if ((exception2 == null) || !exception2.WasThrownFromThrowStatement)
                        {
                            e = new CmdletInvocationException(e, this.Command.MyInvocation);
                        }
                    }
                    if (this.commandRuntime.UseTransaction != 0)
                    {
                        bool flag = false;
                        for (Exception exception3 = e; exception3 != null; exception3 = exception3.InnerException)
                        {
                            if (exception3 is TimeoutException)
                            {
                                flag = true;
                                break;
                            }
                        }
                        if (flag)
                        {
                            ErrorRecord errorRecord = new ErrorRecord(new InvalidOperationException(TransactionStrings.TransactionTimedOut), "TRANSACTION_TIMEOUT", ErrorCategory.InvalidOperation, e);
                            errorRecord.SetInvocationInfo(this.Command.MyInvocation);
                            e = new CmdletInvocationException(errorRecord);
                        }
                        if (this._context.TransactionManager.HasTransaction && (this._context.TransactionManager.RollbackPreference != RollbackSeverity.Never))
                        {
                            this.Context.TransactionManager.Rollback(true);
                        }
                    }
                    return((PipelineStoppedException)this.commandRuntime.ManageException(e));
                }
                exception4 = new PipelineStoppedException();
            }
            catch (Exception)
            {
                throw;
            }
            return(exception4);
        }
Beispiel #8
0
 protected static void ValidateCompatibleLanguageMode(ScriptBlock scriptBlock, PSLanguageMode languageMode, InvocationInfo invocationInfo)
 {
     if (scriptBlock.LanguageMode.HasValue)
     {
         PSLanguageMode?nullable2 = scriptBlock.LanguageMode;
         PSLanguageMode mode      = languageMode;
         if (((((PSLanguageMode)nullable2.GetValueOrDefault()) != mode) || !nullable2.HasValue) && ((languageMode == PSLanguageMode.RestrictedLanguage) || (languageMode == PSLanguageMode.ConstrainedLanguage)))
         {
             ErrorRecord errorRecord = new ErrorRecord(new NotSupportedException(DiscoveryExceptions.DotSourceNotSupported), "DotSourceNotSupported", ErrorCategory.InvalidOperation, null);
             errorRecord.SetInvocationInfo(invocationInfo);
             throw new CmdletInvocationException(errorRecord);
         }
     }
 }
        private RuntimeException ConvertToException(
            object result,
            ExecutionContext context)
        {
            result = PSObject.Base(result);
            if (LanguagePrimitives.IsNull(result) && context.CurrentExceptionBeingHandled != null && this._inCatch)
            {
                result = (object)context.CurrentExceptionBeingHandled;
            }
            switch (result)
            {
            case RuntimeException runtimeException3:
                runtimeException3.WasThrownFromThrowStatement = true;
                return(runtimeException3);

            case ErrorRecord errorRecord3:
                RuntimeException runtimeException1 = new RuntimeException(errorRecord3.ToString(), errorRecord3.Exception, errorRecord3);
                if (errorRecord3.InvocationInfo == null)
                {
                    errorRecord3.SetInvocationInfo(new InvocationInfo((CommandInfo)null, this.NodeToken, context));
                }
                runtimeException1.WasThrownFromThrowStatement = true;
                return(runtimeException1);

            case Exception exception2:
                ErrorRecord errorRecord1 = new ErrorRecord(exception2, exception2.Message, ErrorCategory.OperationStopped, (object)null);
                errorRecord1.SetInvocationInfo(new InvocationInfo((CommandInfo)null, this.NodeToken, context));
                return(new RuntimeException(exception2.Message, exception2, errorRecord1)
                {
                    WasThrownFromThrowStatement = true
                });

            default:
                string      str          = LanguagePrimitives.IsNull(result) ? "ScriptHalted" : Parser.ConvertTo <string>(result, this.NodeToken);
                Exception   exception1   = (Exception) new RuntimeException(str, (Exception)null);
                ErrorRecord errorRecord2 = new ErrorRecord(exception1, str, ErrorCategory.OperationStopped, (object)null);
                errorRecord2.SetInvocationInfo(new InvocationInfo((CommandInfo)null, this.NodeToken, context));
                RuntimeException runtimeException2 = new RuntimeException(str, exception1, errorRecord2);
                runtimeException2.WasThrownFromThrowStatement = true;
                runtimeException2.SetTargetObject(result);
                return(runtimeException2);
            }
        }
Beispiel #10
0
        /// <summary>
        /// Ensures that the provided script block is compatible with the current language mode - to
        /// be used when a script block is being dotted.
        /// </summary>
        /// <param name="scriptBlock">The script block being dotted.</param>
        /// <param name="languageMode">The current language mode.</param>
        /// <param name="invocationInfo">The invocation info about the command.</param>
        protected static void ValidateCompatibleLanguageMode(
            ScriptBlock scriptBlock,
            PSLanguageMode languageMode,
            InvocationInfo invocationInfo)
        {
            // If we are in a constrained language mode (Core or Restricted), block it.
            // We are currently restricting in one direction:
            //    - Can't dot something from a more permissive mode, since that would probably expose
            //      functions that were never designed to handle untrusted data.
            // This function won't be called for NoLanguage mode so the only direction checked is trusted
            // (FullLanguage mode) script running in a constrained/restricted session.
            if ((scriptBlock.LanguageMode.HasValue) &&
                (scriptBlock.LanguageMode != languageMode) &&
                ((languageMode == PSLanguageMode.RestrictedLanguage) ||
                 (languageMode == PSLanguageMode.ConstrainedLanguage)))
            {
                // Finally check if script block is really just PowerShell commands plus parameters.
                // If so then it is safe to dot source across language mode boundaries.
                bool isSafeToDotSource = false;
                try
                {
                    scriptBlock.GetPowerShell();
                    isSafeToDotSource = true;
                }
                catch (Exception)
                {
                }

                if (!isSafeToDotSource)
                {
                    ErrorRecord errorRecord = new ErrorRecord(
                        new NotSupportedException(
                            DiscoveryExceptions.DotSourceNotSupported),
                        "DotSourceNotSupported",
                        ErrorCategory.InvalidOperation,
                        null);
                    errorRecord.SetInvocationInfo(invocationInfo);
                    throw new CmdletInvocationException(errorRecord);
                }
            }
        }
Beispiel #11
0
 internal static void UpdateExceptionErrorRecordPosition(Exception exception, IScriptExtent extent)
 {
     if ((extent != null) && (extent != PositionUtilities.EmptyExtent))
     {
         IContainsErrorRecord record = exception as IContainsErrorRecord;
         if (record != null)
         {
             ErrorRecord    errorRecord    = record.ErrorRecord;
             InvocationInfo invocationInfo = errorRecord.InvocationInfo;
             if (invocationInfo == null)
             {
                 errorRecord.SetInvocationInfo(new InvocationInfo(null, extent));
             }
             else if ((invocationInfo.ScriptPosition == null) || (invocationInfo.ScriptPosition == PositionUtilities.EmptyExtent))
             {
                 invocationInfo.ScriptPosition = extent;
                 errorRecord.LockScriptStackTrace();
             }
         }
     }
 }
Beispiel #12
0
        /// <summary>
        /// Implementation of ThrowTerminatingError.
        /// </summary>
        /// <param name="errorRecord">
        /// The error which caused the command to be terminated
        /// </param>
        /// <exception cref="PipelineStoppedException">
        /// always
        /// </exception>
        /// <remarks>
        /// <see cref="System.Management.Automation.Cmdlet.ThrowTerminatingError"/>
        /// terminates the command, where
        /// <see cref="System.Management.Automation.ICommandRuntime.WriteError"/>
        /// allows the command to continue.
        /// 
        /// The cmdlet can also terminate the command by simply throwing
        /// any exception.  When the cmdlet's implementation of
        /// <see cref="System.Management.Automation.Cmdlet.ProcessRecord"/>,
        /// <see cref="System.Management.Automation.Cmdlet.BeginProcessing"/> or
        /// <see cref="System.Management.Automation.Cmdlet.EndProcessing"/>
        /// throws an exception, the Engine will always catch the exception
        /// and report it as a terminating error.
        /// However, it is preferred for the cmdlet to call
        /// <see cref="System.Management.Automation.Cmdlet.ThrowTerminatingError"/>,
        /// so that the additional information in
        /// <see cref="System.Management.Automation.ErrorRecord"/>
        /// is available.
        /// 
        /// <see cref="System.Management.Automation.Cmdlet.ThrowTerminatingError"/>
        /// always throws
        /// <see cref="System.Management.Automation.PipelineStoppedException"/>,
        /// regardless of what error was specified in <paramref name="errorRecord"/>.
        /// The Cmdlet should generally just allow
        /// <see cref="System.Management.Automation.PipelineStoppedException"/>.
        /// to percolate up to the caller of
        /// <see cref="System.Management.Automation.Cmdlet.ProcessRecord"/>.
        /// etc.
        /// </remarks>
        public void ThrowTerminatingError(ErrorRecord errorRecord)
        {
            ThrowIfStopping();
            if (null == errorRecord)
            {
                throw PSTraceSource.NewArgumentNullException("errorRecord");
            }
            errorRecord.SetInvocationInfo(MyInvocation);

            if (null != errorRecord.ErrorDetails
                && null != errorRecord.ErrorDetails.TextLookupError)
            {
                Exception textLookupError = errorRecord.ErrorDetails.TextLookupError;
                errorRecord.ErrorDetails.TextLookupError = null;
                MshLog.LogCommandHealthEvent(
                    Context,
                    textLookupError,
                    Severity.Warning);
            }

            // This code forces the stack trace and source fields to be populated
            if (null != errorRecord.Exception
                && String.IsNullOrEmpty(errorRecord.Exception.StackTrace))
            {
                try
                {
                    throw errorRecord.Exception;
                }
                catch (Exception)
                {
                    // no need to worry about severe exceptions since
                    // it wasn't really thrown originally
                }
            }

            CmdletInvocationException e =
                new CmdletInvocationException(errorRecord);
            // Code sees only that execution stopped
            throw ManageException(e);
        }
Beispiel #13
0
        /// <summary>
        /// Wraps the exception which occurred during cmdlet invocation,
        /// stores that as the exception to be returned from
        /// PipelineProcessor.SynchronousExecute, and writes it to
        /// the error variable.
        /// </summary>
        /// <param name="e">
        /// The exception to wrap in a CmdletInvocationException or
        /// CmdletProviderInvocationException.
        /// </param>
        /// <returns>
        /// Always returns PipelineStoppedException.  The caller should
        /// throw this exception.
        /// </returns>
        /// <remarks>
        /// Almost all exceptions which occur during pipeline invocation
        /// are wrapped in CmdletInvocationException before they are stored
        /// in the pipeline.  However, there are several exceptions:
        ///
        /// AccessViolationException, StackOverflowException:
        /// These are considered to be such severe errors that we
        /// FailFast the process immediately.
        ///
        /// ProviderInvocationException: In this case, we assume that the
        /// cmdlet is get-item or the like, a thin wrapper around the
        /// provider API.  We discard the original ProviderInvocationException
        /// and re-wrap its InnerException (the real error) in
        /// CmdletProviderInvocationException. This makes it easier to reach
        /// the real error.
        ///
        /// CmdletInvocationException, ActionPreferenceStopException:
        /// This indicates that the cmdlet itself ran a command which failed.
        /// We could go ahead and wrap the original exception in multiple
        /// layers of CmdletInvocationException, but this makes it difficult
        /// for the caller to access the root problem, plus the serialization
        /// layer might not communicate properties beyond some fixed depth.
        /// Instead, we choose to not re-wrap the exception.
        ///
        /// PipelineStoppedException: This could mean one of two things.
        /// It usually means that this pipeline has already stopped,
        /// in which case the pipeline already stores the original error.
        /// It could also mean that the cmdlet ran a command which was
        /// stopped by CTRL-C etc, in which case we choose not to
        /// re-wrap the exception as with CmdletInvocationException.
        /// </remarks>
        internal PipelineStoppedException ManageInvocationException(Exception e)
        {
            try
            {
                if (Command != null)
                {
                    do // false loop
                    {
                        ProviderInvocationException pie = e as ProviderInvocationException;
                        if (pie != null)
                        {
                            // If a ProviderInvocationException occurred,
                            // discard the ProviderInvocationException and
                            // re-wrap in CmdletProviderInvocationException
                            e = new CmdletProviderInvocationException(
                                pie,
                                Command.MyInvocation);
                            break;
                        }

                        // 1021203-2005/05/09-JonN
                        // HaltCommandException will cause the command
                        // to stop, but not be reported as an error.
                        // 906445-2005/05/16-JonN
                        // FlowControlException should not be wrapped
                        if (e is PipelineStoppedException ||
                            e is CmdletInvocationException ||
                            e is ActionPreferenceStopException ||
                            e is HaltCommandException ||
                            e is FlowControlException ||
                            e is ScriptCallDepthException)
                        {
                            // do nothing; do not rewrap these exceptions
                            break;
                        }

                        RuntimeException rte = e as RuntimeException;
                        if (rte != null && rte.WasThrownFromThrowStatement)
                        {
                            // do not rewrap a script based throw
                            break;
                        }

                        // wrap all other exceptions
                        e = new CmdletInvocationException(
                            e,
                            Command.MyInvocation);
                    } while (false);

                    // commandRuntime.ManageException will always throw PipelineStoppedException
                    // Otherwise, just return this exception...

                    // If this exception happened in a transacted cmdlet,
                    // rollback the transaction
                    if (commandRuntime.UseTransaction)
                    {
                        // The "transaction timed out" exception is
                        // exceedingly obtuse. We clarify things here.
                        bool      isTimeoutException = false;
                        Exception tempException      = e;
                        while (tempException != null)
                        {
                            if (tempException is System.TimeoutException)
                            {
                                isTimeoutException = true;
                                break;
                            }

                            tempException = tempException.InnerException;
                        }

                        if (isTimeoutException)
                        {
                            ErrorRecord errorRecord = new ErrorRecord(
                                new InvalidOperationException(
                                    TransactionStrings.TransactionTimedOut),
                                "TRANSACTION_TIMEOUT",
                                ErrorCategory.InvalidOperation,
                                e);
                            errorRecord.SetInvocationInfo(Command.MyInvocation);

                            e = new CmdletInvocationException(errorRecord);
                        }

                        // Rollback the transaction in the case of errors.
                        if (
                            _context.TransactionManager.HasTransaction
                            &&
                            _context.TransactionManager.RollbackPreference != RollbackSeverity.Never
                            )
                        {
                            Context.TransactionManager.Rollback(true);
                        }
                    }

                    return((PipelineStoppedException)this.commandRuntime.ManageException(e));
                }

                // Upstream cmdlets see only that execution stopped
                // This should only happen if Command is null
                return(new PipelineStoppedException());
            }
            catch (Exception)
            {
                // this method should not throw exceptions; warn about any violations on checked builds and re-throw
                Diagnostics.Assert(false, "This method should not throw exceptions!");
                throw;
            }
        }
Beispiel #14
0
        internal RuntimeException(ErrorCategory errorCategory,
            InvocationInfo invocationInfo,
            IScriptExtent errorPosition,
            string errorIdAndResourceId,
            string message,
            Exception innerException)
            : base(message, innerException)
        {
            SetErrorCategory(errorCategory);
            SetErrorId(errorIdAndResourceId);

            if ((errorPosition == null) && (invocationInfo != null))
            {
                errorPosition = invocationInfo.ScriptPosition;
            }

            if (invocationInfo == null) return;
            _errorRecord = new ErrorRecord(
              new ParentContainsErrorRecordException(this),
                _errorId,
                _errorCategory,
                _targetObject);
            _errorRecord.SetInvocationInfo(new InvocationInfo(invocationInfo.MyCommand, errorPosition));
        }
        /// <summary>
        /// Wraps the exception which occurred during cmdlet invocation,
        /// stores that as the exception to be returned from
        /// PipelineProcessor.SynchronousExecute, and writes it to
        /// the error variable.
        /// </summary>
        /// 
        /// <param name="e">
        /// The exception to wrap in a CmdletInvocationException or
        /// CmdletProviderInvocationException.
        /// </param>
        /// 
        /// <returns>
        /// Always returns PipelineStoppedException.  The caller should
        /// throw this exception.
        /// </returns>
        /// 
        /// <remarks>
        /// Almost all exceptions which occur during pipeline invocation
        /// are wrapped in CmdletInvocationException before they are stored
        /// in the pipeline.  However, there are several exceptions:
        /// 
        /// AccessViolationException, StackOverflowException:
        /// These are considered to be such severe errors that we
        /// FailFast the process immediately.
        /// 
        /// ProviderInvocationException: In this case, we assume that the
        /// cmdlet is get-item or the like, a thin wrapper around the
        /// provider API.  We discard the original ProviderInvocationException
        /// and re-wrap its InnerException (the real error) in
        /// CmdletProviderInvocationException. This makes it easier to reach
        /// the real error.
        /// 
        /// CmdletInvocationException, ActionPreferenceStopException:
        /// This indicates that the cmdlet itself ran a command which failed.
        /// We could go ahead and wrap the original exception in multiple
        /// layers of CmdletInvocationException, but this makes it difficult
        /// for the caller to access the root problem, plus the serialization
        /// layer might not communicate properties beyond some fixed depth.
        /// Instead, we choose to not re-wrap the exception.
        /// 
        /// PipelineStoppedException: This could mean one of two things.
        /// It usually means that this pipeline has already stopped,
        /// in which case the pipeline already stores the original error.
        /// It could also mean that the cmdlet ran a command which was
        /// stopped by CTRL-C etc, in which case we choose not to
        /// re-wrap the exception as with CmdletInvocationException.
        /// </remarks>
        internal PipelineStoppedException ManageInvocationException(Exception e)
        {
            try
            {
                if (null != Command)
                {
                    do // false loop
                    {
                        ProviderInvocationException pie = e as ProviderInvocationException;
                        if (pie != null)
                        {
                            // If a ProviderInvocationException occurred,
                            // discard the ProviderInvocationException and
                            // re-wrap in CmdletProviderInvocationException 
                            e = new CmdletProviderInvocationException(
                                pie,
                                Command.MyInvocation);
                            break;
                        }

                        // 1021203-2005/05/09-JonN
                        // HaltCommandException will cause the command
                        // to stop, but not be reported as an error.
                        // 906445-2005/05/16-JonN
                        // FlowControlException should not be wrapped
                        if (e is PipelineStoppedException
                            || e is CmdletInvocationException
                            || e is ActionPreferenceStopException
                            || e is HaltCommandException
                            || e is FlowControlException
                            || e is ScriptCallDepthException)
                        {
                            // do nothing; do not rewrap these exceptions
                            break;
                        }

                        RuntimeException rte = e as RuntimeException;
                        if (rte != null && rte.WasThrownFromThrowStatement)
                        {
                            // do not rewrap a script based throw
                            break;
                        }

                        // wrap all other exceptions
                        e = new CmdletInvocationException(
                                    e,
                                    Command.MyInvocation);
                    } while (false);

                    // commandRuntime.ManageException will always throw PipelineStoppedException
                    // Otherwise, just return this exception...

                    // If this exception happened in a transacted cmdlet,
                    // rollback the transaction
                    if (commandRuntime.UseTransaction)
                    {
                        // The "transaction timed out" exception is
                        // exceedingly obtuse. We clarify things here.
                        bool isTimeoutException = false;
                        Exception tempException = e;
                        while (tempException != null)
                        {
                            if (tempException is System.TimeoutException)
                            {
                                isTimeoutException = true;
                                break;
                            }

                            tempException = tempException.InnerException;
                        }

                        if (isTimeoutException)
                        {
                            ErrorRecord errorRecord = new ErrorRecord(
                                new InvalidOperationException(
                                    TransactionStrings.TransactionTimedOut),
                                "TRANSACTION_TIMEOUT",
                                ErrorCategory.InvalidOperation,
                                e);
                            errorRecord.SetInvocationInfo(Command.MyInvocation);

                            e = new CmdletInvocationException(errorRecord);
                        }

                        // Rollback the transaction in the case of errors.
                        if (
                            _context.TransactionManager.HasTransaction
                            &&
                            _context.TransactionManager.RollbackPreference != RollbackSeverity.Never
                           )
                        {
                            Context.TransactionManager.Rollback(true);
                        }
                    }

                    return (PipelineStoppedException)this.commandRuntime.ManageException(e);
                }

                // Upstream cmdlets see only that execution stopped
                // This should only happen if Command is null
                return new PipelineStoppedException();
            }
            catch (Exception)
            {
                // this method should not throw exceptions; warn about any violations on checked builds and re-throw
                Diagnostics.Assert(false, "This method should not throw exceptions!");
                throw;
            }
        }
 /// <summary>
 /// Ensures that the provided script block is compatible with the current language mode - to
 /// be used when a script block is being dotted.
 /// </summary>
 /// <param name="scriptBlock">The script block being dotted</param>
 /// <param name="languageMode">The current language mode</param>
 /// <param name="invocationInfo">The invocation info about the command</param>
 protected static void ValidateCompatibleLanguageMode(ScriptBlock scriptBlock,
     PSLanguageMode languageMode,
     InvocationInfo invocationInfo)
 {
     // If we are in a constrained language mode (Core or Restricted), block it.
     // This goes both ways:
     //    - Can't dot something from a more permissive mode, since that would probably expose
     //      functions that were never designed to handle untrusted data.
     //    - Can't dot something from a less permissive mode, since that might introduce tainted
     //      data into the current scope.
     if ((scriptBlock.LanguageMode.HasValue) &&
         (scriptBlock.LanguageMode != languageMode) &&
         ((languageMode == PSLanguageMode.RestrictedLanguage) ||
         (languageMode == PSLanguageMode.ConstrainedLanguage)))
     {
         ErrorRecord errorRecord = new ErrorRecord(
             new NotSupportedException(
                 DiscoveryExceptions.DotSourceNotSupported),
                 "DotSourceNotSupported",
                 ErrorCategory.InvalidOperation,
                 null);
         errorRecord.SetInvocationInfo(invocationInfo);
         throw new CmdletInvocationException(errorRecord);
     }
 }
Beispiel #17
0
 protected static void ValidateCompatibleLanguageMode(ScriptBlock scriptBlock, PSLanguageMode languageMode, InvocationInfo invocationInfo)
 {
     if (scriptBlock.LanguageMode.HasValue)
     {
         PSLanguageMode? nullable2 = scriptBlock.LanguageMode;
         PSLanguageMode mode = languageMode;
         if (((((PSLanguageMode) nullable2.GetValueOrDefault()) != mode) || !nullable2.HasValue) && ((languageMode == PSLanguageMode.RestrictedLanguage) || (languageMode == PSLanguageMode.ConstrainedLanguage)))
         {
             ErrorRecord errorRecord = new ErrorRecord(new NotSupportedException(DiscoveryExceptions.DotSourceNotSupported), "DotSourceNotSupported", ErrorCategory.InvalidOperation, null);
             errorRecord.SetInvocationInfo(invocationInfo);
             throw new CmdletInvocationException(errorRecord);
         }
     }
 }
Beispiel #18
0
 internal PipelineStoppedException ManageInvocationException(Exception e)
 {
     PipelineStoppedException exception4;
     try
     {
         if (this.Command != null)
         {
             ProviderInvocationException innerException = e as ProviderInvocationException;
             if (innerException != null)
             {
                 e = new CmdletProviderInvocationException(innerException, this.Command.MyInvocation);
             }
             else if (((!(e is PipelineStoppedException) && !(e is CmdletInvocationException)) && (!(e is ActionPreferenceStopException) && !(e is HaltCommandException))) && (!(e is FlowControlException) && !(e is ScriptCallDepthException)))
             {
                 RuntimeException exception2 = e as RuntimeException;
                 if ((exception2 == null) || !exception2.WasThrownFromThrowStatement)
                 {
                     e = new CmdletInvocationException(e, this.Command.MyInvocation);
                 }
             }
             if (this.commandRuntime.UseTransaction != 0)
             {
                 bool flag = false;
                 for (Exception exception3 = e; exception3 != null; exception3 = exception3.InnerException)
                 {
                     if (exception3 is TimeoutException)
                     {
                         flag = true;
                         break;
                     }
                 }
                 if (flag)
                 {
                     ErrorRecord errorRecord = new ErrorRecord(new InvalidOperationException(TransactionStrings.TransactionTimedOut), "TRANSACTION_TIMEOUT", ErrorCategory.InvalidOperation, e);
                     errorRecord.SetInvocationInfo(this.Command.MyInvocation);
                     e = new CmdletInvocationException(errorRecord);
                 }
                 if (this._context.TransactionManager.HasTransaction && (this._context.TransactionManager.RollbackPreference != RollbackSeverity.Never))
                 {
                     this.Context.TransactionManager.Rollback(true);
                 }
             }
             return (PipelineStoppedException) this.commandRuntime.ManageException(e);
         }
         exception4 = new PipelineStoppedException();
     }
     catch (Exception)
     {
         throw;
     }
     return exception4;
 }
Beispiel #19
0
 public void ThrowTerminatingError(ErrorRecord errorRecord)
 {
     this.ThrowIfStopping();
     if (errorRecord == null)
     {
         throw PSTraceSource.NewArgumentNullException("errorRecord");
     }
     errorRecord.SetInvocationInfo(this.MyInvocation);
     if ((errorRecord.ErrorDetails != null) && (errorRecord.ErrorDetails.TextLookupError != null))
     {
         Exception textLookupError = errorRecord.ErrorDetails.TextLookupError;
         errorRecord.ErrorDetails.TextLookupError = null;
         MshLog.LogCommandHealthEvent(this.context, textLookupError, Severity.Warning);
     }
     if ((errorRecord.Exception != null) && string.IsNullOrEmpty(errorRecord.Exception.StackTrace))
     {
         try
         {
             throw errorRecord.Exception;
         }
         catch (Exception)
         {
         }
     }
     CmdletInvocationException e = new CmdletInvocationException(errorRecord);
     throw this.ManageException(e);
 }
 private void ProcessOutputHelper()
 {
     for (object obj2 = this.outputReader.Read(); obj2 != AutomationNull.Value; obj2 = this.outputReader.Read())
     {
         ProcessOutputObject obj3 = obj2 as ProcessOutputObject;
         if (obj3.Stream == MinishellStream.Error)
         {
             ErrorRecord data = obj3.Data as ErrorRecord;
             data.SetInvocationInfo(base.Command.MyInvocation);
             ActionPreference?actionPreference = null;
             base.commandRuntime._WriteErrorSkipAllowCheck(data, actionPreference);
         }
         else if (obj3.Stream == MinishellStream.Output)
         {
             base.commandRuntime._WriteObjectSkipAllowCheck(obj3.Data);
         }
         else if (obj3.Stream == MinishellStream.Debug)
         {
             string message = obj3.Data as string;
             base.Command.PSHostInternal.UI.WriteDebugLine(message);
         }
         else if (obj3.Stream == MinishellStream.Verbose)
         {
             string str2 = obj3.Data as string;
             base.Command.PSHostInternal.UI.WriteVerboseLine(str2);
         }
         else if (obj3.Stream == MinishellStream.Warning)
         {
             string str3 = obj3.Data as string;
             base.Command.PSHostInternal.UI.WriteWarningLine(str3);
         }
         else if (obj3.Stream == MinishellStream.Progress)
         {
             PSObject obj4 = obj3.Data as PSObject;
             if (obj4 != null)
             {
                 long         sourceId = 0L;
                 PSMemberInfo info     = obj4.Properties["SourceId"];
                 if (info != null)
                 {
                     sourceId = (long)info.Value;
                 }
                 info = obj4.Properties["Record"];
                 ProgressRecord record = null;
                 if (info != null)
                 {
                     record = info.Value as ProgressRecord;
                 }
                 if (record != null)
                 {
                     base.Command.PSHostInternal.UI.WriteProgress(sourceId, record);
                 }
             }
         }
         if (base.Command.Context.CurrentPipelineStopping)
         {
             this.StopProcessing();
             return;
         }
     }
 }
Beispiel #21
0
 private void WriteInputObjectError(object inputObject, string resourceAndErrorId, params object[] args)
 {
     Type typeSpecified = (inputObject == null) ? null : inputObject.GetType();
     ParameterBindingException exception = new ParameterBindingException(ErrorCategory.InvalidArgument, base.Command.MyInvocation, null, null, null, typeSpecified, "ParameterBinderStrings", resourceAndErrorId, args);
     ErrorRecord errorRecord = new ErrorRecord(exception, resourceAndErrorId, ErrorCategory.InvalidArgument, inputObject);
     errorRecord.SetInvocationInfo(base.Command.MyInvocation);
     base.commandRuntime._WriteErrorSkipAllowCheck(errorRecord, null);
 }
Beispiel #22
0
        /// <summary>
        /// Writes an ErrorRecord to the commands error pipe because the specified
        /// input object was not bound to the command.
        /// </summary>
        /// 
        /// <param name="inputObject">
        /// The pipeline input object that was not bound.
        /// </param>
        /// 
        /// <param name="resourceString">
        /// The error message.
        /// </param>
        /// 
        /// <param name="errorId">
        /// The resource ID of the error message is also used as error ID
        /// of the ErrorRecord.
        /// </param>
        /// 
        /// <param name="args">
        /// Additional arguments to be formatted into the error message that represented in <paramref name="resourceString"/>.
        /// </param>
        /// 
        private void WriteInputObjectError(
            object inputObject,
            string resourceString,
            string errorId,
            params object[] args)
        {
            Type inputObjectType = (inputObject == null) ? null : inputObject.GetType();

            ParameterBindingException bindingException = new ParameterBindingException(
                ErrorCategory.InvalidArgument,
                this.Command.MyInvocation,
                null,
                null,
                null,
                inputObjectType,
                resourceString,
                errorId,
                args);

            ErrorRecord errorRecord =
                new ErrorRecord(
                    bindingException,
                    errorId,
                    ErrorCategory.InvalidArgument,
                    inputObject);

            errorRecord.SetInvocationInfo(this.Command.MyInvocation);

            this.commandRuntime._WriteErrorSkipAllowCheck(errorRecord);
        } // WriteIgnoredInputObjectError
Beispiel #23
0
        /// <summary>
        /// Ensures that the provided script block is compatible with the current language mode - to
        /// be used when a script block is being dotted.
        /// </summary>
        /// <param name="scriptBlock">The script block being dotted</param>
        /// <param name="languageMode">The current language mode</param>
        /// <param name="invocationInfo">The invocation info about the command</param>
        protected static void ValidateCompatibleLanguageMode(ScriptBlock scriptBlock,
            PSLanguageMode languageMode,
            InvocationInfo invocationInfo)
        {
            // If we are in a constrained language mode (Core or Restricted), block it.
            // We are currently restricting in one direction:
            //    - Can't dot something from a more permissive mode, since that would probably expose
            //      functions that were never designed to handle untrusted data.
            // This function won't be called for NoLanguage mode so the only direction checked is trusted 
            // (FullLanguage mode) script running in a constrained/restricted session.
            if ((scriptBlock.LanguageMode.HasValue) &&
                (scriptBlock.LanguageMode != languageMode) &&
                ((languageMode == PSLanguageMode.RestrictedLanguage) ||
                (languageMode == PSLanguageMode.ConstrainedLanguage)))
            {
                // Finally check if script block is really just PowerShell commands plus parameters.
                // If so then it is safe to dot source across language mode boundaries.
                bool isSafeToDotSource = false;
                try
                {
                    scriptBlock.GetPowerShell();
                    isSafeToDotSource = true;
                }
                catch (Exception e)
                {
                    CheckForSevereException(e);
                }

                if (!isSafeToDotSource)
                {
                    ErrorRecord errorRecord = new ErrorRecord(
                    new NotSupportedException(
                        DiscoveryExceptions.DotSourceNotSupported),
                        "DotSourceNotSupported",
                        ErrorCategory.InvalidOperation,
                        null);
                    errorRecord.SetInvocationInfo(invocationInfo);
                    throw new CmdletInvocationException(errorRecord);
                }
            }
        }