Exemple #1
0
        internal static string Multiply(string s, int times)
        {
            if (times < 0)
            {
                throw new ArgumentOutOfRangeException("times");
            }
            if ((times == 0) || (s.Length == 0))
            {
                return(string.Empty);
            }
            ExecutionContext executionContextFromTLS = LocalPipeline.GetExecutionContextFromTLS();

            if (((executionContextFromTLS != null) && (executionContextFromTLS.LanguageMode == PSLanguageMode.RestrictedLanguage)) && ((s.Length * times) > 0x400))
            {
                throw InterpreterError.NewInterpreterException(times, typeof(RuntimeException), null, "StringMultiplyToolongInDataSection", ParserStrings.StringMultiplyToolongInDataSection, new object[] { 0x400 });
            }
            if (s.Length == 1)
            {
                return(new string(s[0], times));
            }
            return(new string(ArrayOps.Multiply <char>(s.ToCharArray(), (int)times)));
        }
Exemple #2
0
        private object GetItemPropertyValue(object obj, object index, ExecutionContext context)
        {
            IEnumerator enumerator = LanguagePrimitives.GetEnumerator(index);

            if (enumerator != null)
            {
                ArrayList arrayList = new ArrayList();
                while (ParserOps.MoveNext(context, this.NodeToken, enumerator))
                {
                    try
                    {
                        object obj1 = this.GetItem(obj, enumerator.Current);
                        arrayList.Add(obj1);
                    }
                    catch (Exception ex)
                    {
                        CommandProcessorBase.CheckForSevereException(ex);
                        if (this.IsMethodNotFoundException(ex))
                        {
                            throw InterpreterError.NewInterpreterExceptionWithInnerException(index, typeof(RuntimeException), this.NodeToken, "CannotIndex", ex, (object)obj.GetType().FullName);
                        }
                    }
                }
                return((object)arrayList.ToArray());
            }
            try
            {
                return(this.GetItem(obj, index));
            }
            catch (Exception ex)
            {
                CommandProcessorBase.CheckForSevereException(ex);
                if (this.IsMethodNotFoundException(ex))
                {
                    throw InterpreterError.NewInterpreterExceptionWithInnerException(index, typeof(RuntimeException), this.NodeToken, "CannotIndex", ex, (object)obj.GetType().FullName);
                }
                return((object)null);
            }
        }
Exemple #3
0
        internal static object PropertyGetter(PSGetMemberBinder binder, IEnumerator enumerator)
        {
            CallSite <Func <CallSite, object, object> > getMemberBinderSite = CallSite <Func <CallSite, object, object> > .Create(binder);

            ArrayList        result = new ArrayList();
            ExecutionContext executionContextFromTLS = LocalPipeline.GetExecutionContextFromTLS();

            PropertyGetterWorker(getMemberBinderSite, enumerator, executionContextFromTLS, result);
            if (result.Count == 1)
            {
                return(result[0]);
            }
            if (result.Count != 0)
            {
                return(result.ToArray());
            }
            if (executionContextFromTLS.IsStrictVersion(2))
            {
                throw InterpreterError.NewInterpreterException(null, typeof(RuntimeException), null, "PropertyNotFoundStrict", ParserStrings.PropertyNotFoundStrict, new object[] { binder.Name });
            }
            return(null);
        }
Exemple #4
0
        internal static object MethodInvoker(PSInvokeMemberBinder binder, Type delegateType, IEnumerator enumerator, object[] args, Type typeForMessage)
        {
            CallSite         invokeMemberSite        = CallSite.Create(delegateType, binder);
            ArrayList        result                  = new ArrayList();
            ExecutionContext executionContextFromTLS = LocalPipeline.GetExecutionContextFromTLS();
            bool             foundMethod             = false;

            MethodInvokerWorker(invokeMemberSite, enumerator, args, executionContextFromTLS, result, ref foundMethod);
            if (result.Count == 1)
            {
                return(result[0]);
            }
            if (!foundMethod)
            {
                throw InterpreterError.NewInterpreterException(null, typeof(RuntimeException), null, "MethodNotFound", ParserStrings.MethodNotFound, new object[] { typeForMessage.FullName, binder.Name });
            }
            if (result.Count == 0)
            {
                return(AutomationNull.Value);
            }
            return(result.ToArray());
        }
Exemple #5
0
        internal Pipe GetRedirectionPipe(ExecutionContext context, System.Management.Automation.Internal.PipelineProcessor parentPipelineProcessor)
        {
            if (string.IsNullOrWhiteSpace(this.File))
            {
                return(new Pipe {
                    NullPipe = true
                });
            }
            CommandProcessorBase     commandProcessor = context.CreateCommand("out-file", false);
            CommandParameterInternal parameter        = CommandParameterInternal.CreateParameterWithArgument(PositionUtilities.EmptyExtent, "Encoding", "-Encoding:", PositionUtilities.EmptyExtent, "Unicode", false);

            commandProcessor.AddParameter(parameter);
            if (this.Appending)
            {
                parameter = CommandParameterInternal.CreateParameterWithArgument(PositionUtilities.EmptyExtent, "Append", "-Append:", PositionUtilities.EmptyExtent, true, false);
                commandProcessor.AddParameter(parameter);
            }
            parameter = CommandParameterInternal.CreateParameterWithArgument(PositionUtilities.EmptyExtent, "Filepath", "-Filepath:", PositionUtilities.EmptyExtent, this.File, false);
            commandProcessor.AddParameter(parameter);
            this.PipelineProcessor = new System.Management.Automation.Internal.PipelineProcessor();
            this.PipelineProcessor.Add(commandProcessor);
            try
            {
                this.PipelineProcessor.StartStepping(true);
            }
            catch (RuntimeException exception)
            {
                if (exception.ErrorRecord.Exception is ArgumentException)
                {
                    throw InterpreterError.NewInterpreterExceptionWithInnerException(null, typeof(RuntimeException), null, "RedirectionFailed", ParserStrings.RedirectionFailed, exception.ErrorRecord.Exception, new object[] { this.File, exception.ErrorRecord.Exception.Message });
                }
                throw;
            }
            if (parentPipelineProcessor != null)
            {
                parentPipelineProcessor.AddRedirectionPipe(this.PipelineProcessor);
            }
            return(new Pipe(context, this.PipelineProcessor));
        }
Exemple #6
0
        internal ScriptCommandProcessor(
            string script,
            ExecutionContext context,
            bool isFilter,
            bool useLocalScope,
            bool interactiveCommand,
            CommandOrigin origin)
        {
            this.Context                    = context;
            this._interactiveCommand        = interactiveCommand;
            this._dontUseScopeCommandOrigin = false;
            this._rethrowExitException      = this.Context.ScriptCommandProcessorShouldRethrowExit;
            this.Context.ScriptCommandProcessorShouldRethrowExit = false;
            if (origin == CommandOrigin.Runspace && this.Context.LanguageMode == PSLanguageMode.NoLanguage)
            {
                throw InterpreterError.NewInterpreterException((object)script, typeof(ParseException), (Token)null, "ScriptsNotAllowed");
            }
            this._scriptBlock = this.Context.Engine.ParseScriptBlock(script, interactiveCommand);
            if (origin == CommandOrigin.Runspace)
            {
                switch (this.Context.LanguageMode)
                {
                case PSLanguageMode.FullLanguage:
                    break;

                case PSLanguageMode.RestrictedLanguage:
                    RestrictedLanguageModeChecker.Check(this.Context.Engine.EngineParser, this._scriptBlock, (IEnumerable <string>)null, false);
                    break;

                default:
                    throw new InvalidOperationException("Invalid langage mode was set when building a ScriptCommandProcessor");
                }
            }
            this.CommandInfo   = (CommandInfo) new ScriptInfo(string.Empty, this._scriptBlock, context);
            this._fromPipeline = true;
            this.SetupCommand();
            this.Command.CommandOriginInternal = origin;
            this.UseLocalScope = useLocalScope;
        }
        internal override object Execute(Array input, Pipe outputPipe, ExecutionContext context)
        {
            this.CheckForInterrupts(context);
            object obj1 = (object)null;

            try
            {
                obj1 = this._rightHandSide.Execute(input, (Pipe)null, context);
                if (obj1 == AutomationNull.Value)
                {
                    obj1 = (object)null;
                }
                IAssignableValue assignableValue = this._left.GetAssignableValue(input, context);
                object           obj2            = this._operationDelegate == null ? obj1 : this._operationDelegate(context, this.NodeToken, assignableValue.GetValue(context), obj1);
                assignableValue.SetValue(obj2, context);
                return(obj2);
            }
            catch (ScriptCallDepthException ex)
            {
                throw;
            }
            catch (FlowControlException ex)
            {
                throw;
            }
            catch (RuntimeException ex)
            {
                if (ex.ErrorRecord != null && ex.ErrorRecord.InvocationInfo == null)
                {
                    ex.ErrorRecord.SetInvocationInfo(new InvocationInfo((CommandInfo)null, this.NodeToken, context));
                }
                throw;
            }
            catch (Exception ex)
            {
                CommandProcessorBase.CheckForSevereException(ex);
                throw InterpreterError.NewInterpreterException(obj1, typeof(RuntimeException), this.NodeToken, "OperatorFailed", (object)this.NodeToken.TokenText, (object)ex.Message);
            }
        }
Exemple #8
0
        internal static object GetAutomaticVariableValue(int tupleIndex, ExecutionContext executionContext, VariableExpressionAst varAst)
        {
            Diagnostics.Assert(tupleIndex < SpecialVariables.AutomaticVariableTypes.Length, "caller to verify a valid tuple index is used");

            if (executionContext._debuggingMode > 0)
            {
                executionContext.Debugger.CheckVariableRead(SpecialVariables.AutomaticVariables[tupleIndex]);
            }

            object result = executionContext.EngineSessionState.GetAutomaticVariableValue((AutomaticVariable)tupleIndex);

            if (result == AutomationNull.Value)
            {
                if (ThrowStrictModeUndefinedVariable(executionContext, varAst))
                {
                    throw InterpreterError.NewInterpreterException(SpecialVariables.AutomaticVariables[tupleIndex], typeof(RuntimeException),
                                                                   varAst.Extent, "VariableIsUndefined", ParserStrings.VariableIsUndefined, SpecialVariables.AutomaticVariables[tupleIndex]);
                }

                result = null;
            }
            return(result);
        }
Exemple #9
0
        internal static string Multiply(string s, int times)
        {
            Diagnostics.Assert(s != null, "caller to verify argument is not null");

            if (times < 0)
            {
                // TODO: this should be a runtime error.
                throw new ArgumentOutOfRangeException("times");
            }

            if (times == 0 || s.Length == 0)
            {
                return(String.Empty);
            }

            var context = LocalPipeline.GetExecutionContextFromTLS();

            if (context != null &&
                context.LanguageMode == PSLanguageMode.RestrictedLanguage && (s.Length * times) > 1024)
            {
                throw InterpreterError.NewInterpreterException(times, typeof(RuntimeException),
                                                               null, "StringMultiplyToolongInDataSection", ParserStrings.StringMultiplyToolongInDataSection, 1024);
            }

            if (s.Length == 1)
            {
                // A string of length 1 has special support in the BCL, so just use it.
                return(new string(s[0], times));
            }

            // Convert the string to a char array, use the array multiplication code,
            // then construct a new string from the resulting char array.  This uses
            // extra memory compared to the naive algorithm, but is faster (measured
            // against a V2 CLR, should be measured against V4 as the StringBuilder
            // implementation changed.)
            return(new string(ArrayOps.Multiply(s.ToCharArray(), (uint)times)));
        }
Exemple #10
0
        internal static object IsOperator(System.Management.Automation.ExecutionContext context, IScriptExtent errorPosition, object left, object right)
        {
            object o    = PSObject.Base(left);
            object obj3 = PSObject.Base(right);
            Type   type = obj3 as Type;

            if (type == null)
            {
                type = ConvertTo <Type>(obj3, errorPosition);
                if (type == null)
                {
                    throw InterpreterError.NewInterpreterException(obj3, typeof(RuntimeException), errorPosition, "IsOperatorRequiresType", ParserStrings.IsOperatorRequiresType, new object[0]);
                }
            }
            if ((type == typeof(PSCustomObject)) && (o is PSObject))
            {
                return(_TrueObject);
            }
            if (type.Equals(typeof(PSObject)) && (left is PSObject))
            {
                return(_TrueObject);
            }
            return(BoolToObject(type.IsInstanceOfType(o)));
        }
Exemple #11
0
        internal static object GetUsingValue(MutableTuple tuple, string usingExpressionKey, int index, ExecutionContext context)
        {
            UsingResult result = GetUsingValueFromTuple(tuple, usingExpressionKey, index);

            if (result != null)
            {
                return(result.Value);
            }

            var scope = context.EngineSessionState.CurrentScope;

            while (scope != null)
            {
                result = GetUsingValueFromTuple(scope.LocalsTuple, usingExpressionKey, index);
                if (result != null)
                {
                    return(result.Value);
                }

                foreach (var dottedScope in scope.DottedScopes)
                {
                    result = GetUsingValueFromTuple(dottedScope, usingExpressionKey, index);
                    if (result != null)
                    {
                        return(result.Value);
                    }
                }

                scope = scope.Parent;
            }

            // $PSBoundParameters is null or not the expected type (because someone may have assigned to it), so
            // we can't even guess if they were mis-using $using:foo
            throw InterpreterError.NewInterpreterException(null, typeof(RuntimeException),
                                                           null, "UsingWithoutInvokeCommand", ParserStrings.UsingWithoutInvokeCommand);
        }
Exemple #12
0
        internal static PSReference GetVariableAsRef(VariablePath variablePath, ExecutionContext executionContext, Type staticType)
        {
            Diagnostics.Assert(variablePath.IsVariable, "calller to verify varpath is a variable.");

            SessionStateInternal sessionState = executionContext.EngineSessionState;
            CommandOrigin        origin       = sessionState.CurrentScope.ScopeOrigin;

            SessionStateScope scope;
            PSVariable        var = sessionState.GetVariableItem(variablePath, out scope, origin);

            if (var == null)
            {
                throw InterpreterError.NewInterpreterException(variablePath, typeof(RuntimeException), null,
                                                               "NonExistingVariableReference",
                                                               ParserStrings.NonExistingVariableReference);
            }

            object value = var.Value;

            if (staticType == null && value != null)
            {
                value = PSObject.Base(value);
                if (value != null)
                {
                    staticType = value.GetType();
                }
            }

            if (staticType == null)
            {
                var declaredType = var.Attributes.OfType <ArgumentTypeConverterAttribute>().FirstOrDefault();
                staticType = declaredType != null ? declaredType.TargetType : typeof(LanguagePrimitives.Null);
            }

            return(PSReference.CreateInstance(var, staticType));
        }
Exemple #13
0
        internal static RuntimeException NewInterpreterExceptionWithInnerException(
            object targetObject,
            Type exceptionType,
            Token errToken,
            string resourceIdAndErrorId,
            Exception innerException,
            params object[] args)
        {
            if (string.IsNullOrEmpty(resourceIdAndErrorId))
            {
                throw InterpreterError.tracer.NewArgumentException(nameof(resourceIdAndErrorId));
            }
            RuntimeException runtimeException;

            try
            {
                string message = args == null || args.Length == 0 ? ResourceManagerCache.GetResourceString("Parser", resourceIdAndErrorId) : ResourceManagerCache.FormatResourceString("Parser", resourceIdAndErrorId, args);
                runtimeException = !string.IsNullOrEmpty(message) ? InterpreterError.NewInterpreterExceptionByMessage(exceptionType, errToken, message, resourceIdAndErrorId, innerException) : InterpreterError.NewBackupInterpreterException(exceptionType, errToken, resourceIdAndErrorId, (Exception)null);
            }
            catch (InvalidOperationException ex)
            {
                runtimeException = InterpreterError.NewBackupInterpreterException(exceptionType, errToken, resourceIdAndErrorId, (Exception)ex);
            }
            catch (MissingManifestResourceException ex)
            {
                runtimeException = InterpreterError.NewBackupInterpreterException(exceptionType, errToken, resourceIdAndErrorId, (Exception)ex);
            }
            catch (FormatException ex)
            {
                runtimeException = InterpreterError.NewBackupInterpreterException(exceptionType, errToken, resourceIdAndErrorId, (Exception)ex);
            }
            runtimeException.SetTargetObject(targetObject);
            return(runtimeException);
        }
        private void ExecuteFileSwitch(
            Array input,
            Pipe outputPipe,
            ref ArrayList resultList,
            ExecutionContext context)
        {
            string filePath = this.GetFilePath(context);

            try
            {
                using (StreamReader streamReader = new StreamReader(filePath))
                {
                    string str;
                    while ((str = streamReader.ReadLine()) != null)
                    {
                        try
                        {
                            this.ProcessClauses((object)str, outputPipe, ref resultList, context);
                        }
                        catch (BreakException ex)
                        {
                            if (this.MatchLabel(ex.Label))
                            {
                                break;
                            }
                            throw;
                        }
                        catch (ContinueException ex)
                        {
                            if (!this.MatchLabel(ex.Label))
                            {
                                throw;
                            }
                        }
                    }
                }
            }
            catch (BreakException ex)
            {
                throw;
            }
            catch (ContinueException ex)
            {
                throw;
            }
            catch (ReturnException ex)
            {
                throw;
            }
            catch (ExitException ex)
            {
                throw;
            }
            catch (TerminateException ex)
            {
                throw;
            }
            catch (Exception ex)
            {
                CommandProcessorBase.CheckForSevereException(ex);
                throw InterpreterError.NewInterpreterExceptionWithInnerException((object)filePath, typeof(RuntimeException), this._expression.NodeToken, "FileReadError", ex, (object)ex.Message);
            }
        }
        /// <summary>
        /// Perform disambiguation on enum names
        /// </summary>
        /// <returns>complete enum name after disambiguation</returns>
        internal static string EnumDisambiguate(string text, Type enumType)
        {
            // Get all enum names in the given enum type
            string[] enumNames = Enum.GetNames(enumType);

            // Get all names that matches the given prefix.
            List <string> namesWithMatchingPrefix = new List <string>();

            foreach (string name in enumNames)
            {
                if (name.StartsWith(text, StringComparison.OrdinalIgnoreCase))
                {
                    namesWithMatchingPrefix.Add(name);
                }
            }

            // Throw error when no match is found.
            if (namesWithMatchingPrefix.Count == 0)
            {
                throw InterpreterError.NewInterpreterException(null, typeof(RuntimeException),
                                                               null, "NoEnumNameMatch", EnumExpressionEvaluatorStrings.NoEnumNameMatch, text, EnumAllValues(enumType));
            }
            // Return the result if there is only one match.
            else if (namesWithMatchingPrefix.Count == 1)
            {
                return(namesWithMatchingPrefix[0]);
            }
            // multiple matches situation
            else
            {
                // test for exact match
                foreach (string matchName in namesWithMatchingPrefix)
                {
                    if (matchName.Equals(text, StringComparison.OrdinalIgnoreCase))
                    {
                        return(matchName);
                    }
                }
                // test for special cases match
                string[] minDisambiguateNames;
                if (s_specialDisambiguateCases.TryGetValue(enumType, out minDisambiguateNames))
                {
                    foreach (string tName in minDisambiguateNames)
                    {
                        if (tName.StartsWith(text, StringComparison.OrdinalIgnoreCase))
                        {
                            return(tName);
                        }
                    }
                }
                // No special cases match, throw error for multiple matches.
                StringBuilder matchListSB = new StringBuilder(namesWithMatchingPrefix[0]);
                string        separator   = ", ";
                for (int i = 1; i < namesWithMatchingPrefix.Count; i++)
                {
                    matchListSB.Append(separator);
                    matchListSB.Append(namesWithMatchingPrefix[i]);
                }

                throw InterpreterError.NewInterpreterException(null, typeof(RuntimeException),
                                                               null, "MultipleEnumNameMatch", EnumExpressionEvaluatorStrings.MultipleEnumNameMatch,
                                                               text, matchListSB.ToString());
            }
        }
Exemple #16
0
        private CommandProcessorBase CreateCommandProcessor(
            out int index,
            ExecutionContext context)
        {
            index = 0;
            CommandProcessorBase commandProcessorBase = (CommandProcessorBase)null;

            if (this._expression != null)
            {
                return((CommandProcessorBase) new ScriptCommandProcessor(ScriptBlock.CreateSynthesized(this._expression, this.NodeToken), context, false));
            }
            bool createScope;
            SessionStateInternal commandSessionState;
            bool   forceSessionState;
            object commandName = this.GetCommandName(out createScope, out index, out commandSessionState, out forceSessionState, context);

            switch (commandName)
            {
            case ScriptBlock scriptblock:
                commandProcessorBase = CommandDiscovery.CreateCommandProcessorForScript(scriptblock, context, createScope);
                if (commandProcessorBase.CommandSessionState == null || forceSessionState)
                {
                    commandProcessorBase.CommandSessionState = commandSessionState;
                    break;
                }
                break;

            case CommandInfo commandInfo:
                commandProcessorBase = context.CommandDiscovery.LookupCommandProcessor(commandInfo, context.EngineSessionState.currentScope.ScopeOrigin, new bool?(false));
                break;

            case string stringParser:
label_7:
                if (string.IsNullOrEmpty(stringParser))
                {
                    throw InterpreterError.NewInterpreterException(commandName, typeof(RuntimeException), (Token)this._elements[0], "BadExpression", (object)((Token)this._elements[0]).TokenText);
                }
                try
                {
                    if (commandSessionState != context.EngineSessionState)
                    {
                        SessionStateInternal engineSessionState = context.EngineSessionState;
                        try
                        {
                            context.EngineSessionState = commandSessionState;
                            commandProcessorBase       = context.CreateCommand(stringParser);
                            break;
                        }
                        finally
                        {
                            context.EngineSessionState = engineSessionState;
                        }
                    }
                    else
                    {
                        commandProcessorBase = context.CreateCommand(stringParser);
                        break;
                    }
                }
                catch (ParseException ex)
                {
                    throw;
                }
                catch (RuntimeException ex)
                {
                    if (ex.ErrorRecord.InvocationInfo == null)
                    {
                        ex.ErrorRecord.SetInvocationInfo(new InvocationInfo((CommandInfo)null, (Token)this._elements[0], context));
                    }
                    throw;
                }

            default:
                stringParser = PSObject.ToStringParser(context, commandName);
                goto label_7;
            }
            if (commandProcessorBase.CommandSessionState == null || forceSessionState)
            {
                commandProcessorBase.CommandSessionState = commandSessionState;
            }
            InternalCommand command = commandProcessorBase.Command;

            command.MyInvocation.ScriptToken = (Token)this._elements[0];
            if (context.IsStrictVersion(2) && this._elements.Count == index + 1 && (this._elements[index - 1] is Token && this._elements[index] is ArrayLiteralNode))
            {
                Token element = (Token)this._elements[index - 1];
                if (element.Script[element.End] == '(')
                {
                    throw InterpreterError.NewInterpreterException((object)null, typeof(RuntimeException), (Token)this._elements[index - 1], "StrictModeFunctionCallWithParens");
                }
            }
            if (createScope)
            {
                switch (command)
                {
                case ScriptCommand _:
                case PSScriptCmdlet _:
                    commandProcessorBase.UseLocalScope = true;
                    commandProcessorBase.CommandScope  = commandProcessorBase.CommandSessionState == null?context.EngineSessionState.NewScope(commandProcessorBase.FromScriptFile) : commandProcessorBase.CommandSessionState.NewScope(commandProcessorBase.FromScriptFile);

                    goto label_27;
                }
            }
            commandProcessorBase.UseLocalScope = false;
            commandProcessorBase.CommandScope  = commandProcessorBase.CommandSessionState.CurrentScope;
label_27:
            commandProcessorBase.Command.CallingToken = (Token)this._elements[0];
            return(commandProcessorBase);
        }
Exemple #17
0
        private object GetCommandName(
            out bool createScope,
            out int index,
            out SessionStateInternal commandSessionState,
            out bool forceSessionState,
            ExecutionContext context)
        {
            createScope         = true;
            index               = 0;
            forceSessionState   = false;
            commandSessionState = context.EngineSessionState;
            if (this._elements.Count == 0)
            {
                return((object)null);
            }
            Token element = (Token)this._elements[index++];

            if (element.Is(TokenId.DotToken))
            {
                createScope = false;
            }
            else if (!element.Is(TokenId.AmpersandToken))
            {
                return((object)element.TokenText);
            }
            for (int index1 = 0; index1 < 2; ++index1)
            {
                ParseTreeNode parseTreeNode = (ParseTreeNode)null;
                if (index < this._elements.Count)
                {
                    parseTreeNode = this._elements[index++] as ParseTreeNode;
                }
                object obj = parseTreeNode != null?PSObject.Base(parseTreeNode.Execute(context)) : throw InterpreterError.NewInterpreterException((object)null, typeof(RuntimeException), element, "MissingExpression", (object)element.TokenText);

                if (!(obj is PSModuleInfo psModuleInfo))
                {
                    return(obj);
                }
                if (psModuleInfo.ModuleType == ModuleType.Binary && psModuleInfo.SessionState == null)
                {
                    throw InterpreterError.NewInterpreterException((object)null, typeof(RuntimeException), element, "CantInvokeInBinaryModule", (object)psModuleInfo.Name);
                }
                commandSessionState = psModuleInfo.SessionState.Internal;
                forceSessionState   = true;
            }
            return((object)null);
        }
Exemple #18
0
        internal static object MatchOperator(System.Management.Automation.ExecutionContext context, IScriptExtent errorPosition, object lval, object rval, bool notMatch, bool ignoreCase)
        {
            object       obj3;
            RegexOptions options = ignoreCase ? RegexOptions.IgnoreCase : RegexOptions.None;
            Regex        regex   = PSObject.Base(rval) as Regex;

            if (regex == null)
            {
                regex = NewRegex(PSObject.ToStringParser(context, rval), options);
            }
            IEnumerator targetObject = LanguagePrimitives.GetEnumerator(lval);

            if (targetObject == null)
            {
                string input = (lval == null) ? string.Empty : PSObject.ToStringParser(context, lval);
                Match  match = regex.Match(input);
                if (match.Success)
                {
                    GroupCollection groups = match.Groups;
                    if (groups.Count > 0)
                    {
                        Hashtable newValue = new Hashtable(StringComparer.CurrentCultureIgnoreCase);
                        foreach (string str2 in regex.GetGroupNames())
                        {
                            Group group = groups[str2];
                            if (group.Success)
                            {
                                int num;
                                if (int.TryParse(str2, out num))
                                {
                                    newValue.Add(num, group.ToString());
                                }
                                else
                                {
                                    newValue.Add(str2, group.ToString());
                                }
                            }
                        }
                        context.SetVariable(SpecialVariables.MatchesVarPath, newValue);
                    }
                }
                return(BoolToObject(match.Success ^ notMatch));
            }
            ArrayList list = new ArrayList();
            int       num2 = 0;

            try
            {
                while (targetObject.MoveNext())
                {
                    object current = targetObject.Current;
                    string str3    = (current == null) ? string.Empty : PSObject.ToStringParser(context, current);
                    if (regex.Match(str3).Success ^ notMatch)
                    {
                        list.Add(current);
                    }
                    if (num2++ > 0x3e8)
                    {
                        if ((context != null) && context.CurrentPipelineStopping)
                        {
                            throw new PipelineStoppedException();
                        }
                        num2 = 0;
                    }
                }
                obj3 = list.ToArray();
            }
            catch (RuntimeException)
            {
                throw;
            }
            catch (FlowControlException)
            {
                throw;
            }
            catch (ScriptCallDepthException)
            {
                throw;
            }
            catch (Exception exception)
            {
                CommandProcessorBase.CheckForSevereException(exception);
                throw InterpreterError.NewInterpreterExceptionWithInnerException(targetObject, typeof(RuntimeException), errorPosition, "BadEnumeration", ParserStrings.BadEnumeration, exception, new object[] { exception.Message });
            }
            return(obj3);
        }
Exemple #19
0
        internal static object CallMethod(IScriptExtent errorPosition, object target, string methodName, PSMethodInvocationConstraints invocationConstraints, object[] paramArray, bool callStatic, object valueToSet)
        {
            PSMethodInfo      staticCLRMember   = null;
            MethodInformation methodInformation = null;
            object            obj2 = null;
            PSObject          obj3 = null;
            Type   type;
            object obj4;

            if (LanguagePrimitives.IsNull(target))
            {
                throw InterpreterError.NewInterpreterException(methodName, typeof(RuntimeException), errorPosition, "InvokeMethodOnNull", ParserStrings.InvokeMethodOnNull, new object[0]);
            }
            obj2 = PSObject.Base(target);
            obj3 = PSObject.AsPSObject(target);
            CallsiteCacheEntryFlags none = CallsiteCacheEntryFlags.None;

            if (callStatic)
            {
                none |= CallsiteCacheEntryFlags.Static;
                type  = (Type)obj2;
            }
            else
            {
                type = obj2.GetType();
            }
            if (valueToSet != AutomationNull.Value)
            {
                none |= CallsiteCacheEntryFlags.ParameterizedSetter;
            }
            if (!obj3.isDeserialized)
            {
                methodInformation = Adapter.FindCachedMethod(type, methodName, invocationConstraints, paramArray, none);
            }
            if (methodInformation == null)
            {
                if (callStatic)
                {
                    staticCLRMember = PSObject.GetStaticCLRMember(target, methodName) as PSMethod;
                }
                else
                {
                    staticCLRMember = obj3.Members[methodName] as PSMethodInfo;
                }
                if (staticCLRMember == null)
                {
                    string fullName = null;
                    if (callStatic)
                    {
                        fullName = type.FullName;
                    }
                    else
                    {
                        fullName = GetTypeFullName(target);
                    }
                    if (valueToSet == AutomationNull.Value)
                    {
                        throw InterpreterError.NewInterpreterException(methodName, typeof(RuntimeException), errorPosition, "MethodNotFound", ParserStrings.MethodNotFound, new object[] { fullName, methodName });
                    }
                    throw InterpreterError.NewInterpreterException(methodName, typeof(RuntimeException), errorPosition, "ParameterizedPropertyAssignmentFailed", ParserStrings.ParameterizedPropertyAssignmentFailed, new object[] { fullName, methodName });
                }
            }
            try
            {
                if (methodInformation != null)
                {
                    object[] objArray;
                    PSObject.memberResolution.WriteLine("cache hit, Calling Method: {0}", new object[] { methodInformation.methodDefinition });
                    if (valueToSet != AutomationNull.Value)
                    {
                        DotNetAdapter.ParameterizedPropertyInvokeSet(methodName, obj2, valueToSet, new MethodInformation[] { methodInformation }, paramArray, false);
                        return(valueToSet);
                    }
                    MethodInformation[] methods = new MethodInformation[] { methodInformation };
                    Adapter.GetBestMethodAndArguments(methodName, methods, paramArray, out objArray);
                    return(DotNetAdapter.AuxiliaryMethodInvoke(obj2, objArray, methodInformation, paramArray));
                }
                if (valueToSet != AutomationNull.Value)
                {
                    PSParameterizedProperty property = staticCLRMember as PSParameterizedProperty;
                    if (property == null)
                    {
                        throw InterpreterError.NewInterpreterException(methodName, typeof(RuntimeException), errorPosition, "ParameterizedPropertyAssignmentFailed", ParserStrings.ParameterizedPropertyAssignmentFailed, new object[] { GetTypeFullName(target), methodName });
                    }
                    property.InvokeSet(valueToSet, paramArray);
                    return(valueToSet);
                }
                PSMethod method = staticCLRMember as PSMethod;
                if (method != null)
                {
                    return(method.Invoke(invocationConstraints, paramArray));
                }
                obj4 = staticCLRMember.Invoke(paramArray);
            }
            catch (MethodInvocationException exception)
            {
                if (exception.ErrorRecord.InvocationInfo == null)
                {
                    exception.ErrorRecord.SetInvocationInfo(new InvocationInfo(null, errorPosition));
                }
                throw;
            }
            catch (RuntimeException exception2)
            {
                if (exception2.ErrorRecord.InvocationInfo == null)
                {
                    exception2.ErrorRecord.SetInvocationInfo(new InvocationInfo(null, errorPosition));
                }
                throw;
            }
            catch (FlowControlException)
            {
                throw;
            }
            catch (ScriptCallDepthException)
            {
                throw;
            }
            catch (Exception exception3)
            {
                CommandProcessorBase.CheckForSevereException(exception3);
                throw InterpreterError.NewInterpreterExceptionByMessage(typeof(RuntimeException), errorPosition, exception3.Message, "MethodInvocationException", exception3);
            }
            return(obj4);
        }
        internal void InitializeRuntimeDefinedParameters(ref bool useCmdletBinding)
        {
            if (this._runtimeDefinedParameters != null)
            {
                return;
            }
            this._runtimeDefinedParameters    = new RuntimeDefinedParameterDictionary();
            this._runtimeDefinedParameterList = new List <RuntimeDefinedParameter>();
            bool flag = false;

            if (!useCmdletBinding)
            {
                for (int index = 0; index < this._parameters.Count; ++index)
                {
                    if (this._parameters[index].HasParameterAttribute())
                    {
                        useCmdletBinding = true;
                        break;
                    }
                }
            }
            int num1 = 0;

            for (int index = 0; index < this._parameters.Count; ++index)
            {
                RuntimeDefinedParameter definedParameter = this._parameters[index].GetRuntimeDefinedParameter(useCmdletBinding);
                if (!useCmdletBinding)
                {
                    ParameterAttribute parameterAttribute = new ParameterAttribute();
                    if (!this._parameters[index].IsSwitchParameter())
                    {
                        parameterAttribute.Position = num1++;
                    }
                    definedParameter.Attributes.Add((Attribute)parameterAttribute);
                }
                else
                {
                    foreach (Attribute attribute in definedParameter.Attributes)
                    {
                        if (attribute is ParameterAttribute parameterAttribute && (parameterAttribute.Position != int.MinValue || !parameterAttribute.ParameterSetName.Equals("__AllParameterSets", StringComparison.OrdinalIgnoreCase)))
                        {
                            flag = true;
                            break;
                        }
                    }
                }
                try
                {
                    this._runtimeDefinedParameters.Add(definedParameter.Name, definedParameter);
                    this._runtimeDefinedParameterList.Add(definedParameter);
                }
                catch (ArgumentException ex)
                {
                    throw InterpreterError.NewInterpreterException((object)null, typeof(RuntimeException), this._parameters[index].NodeToken, "DuplicateFormalParameter", (object)this._parameters[index].NodeToken.TokenText);
                }
            }
            if (!useCmdletBinding || flag)
            {
                return;
            }
            for (int index = 0; index < this._runtimeDefinedParameterList.Count; ++index)
            {
                foreach (Attribute attribute in this._runtimeDefinedParameterList[index].Attributes)
                {
                    if (attribute is ParameterAttribute parameterAttribute && !this._parameters[index].IsSwitchParameter())
                    {
                        int num2 = num1++;
                        parameterAttribute.Position = num2;
                        break;
                    }
                }
            }
        }
Exemple #21
0
        private static CommandProcessorBase AddCommand(PipelineProcessor pipe, CommandParameterInternal[] commandElements, CommandBaseAst commandBaseAst, CommandRedirection[] redirections, System.Management.Automation.ExecutionContext context)
        {
            object               parameterText;
            IScriptExtent        parameterExtent;
            CommandProcessorBase base2;
            InternalCommand      command;
            string               str3;
            HelpCategory         category;
            CommandAst           ast          = commandBaseAst as CommandAst;
            TokenKind            kind         = (ast != null) ? ast.InvocationOperator : TokenKind.Unknown;
            bool dotSource                    = kind == TokenKind.Dot;
            SessionStateInternal sessionState = null;
            int          index                = 0;
            PSModuleInfo info                 = PSObject.Base(commandElements[0].ArgumentValue) as PSModuleInfo;

            if (info != null)
            {
                if ((info.ModuleType == ModuleType.Binary) && (info.SessionState == null))
                {
                    throw InterpreterError.NewInterpreterException(null, typeof(RuntimeException), null, "CantInvokeInBinaryModule", ParserStrings.CantInvokeInBinaryModule, new object[] { info.Name });
                }
                if (info.SessionState == null)
                {
                    throw InterpreterError.NewInterpreterException(null, typeof(RuntimeException), null, "CantInvokeInNonImportedModule", ParserStrings.CantInvokeInNonImportedModule, new object[] { info.Name });
                }
                sessionState = info.SessionState.Internal;
                index++;
            }
            CommandParameterInternal internal3 = commandElements[index];

            if (internal3.ParameterNameSpecified)
            {
                parameterText   = internal3.ParameterText;
                parameterExtent = internal3.ParameterExtent;
                if (!internal3.ArgumentSpecified)
                {
                }
            }
            else
            {
                parameterText   = PSObject.Base(internal3.ArgumentValue);
                parameterExtent = internal3.ArgumentExtent;
            }
            string      str         = dotSource ? "." : ((kind == TokenKind.Ampersand) ? "&" : null);
            ScriptBlock scriptblock = parameterText as ScriptBlock;

            if (scriptblock != null)
            {
                base2 = CommandDiscovery.CreateCommandProcessorForScript(scriptblock, context, !dotSource, sessionState);
            }
            else
            {
                CommandInfo commandInfo = parameterText as CommandInfo;
                if (commandInfo != null)
                {
                    base2 = context.CommandDiscovery.LookupCommandProcessor(commandInfo, context.EngineSessionState.CurrentScope.ScopeOrigin, new bool?(!dotSource), sessionState);
                }
                else
                {
                    string str2 = (parameterText as string) ?? PSObject.ToStringParser(context, parameterText);
                    str = str ?? str2;
                    if (string.IsNullOrEmpty(str2))
                    {
                        throw InterpreterError.NewInterpreterException(parameterText, typeof(RuntimeException), parameterExtent, "BadExpression", ParserStrings.BadExpression, new object[] { dotSource ? "." : "&" });
                    }
                    try
                    {
                        if (sessionState != null)
                        {
                            SessionStateInternal engineSessionState = context.EngineSessionState;
                            try
                            {
                                context.EngineSessionState = sessionState;
                                base2 = context.CreateCommand(str2, dotSource);
                                goto Label_025D;
                            }
                            finally
                            {
                                context.EngineSessionState = engineSessionState;
                            }
                        }
                        base2 = context.CreateCommand(str2, dotSource);
                    }

                    catch (RuntimeException exception)
                    {
                        if (exception.ErrorRecord.InvocationInfo == null)
                        {
                            InvocationInfo invocationInfo = new InvocationInfo(null, parameterExtent, context)
                            {
                                InvocationName = str
                            };
                            exception.ErrorRecord.SetInvocationInfo(invocationInfo);
                        }
                        throw;
                    }
                }
            }
Label_025D:
            command             = base2.Command;
            base2.UseLocalScope = !dotSource && ((command is ScriptCommand) || (command is PSScriptCmdlet));
            bool flag2 = base2 is NativeCommandProcessor;

            for (int i = index + 1; i < commandElements.Length; i++)
            {
                CommandParameterInternal parameter = commandElements[i];
                if ((!parameter.ParameterNameSpecified || !parameter.ParameterName.Equals("-", StringComparison.OrdinalIgnoreCase)) || flag2)
                {
                    if (parameter.ArgumentSplatted)
                    {
                        foreach (CommandParameterInternal internal6 in Splat(parameter.ArgumentValue, parameter.ArgumentExtent))
                        {
                            base2.AddParameter(internal6);
                        }
                    }
                    else
                    {
                        base2.AddParameter(parameter);
                    }
                }
            }
            if (base2.IsHelpRequested(out str3, out category))
            {
                base2 = CommandProcessorBase.CreateGetHelpCommandProcessor(context, str3, category);
            }
            base2.Command.InvocationExtent            = commandBaseAst.Extent;
            base2.Command.MyInvocation.ScriptPosition = commandBaseAst.Extent;
            base2.Command.MyInvocation.InvocationName = str;
            pipe.Add(base2);
            bool flag3 = false;
            bool flag4 = false;
            bool flag5 = false;
            bool flag6 = false;

            if (redirections != null)
            {
                foreach (CommandRedirection redirection in redirections)
                {
                    redirection.Bind(pipe, base2, context);
                    switch (redirection.FromStream)
                    {
                    case RedirectionStream.All:
                        flag3 = true;
                        flag4 = true;
                        flag5 = true;
                        flag6 = true;
                        break;

                    case RedirectionStream.Error:
                        flag3 = true;
                        break;

                    case RedirectionStream.Warning:
                        flag4 = true;
                        break;

                    case RedirectionStream.Verbose:
                        flag5 = true;
                        break;

                    case RedirectionStream.Debug:
                        flag6 = true;
                        break;
                    }
                }
            }
            if (!flag3)
            {
                if (context.ShellFunctionErrorOutputPipe != null)
                {
                    base2.CommandRuntime.ErrorOutputPipe = context.ShellFunctionErrorOutputPipe;
                }
                else
                {
                    base2.CommandRuntime.ErrorOutputPipe.ExternalWriter = context.ExternalErrorOutput;
                }
            }
            if (!flag4 && (context.ExpressionWarningOutputPipe != null))
            {
                base2.CommandRuntime.WarningOutputPipe = context.ExpressionWarningOutputPipe;
                flag4 = true;
            }
            if (!flag5 && (context.ExpressionVerboseOutputPipe != null))
            {
                base2.CommandRuntime.VerboseOutputPipe = context.ExpressionVerboseOutputPipe;
                flag5 = true;
            }
            if (!flag6 && (context.ExpressionDebugOutputPipe != null))
            {
                base2.CommandRuntime.DebugOutputPipe = context.ExpressionDebugOutputPipe;
                flag6 = true;
            }
            if ((context.CurrentCommandProcessor != null) && (context.CurrentCommandProcessor.CommandRuntime != null))
            {
                if (!flag4 && (context.CurrentCommandProcessor.CommandRuntime.WarningOutputPipe != null))
                {
                    base2.CommandRuntime.WarningOutputPipe = context.CurrentCommandProcessor.CommandRuntime.WarningOutputPipe;
                }
                if (!flag5 && (context.CurrentCommandProcessor.CommandRuntime.VerboseOutputPipe != null))
                {
                    base2.CommandRuntime.VerboseOutputPipe = context.CurrentCommandProcessor.CommandRuntime.VerboseOutputPipe;
                }
                if (!flag6 && (context.CurrentCommandProcessor.CommandRuntime.DebugOutputPipe != null))
                {
                    base2.CommandRuntime.DebugOutputPipe = context.CurrentCommandProcessor.CommandRuntime.DebugOutputPipe;
                }
            }
            return(base2);
        }
Exemple #22
0
        internal static object ReplaceOperator(System.Management.Automation.ExecutionContext context, IScriptExtent errorPosition, object lval, object rval, bool ignoreCase)
        {
            string replacement = "";
            object obj2        = "";

            rval = PSObject.Base(rval);
            IList list = rval as IList;

            if (list != null)
            {
                if (list.Count > 2)
                {
                    throw InterpreterError.NewInterpreterException(rval, typeof(RuntimeException), errorPosition, "BadReplaceArgument", ParserStrings.BadReplaceArgument, new object[] { ignoreCase ? "-ireplace" : "-replace", list.Count });
                }
                if (list.Count > 0)
                {
                    obj2 = list[0];
                    if (list.Count > 1)
                    {
                        replacement = PSObject.ToStringParser(context, list[1]);
                    }
                }
            }
            else
            {
                obj2 = rval;
            }
            RegexOptions none = RegexOptions.None;

            if (ignoreCase)
            {
                none = RegexOptions.IgnoreCase;
            }
            Regex regex = obj2 as Regex;

            if (regex == null)
            {
                try
                {
                    regex = NewRegex(PSObject.ToStringParser(context, obj2), none);
                }
                catch (ArgumentException exception)
                {
                    throw InterpreterError.NewInterpreterExceptionWithInnerException(obj2, typeof(RuntimeException), null, "InvalidRegularExpression", ParserStrings.InvalidRegularExpression, exception, new object[] { obj2 });
                }
            }
            IEnumerator enumerator = LanguagePrimitives.GetEnumerator(lval);

            if (enumerator == null)
            {
                string input = ((lval == null) ? string.Empty : lval).ToString();
                return(regex.Replace(input, replacement));
            }
            ArrayList list2 = new ArrayList();

            while (MoveNext(context, errorPosition, enumerator))
            {
                string str3 = PSObject.ToStringParser(context, Current(errorPosition, enumerator));
                list2.Add(regex.Replace(str3, replacement));
            }
            return(list2.ToArray());
        }
Exemple #23
0
        /// <summary>
        /// Collect values for UsingExpressions, in the form of a dictionary and an array.
        ///  - The dictionary form is used when the remote server is PSv5 and later version for handling UsingExpression in Invoke-Command/Start-Job
        ///  - The array form is used when the remote server is PSv3 and PSv4 for handling UsingExpression in Invoke-Command.
        /// </summary>
        /// <remarks>
        /// We still keep the array-form using values because we want to avoid any breaking changes when running Invoke-Command
        /// targeting PSv3 or PSv4 remote end -- if UsingExpressions are all in the same scope, then we still pass an array of using
        /// values to the remote end; otherwise, we will handle UsingExpression as if the remote end is PSv2.
        /// </remarks>
        /// <returns>
        /// A tuple of the dictionary-form and the array-form using values.
        /// If the array-form using value is null, then there are UsingExpressions used in different scopes.
        /// </returns>
        private static Tuple <Dictionary <string, object>, object[]> GetUsingValues(Ast body, bool isTrustedInput, ExecutionContext context, Dictionary <string, object> variables, bool filterNonUsingVariables)
        {
            Diagnostics.Assert(context != null || variables != null, "can't retrieve variables with no context and no variables");

            var usingAsts                  = UsingExpressionAstSearcher.FindAllUsingExpressionExceptForWorkflow(body).ToList();
            var usingValueArray            = new object[usingAsts.Count];
            var usingValueMap              = new Dictionary <string, object>(usingAsts.Count);
            HashSet <string> usingVarNames = (variables != null && filterNonUsingVariables) ? new HashSet <string>() : null;

            // Used to check if the PSv3/PSv4 way of handling UsingExpression can continue to be used.
            bool           hasUsingExprInDifferentScope = false;
            ScriptBlockAst sbClosestToPreUsingExpr      = null;

            UsingExpressionAst usingAst         = null;
            Version            oldStrictVersion = null;

            try
            {
                if (context != null)
                {
                    oldStrictVersion = context.EngineSessionState.CurrentScope.StrictModeVersion;
                    context.EngineSessionState.CurrentScope.StrictModeVersion = PSVersionInfo.PSVersion;
                }

                for (int i = 0; i < usingAsts.Count; ++i)
                {
                    usingAst = (UsingExpressionAst)usingAsts[i];
                    object value = null;

                    // This happens only when GetUsingValues gets called outside the ScriptBlockToPowerShellConverter class
                    if (!hasUsingExprInDifferentScope && HasUsingExpressionsInDifferentScopes(usingAst, body, ref sbClosestToPreUsingExpr))
                    {
                        // If there are UsingExpressions in different scopes, the array-form using values will not be useful
                        // even if the remote end is PSv3 or PSv4, because the way we handle using expression in PSv3 and PSv4
                        // doesn't support UsingExpression in different scopes. In this case, we will set the array-form using
                        // value to be null before return.
                        //
                        // Note that this check only affect array-form using value. In PSv5, we change the way to handle UsingExpression
                        // on both client and server sides. The dictionary-form using values is used and UsingExpression in different
                        // scope is supported.
                        hasUsingExprInDifferentScope = true;
                    }

                    if (variables != null)
                    {
                        var variableAst = usingAst.SubExpression as VariableExpressionAst;
                        if (variableAst == null)
                        {
                            throw InterpreterError.NewInterpreterException(null, typeof(RuntimeException),
                                                                           usingAst.Extent, "CantGetUsingExpressionValueWithSpecifiedVariableDictionary", AutomationExceptions.CantGetUsingExpressionValueWithSpecifiedVariableDictionary, usingAst.Extent.Text);
                        }

                        string varName = variableAst.VariablePath.UserPath;
                        if (varName != null && variables.TryGetValue(varName, out value) && usingVarNames != null)
                        {
                            usingVarNames.Add(varName);
                        }
                    }
                    else
                    {
                        value = Compiler.GetExpressionValue(usingAst.SubExpression, isTrustedInput, context);
                    }

                    // Collect UsingExpression value as an array
                    usingValueArray[i] = value;

                    // Collect UsingExpression value as a dictionary
                    string usingAstKey = PsUtils.GetUsingExpressionKey(usingAst);
                    usingValueMap.TryAdd(usingAstKey, value);
                }
            }
            catch (RuntimeException rte)
            {
                if (rte.ErrorRecord.FullyQualifiedErrorId.Equals("VariableIsUndefined", StringComparison.Ordinal))
                {
                    throw InterpreterError.NewInterpreterException(null, typeof(RuntimeException),
                                                                   usingAst.Extent, "UsingVariableIsUndefined", AutomationExceptions.UsingVariableIsUndefined, rte.ErrorRecord.TargetObject);
                }
                else if (rte.ErrorRecord.FullyQualifiedErrorId.Equals("CantGetUsingExpressionValueWithSpecifiedVariableDictionary", StringComparison.Ordinal))
                {
                    throw;
                }
            }
            finally
            {
                if (context != null)
                {
                    context.EngineSessionState.CurrentScope.StrictModeVersion = oldStrictVersion;
                }
            }

            if (usingVarNames != null)
            {
                string[] keys = variables.Keys.ToArray();
                foreach (string key in keys)
                {
                    if (!usingVarNames.Contains(key))
                    {
                        variables.Remove(key);
                    }
                }
            }

            if (hasUsingExprInDifferentScope)
            {
                usingValueArray = null;
            }

            return(Tuple.Create(usingValueMap, usingValueArray));
        }
 private object PrivateGetValue(ExecutionContext context)
 {
     try
     {
         if (this._useConstantValue)
         {
             return(this._constantValue);
         }
         if (!this._variablePath.IsScopedItem)
         {
             CmdletProviderContext context1           = (CmdletProviderContext)null;
             SessionStateScope     scope              = (SessionStateScope)null;
             SessionStateInternal  engineSessionState = context.EngineSessionState;
             return(engineSessionState.GetVariableValueFromProvider(this._variablePath, out context1, out scope, engineSessionState.currentScope.ScopeOrigin));
         }
         PSVariable variable = this.GetVariable(context);
         if (this._typeConstraint != null && this._typeConstraint.Count == 1 && this._typeConstraint[0].Type.Equals(typeof(PSReference)))
         {
             return(variable != null ? (object)new PSReference((object)variable) : throw InterpreterError.NewInterpreterException((object)this.NodeToken, typeof(RuntimeException), this.NodeToken, "NonExistingVariableReference", (object)this.NodeToken));
         }
         if (variable != null)
         {
             return(variable.Value);
         }
         if (context.Debugger.IsOn)
         {
             context.Debugger.CheckVariableRead(this._varName);
         }
         return((object)null);
     }
     catch (RuntimeException ex)
     {
         if (ex.ErrorRecord != null && ex.ErrorRecord.InvocationInfo == null)
         {
             ex.ErrorRecord.SetInvocationInfo(new InvocationInfo((CommandInfo)null, this.NodeToken, context));
         }
         throw;
     }
 }
Exemple #25
0
        internal static void CheckActionPreference(FunctionContext funcContext, Exception exception)
        {
            ActionPreference preference;

            if (exception is TargetInvocationException)
            {
                exception = exception.InnerException;
            }
            CommandProcessorBase.CheckForSevereException(exception);
            RuntimeException exception2 = exception as RuntimeException;

            if (exception2 == null)
            {
                exception2 = ConvertToRuntimeException(exception, funcContext.CurrentPosition);
            }
            else
            {
                InterpreterError.UpdateExceptionErrorRecordPosition(exception2, funcContext.CurrentPosition);
            }
            RuntimeException.LockStackTrace(exception2);
            ExecutionContext context        = funcContext._executionContext;
            Pipe             outputPipe     = funcContext._outputPipe;
            IScriptExtent    scriptPosition = exception2.ErrorRecord.InvocationInfo.ScriptPosition;

            SetErrorVariables(scriptPosition, exception2, context, outputPipe);
            context.QuestionMarkVariableValue = false;
            bool flag = funcContext._traps.Any <Tuple <Type[], Action <FunctionContext>[], Type[]> >() && (funcContext._traps.Last <Tuple <Type[], Action <FunctionContext>[], Type[]> >().Item2 != null);

            if (!flag && !NeedToQueryForActionPreference(exception2, context))
            {
                throw exception2;
            }
            if (flag)
            {
                preference = ProcessTraps(funcContext, exception2);
            }
            else
            {
                preference = QueryForAction(exception2, exception2.Message, context);
            }
            context.QuestionMarkVariableValue = false;
            switch (preference)
            {
            case ActionPreference.SilentlyContinue:
            case ActionPreference.Ignore:
                return;

            case ActionPreference.Stop:
                exception2.SuppressPromptInInterpreter = true;
                throw exception2;
            }
            if (!flag && exception2.WasThrownFromThrowStatement)
            {
                throw exception2;
            }
            bool flag2 = ReportErrorRecord(scriptPosition, exception2, context);

            context.QuestionMarkVariableValue = false;
            if (!flag2)
            {
                throw exception2;
            }
        }
Exemple #26
0
        private static object[] GetUsingValues(Ast body, ExecutionContext context, Dictionary <string, object> variables, bool filterNonUsingVariables)
        {
            List <Ast> list = UsingExpressionAstSearcher.FindAllUsingExpressionExceptForWorkflow(body).ToList <Ast>();

            object[]           objArray          = new object[list.Count];
            HashSet <string>   set               = ((variables != null) && filterNonUsingVariables) ? new HashSet <string>() : null;
            UsingExpressionAst usingExpr         = null;
            Version            strictModeVersion = null;

            try
            {
                if (context != null)
                {
                    strictModeVersion = context.EngineSessionState.CurrentScope.StrictModeVersion;
                    context.EngineSessionState.CurrentScope.StrictModeVersion = PSVersionInfo.PSVersion;
                }
                for (int i = 0; i < objArray.Length; i++)
                {
                    usingExpr = (UsingExpressionAst)list[i];
                    if (IsUsingExpressionInFunction(usingExpr, body))
                    {
                        throw InterpreterError.NewInterpreterException(null, typeof(RuntimeException), usingExpr.Extent, "UsingVariableNotSupportedInFunctionOrFilter", AutomationExceptions.UsingVariableNotSupportedInFunctionOrFilter, new object[] { usingExpr });
                    }
                    object obj2 = null;
                    if (variables != null)
                    {
                        VariableExpressionAst subExpression = usingExpr.SubExpression as VariableExpressionAst;
                        if (subExpression == null)
                        {
                            throw InterpreterError.NewInterpreterException(null, typeof(RuntimeException), usingExpr.Extent, "CantGetUsingExpressionValueWithSpecifiedVariableDictionary", AutomationExceptions.CantGetUsingExpressionValueWithSpecifiedVariableDictionary, new object[] { usingExpr.Extent.Text });
                        }
                        string userPath = subExpression.VariablePath.UserPath;
                        if (((userPath != null) && variables.TryGetValue(userPath, out obj2)) && (set != null))
                        {
                            set.Add(userPath);
                        }
                    }
                    else
                    {
                        obj2 = Compiler.GetExpressionValue(usingExpr.SubExpression, context, (IList)null);
                    }
                    objArray[i] = obj2;
                    usingExpr.RuntimeUsingIndex = i;
                }
            }
            catch (RuntimeException exception)
            {
                if (exception.ErrorRecord.FullyQualifiedErrorId.Equals("VariableIsUndefined", StringComparison.Ordinal))
                {
                    throw InterpreterError.NewInterpreterException(null, typeof(RuntimeException), usingExpr.Extent, "UsingVariableIsUndefined", AutomationExceptions.UsingVariableIsUndefined, new object[] { exception.ErrorRecord.TargetObject });
                }
                if (exception.ErrorRecord.FullyQualifiedErrorId.Equals("UsingVariableNotSupportedInFunctionOrFilter", StringComparison.Ordinal) || exception.ErrorRecord.FullyQualifiedErrorId.Equals("CantGetUsingExpressionValueWithSpecifiedVariableDictionary", StringComparison.Ordinal))
                {
                    throw;
                }
            }
            finally
            {
                if (context != null)
                {
                    context.EngineSessionState.CurrentScope.StrictModeVersion = strictModeVersion;
                }
            }
            if (set != null)
            {
                foreach (string str2 in variables.Keys.ToArray <string>())
                {
                    if (!set.Contains(str2))
                    {
                        variables.Remove(str2);
                    }
                }
            }
            return(objArray);
        }
Exemple #27
0
 internal static void ThrowError(ScriptBlockToPowerShellNotSupportedException ex, Ast ast)
 {
     InterpreterError.UpdateExceptionErrorRecordPosition(ex, ast.Extent);
     throw ex;
 }
        private void ExecuteStatement(
            ParseTreeNode statement,
            Array input,
            Pipe outputPipe,
            ref ArrayList resultList,
            ExecutionContext context)
        {
            ScriptTrace.TraceLine(context, statement);
            Exception e = (Exception)null;

            try
            {
                try
                {
                    if (statement.IsVoidable)
                    {
                        statement.Execute(input, (Pipe)null, context);
                    }
                    else
                    {
                        statement.Execute(input, outputPipe, ref resultList, context);
                    }
                    ParseTreeNode parseTreeNode = statement;
                    while (parseTreeNode is AssignmentStatementNode assignmentStatementNode)
                    {
                        parseTreeNode = assignmentStatementNode.RightHandSide;
                    }
                    if (parseTreeNode.IsExpression)
                    {
                        context.QuestionMarkVariableValue = true;
                    }
                    else if (parseTreeNode is PipelineNode pipelineNode)
                    {
                        context.QuestionMarkVariableValue = !pipelineNode.ExecutionFailed(context);
                    }
                }
                catch (COMException ex)
                {
                    throw InterpreterError.NewInterpreterExceptionWithInnerException((object)null, typeof(RuntimeException), statement.NodeToken, "COMException", (Exception)ex, (object)ex.Message);
                }
                catch (InvalidComObjectException ex)
                {
                    throw InterpreterError.NewInterpreterExceptionWithInnerException((object)null, typeof(RuntimeException), statement.NodeToken, "InvalidComObjectException", (Exception)ex, (object)ex.Message);
                }
            }
            catch (ReturnException ex)
            {
                if (resultList == null || resultList.Count == 0)
                {
                    e = (Exception)ex;
                }
                else
                {
                    ParseTreeNode.AppendResult(context, ex.Argument, (Pipe)null, ref resultList);
                    ex.SetArgument((object)resultList.ToArray());
                    resultList = (ArrayList)null;
                    e          = (Exception)ex;
                }
            }
            catch (RuntimeException ex)
            {
                e = this.HandleException(statement.NodeToken, ex, outputPipe, ref resultList, context);
            }
            if (e != null)
            {
                RuntimeException.LockStackTrace(e);
                throw e;
            }
        }
Exemple #29
0
        /// <summary>
        /// Given the start (offset) of the next token, traverse through
        /// the string to find the next token, stripping correctly
        /// enclosed quotes.
        /// </summary>
        /// <param name="input">
        /// Input string
        /// </param>
        /// <param name="_offset">
        /// Current offset position for the string parser.
        /// </param>
        /// <returns>
        /// The next token on the input string
        /// </returns>
        private Token GetNextToken(string input, ref int _offset)
        {
            StringBuilder sb = new StringBuilder();
            //bool singleQuoted = false;
            //bool doubleQuoted = false;
            bool readingIdentifier = false;

            while (_offset < input.Length)
            {
                char cc = input[_offset++];
                if ((cc == ',') || (cc == '+') || (cc == '!'))
                {
                    if (!readingIdentifier)
                    {
                        sb.Append(cc);
                    }
                    else
                    {
                        _offset--;
                    }
                    break;
                }
                else
                {
                    sb.Append(cc);
                    readingIdentifier = true;
                }
            }

            string result = sb.ToString().Trim();

            // If resulting identifier is enclosed in paired quotes,
            // remove the only the first pair of quotes from the string
            if (result.Length >= 2 &&
                ((result[0] == '\'' && result[result.Length - 1] == '\'') ||
                 (result[0] == '\"' && result[result.Length - 1] == '\"')))
            {
                result = result.Substring(1, result.Length - 2);
            }

            result = result.Trim();

            // possible empty token because white spaces are enclosed in quotation marks.
            if (String.IsNullOrWhiteSpace(result))
            {
                throw InterpreterError.NewInterpreterException(input, typeof(RuntimeException),
                                                               null, "EmptyTokenString", EnumExpressionEvaluatorStrings.EmptyTokenString,
                                                               EnumMinimumDisambiguation.EnumAllValues(typeof(T)));
            }
            else if (result[0] == '(')
            {
                int matchIndex = input.IndexOf(')', _offset);
                if (result[result.Length - 1] == ')' || matchIndex >= 0)
                {
                    throw InterpreterError.NewInterpreterException(input, typeof(RuntimeException),
                                                                   null, "NoIdentifierGroupingAllowed", EnumExpressionEvaluatorStrings.NoIdentifierGroupingAllowed);
                }
            }
            if (result.Equals(","))
            {
                return(new Token(TokenKind.Or));
            }
            else if (result.Equals("+"))
            {
                return(new Token(TokenKind.And));
            }
            else if (result.Equals("!"))
            {
                return(new Token(TokenKind.Not));
            }
            else
            {
                return(new Token(result));
            }
        }
Exemple #30
0
 internal void Validate(Parser parser)
 {
     if (!this._validated && this._catchBlocks.Count > 1)
     {
         Exception exception = (Exception)null;
         try
         {
             for (int index1 = 0; index1 < this._catchBlocks.Count - 1; ++index1)
             {
                 ExceptionHandlerNode catchBlock1 = this._catchBlocks[index1];
                 for (int index2 = index1 + 1; index2 < this._catchBlocks.Count; ++index2)
                 {
                     ExceptionHandlerNode catchBlock2 = this._catchBlocks[index2];
                     if (catchBlock1.ExceptionTypes == null)
                     {
                         if (parser != null)
                         {
                             parser.ReportException((object)null, typeof(ParseException), catchBlock1.NodeToken, "EmptyCatchNotLast");
                             break;
                         }
                         exception = (Exception)InterpreterError.NewInterpreterException((object)null, typeof(RuntimeException), catchBlock1.NodeToken, "EmptyCatchNotLast");
                         break;
                     }
                     if (catchBlock2.ExceptionTypes != null)
                     {
                         foreach (TypeLiteral exceptionType1 in (Collection <TypeLiteral>)catchBlock1.ExceptionTypes)
                         {
                             Type type1 = exceptionType1.Type;
                             foreach (TypeLiteral exceptionType2 in (Collection <TypeLiteral>)catchBlock2.ExceptionTypes)
                             {
                                 Type type2 = exceptionType2.Type;
                                 if (type1 == type2 || type2.IsSubclassOf(type1))
                                 {
                                     if (parser != null)
                                     {
                                         parser.ReportException((object)null, typeof(ParseException), exceptionType2.Token, "ExceptionTypeAlreadyCaught", (object)type2);
                                     }
                                     else
                                     {
                                         exception = (Exception)InterpreterError.NewInterpreterException((object)null, typeof(RuntimeException), exceptionType2.Token, "ExceptionTypeAlreadyCaught", (object)type2);
                                     }
                                 }
                             }
                         }
                     }
                 }
             }
         }
         catch (ParseException ex)
         {
             throw;
         }
         catch (RuntimeException ex)
         {
             return;
         }
         if (exception != null)
         {
             throw exception;
         }
     }
     this._validated = true;
 }