Example #1
0
 private static object GetUsingValue(MutableTuple tuple, int index, ExecutionContext context)
 {
     UsingResult usingValueFromTuple = GetUsingValueFromTuple(tuple, index);
     if (usingValueFromTuple != null)
     {
         return usingValueFromTuple.Value;
     }
     for (SessionStateScope scope = context.EngineSessionState.CurrentScope; scope != null; scope = scope.Parent)
     {
         usingValueFromTuple = GetUsingValueFromTuple(scope.LocalsTuple, index);
         if (usingValueFromTuple != null)
         {
             return usingValueFromTuple.Value;
         }
         foreach (MutableTuple tuple2 in scope.DottedScopes)
         {
             usingValueFromTuple = GetUsingValueFromTuple(tuple2, index);
             if (usingValueFromTuple != null)
             {
                 return usingValueFromTuple.Value;
             }
         }
     }
     throw InterpreterError.NewInterpreterException(null, typeof(RuntimeException), null, "UsingWithoutInvokeCommand", ParserStrings.UsingWithoutInvokeCommand, new object[0]);
 }
Example #2
0
        private static UsingResult GetUsingValueFromTuple(MutableTuple tuple, string usingExpressionKey, int index)
        {
            var boundParameters =
                tuple.GetAutomaticVariable(AutomaticVariable.PSBoundParameters) as PSBoundParametersDictionary;

            if (boundParameters != null)
            {
                var implicitUsingParameters = boundParameters.ImplicitUsingParameters;
                if (implicitUsingParameters != null)
                {
                    if (implicitUsingParameters.Contains(usingExpressionKey))
                    {
                        return(new UsingResult {
                            Value = implicitUsingParameters[usingExpressionKey]
                        });
                    }
                    else if (implicitUsingParameters.Contains(index))
                    {
                        // Handle downlevel (V4) using variables by using index to look up using value.
                        return(new UsingResult {
                            Value = implicitUsingParameters[index]
                        });
                    }
                }
            }

            return(null);
        }
Example #3
0
        internal void CaptureLocals()
        {
            if (this._sessionState == null)
            {
                throw PSTraceSource.NewInvalidOperationException("Modules", "InvalidOperationOnBinaryModule", new object[0]);
            }
            ExecutionContext         executionContextFromTLS = LocalPipeline.GetExecutionContextFromTLS();
            MutableTuple             localsTuple             = executionContextFromTLS.EngineSessionState.CurrentScope.LocalsTuple;
            IEnumerable <PSVariable> values = executionContextFromTLS.EngineSessionState.CurrentScope.Variables.Values;

            if (localsTuple != null)
            {
                Dictionary <string, PSVariable> result = new Dictionary <string, PSVariable>();
                localsTuple.GetVariableTable(result, false);
                values = result.Values.Concat <PSVariable>(values);
            }
            foreach (PSVariable variable in values)
            {
                try
                {
                    if (variable.Options == ScopedItemOptions.None)
                    {
                        PSVariable variable2 = new PSVariable(variable.Name, variable.Value, variable.Options, variable.Attributes, variable.Description);
                        this._sessionState.Internal.NewVariable(variable2, false);
                    }
                }
                catch (SessionStateException)
                {
                }
            }
        }
Example #4
0
        public static object[] GetTupleValues(MutableTuple tuple)
        {
            List <object> args = new List <object>();

            GetTupleValues(tuple, args);
            return(args.ToArray());
        }
Example #5
0
        private static object GetUsingValue(MutableTuple tuple, int index, ExecutionContext context)
        {
            UsingResult usingValueFromTuple = GetUsingValueFromTuple(tuple, index);

            if (usingValueFromTuple != null)
            {
                return(usingValueFromTuple.Value);
            }
            for (SessionStateScope scope = context.EngineSessionState.CurrentScope; scope != null; scope = scope.Parent)
            {
                usingValueFromTuple = GetUsingValueFromTuple(scope.LocalsTuple, index);
                if (usingValueFromTuple != null)
                {
                    return(usingValueFromTuple.Value);
                }
                foreach (MutableTuple tuple2 in scope.DottedScopes)
                {
                    usingValueFromTuple = GetUsingValueFromTuple(tuple2, index);
                    if (usingValueFromTuple != null)
                    {
                        return(usingValueFromTuple.Value);
                    }
                }
            }
            throw InterpreterError.NewInterpreterException(null, typeof(RuntimeException), null, "UsingWithoutInvokeCommand", ParserStrings.UsingWithoutInvokeCommand, new object[0]);
        }
Example #6
0
 private void Init()
 {
     _scriptBlock       = base._scriptBlock;
     _obsoleteAttribute = _scriptBlock.ObsoleteAttribute;
     _runOptimizedCode  = _scriptBlock.Compile(optimized: _context._debuggingMode > 0 ? false : UseLocalScope);
     _localsTuple       = _scriptBlock.MakeLocalsTuple(_runOptimizedCode);
 }
Example #7
0
        public static MutableTuple MakeTuple(Type tupleType, Dictionary <string, int> nameToIndexMap)
        {
            int          size     = GetSize(tupleType);
            BitArray     bitArray = new BitArray(size);
            MutableTuple tuple    = MakeTuple(tupleType, size, bitArray);

            tuple._nameToIndexMap = nameToIndexMap;
            return(tuple);
        }
Example #8
0
        private static CommandCompletion CompleteInputImpl(Ast ast, Token[] tokens, IScriptPosition positionOfCursor, Hashtable options)
        {
            PowerShell powershell        = PowerShell.Create(RunspaceMode.CurrentRunspace);
            int        replacementIndex  = -1;
            int        replacementLength = -1;
            List <CompletionResult> list = null;

            if (NeedToInvokeLegacyTabExpansion(powershell))
            {
                Tuple <string, int, int> inputAndCursorFromAst = GetInputAndCursorFromAst(positionOfCursor);
                list              = InvokeLegacyTabExpansion(powershell, inputAndCursorFromAst.Item1, inputAndCursorFromAst.Item2, false, out replacementIndex, out replacementLength);
                replacementIndex += inputAndCursorFromAst.Item3;
            }
            if ((list == null) || (list.Count == 0))
            {
                ExecutionContext executionContextFromTLS = LocalPipeline.GetExecutionContextFromTLS();
                MutableTuple     tuple2 = null;
                foreach (CallStackFrame frame in executionContextFromTLS.Debugger.GetCallStack())
                {
                    dynamic obj2  = PSObject.AsPSObject(frame);
                    var     site1 = CallSite <Func <CallSite, object, bool> > .Create(Binder.UnaryOperation(CSharpBinderFlags.None, ExpressionType.IsTrue, typeof(CommandCompletion), new CSharpArgumentInfo[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }));

                    if (site1.Target(site1, obj2.Command.Equals("TabExpansion2", StringComparison.OrdinalIgnoreCase)))
                    {
                        tuple2 = frame.FunctionContext._localsTuple;
                        break;
                    }
                }
                SessionStateScope currentScope = null;
                if (tuple2 != null)
                {
                    currentScope = executionContextFromTLS.EngineSessionState.CurrentScope;
                    SessionStateScope parent = executionContextFromTLS.EngineSessionState.CurrentScope;
                    while ((parent != null) && (parent.LocalsTuple != tuple2))
                    {
                        parent = parent.Parent;
                    }
                    if (parent != null)
                    {
                        executionContextFromTLS.EngineSessionState.CurrentScope = parent.Parent;
                    }
                }
                try
                {
                    list = new CompletionAnalysis(ast, tokens, positionOfCursor, options).GetResults(powershell, out replacementIndex, out replacementLength);
                }
                finally
                {
                    if (currentScope != null)
                    {
                        executionContextFromTLS.EngineSessionState.CurrentScope = currentScope;
                    }
                }
            }
            return(new CommandCompletion(new Collection <CompletionResult>(list ?? EmptyCompletionResult), -1, replacementIndex, replacementLength));
        }
Example #9
0
        internal SessionStateInternal(SessionStateInternal parent, bool linkToGlobal, ExecutionContext context)
        {
            if (context == null)
            {
                throw PSTraceSource.NewArgumentNullException(nameof(context));
            }

            ExecutionContext = context;

            // Create the working directory stack. This
            // is used for the pushd and popd commands

            _workingLocationStack = new Dictionary <string, Stack <PathInfo> >(StringComparer.OrdinalIgnoreCase);

            // Conservative choice to limit the Set-Location history in order to limit memory impact in case of a regression.
            const int locationHistoryLimit = 20;

            _setLocationHistory = new HistoryStack <PathInfo>(locationHistoryLimit);

            GlobalScope   = new SessionStateScope(null);
            ModuleScope   = GlobalScope;
            _currentScope = GlobalScope;

            InitializeSessionStateInternalSpecialVariables(false);

            // Create the push the global scope on as
            // the starting script scope.  That way, if you dot-source a script
            // that uses variables qualified by script: it works.
            GlobalScope.ScriptScope = GlobalScope;

            if (parent != null)
            {
                GlobalScope.Parent = parent.GlobalScope;

                // Copy the drives and providers from the parent...
                CopyProviders(parent);
                // During loading of core modules, providers are not populated.
                // We set the drive information later
                if (Providers != null && Providers.Count > 0)
                {
                    CurrentDrive = parent.CurrentDrive;
                }

                // Link it to the global scope...
                if (linkToGlobal)
                {
                    GlobalScope = parent.GlobalScope;
                }
            }
            else
            {
                _currentScope.LocalsTuple = MutableTuple.MakeTuple(Compiler.DottedLocalsTupleType, Compiler.DottedLocalsNameIndexMap);
            }
        }
Example #10
0
 private static UsingResult GetUsingValueFromTuple(MutableTuple tuple, int index)
 {
     PSBoundParametersDictionary automaticVariable = tuple.GetAutomaticVariable(AutomaticVariable.PSBoundParameters) as PSBoundParametersDictionary;
     if (automaticVariable != null)
     {
         IList implicitUsingParameters = automaticVariable.ImplicitUsingParameters;
         if ((implicitUsingParameters != null) && (index <= (implicitUsingParameters.Count - 1)))
         {
             return new UsingResult { Value = implicitUsingParameters[index] };
         }
     }
     return null;
 }
        private void Init()
        {
            _scriptBlock       = base._scriptBlock;
            _obsoleteAttribute = _scriptBlock.ObsoleteAttribute;
            _runOptimizedCode  = _scriptBlock.Compile(optimized: _context._debuggingMode <= 0 && UseLocalScope);
            _localsTuple       = _scriptBlock.MakeLocalsTuple(_runOptimizedCode);

            if (UseLocalScope)
            {
                Diagnostics.Assert(CommandScope.LocalsTuple == null, "a newly created scope shouldn't have it's tuple set.");
                CommandScope.LocalsTuple = _localsTuple;
            }
        }
Example #12
0
 private static void GetTupleValues(MutableTuple tuple, List <object> args)
 {
     Type[] genericArguments = tuple.GetType().GetGenericArguments();
     for (int i = 0; i < genericArguments.Length; i++)
     {
         if (typeof(MutableTuple).IsAssignableFrom(genericArguments[i]))
         {
             GetTupleValues((MutableTuple)tuple.GetValue(i), args);
         }
         else if (genericArguments[i] != typeof(LanguagePrimitives.Null))
         {
             args.Add(tuple.GetValue(i));
         }
     }
 }
Example #13
0
        internal bool IsValueSet(int index)
        {
            if (this._size < 0x80)
            {
                return(this._valuesSet[index]);
            }
            MutableTuple valueImpl = this;

            int[] source = GetAccessPath(this._size, index).ToArray <int>();
            for (int i = 0; i < (source.Length - 1); i++)
            {
                valueImpl = (MutableTuple)valueImpl.GetValueImpl(source[i]);
            }
            return(valueImpl._valuesSet[source.Last <int>()]);
        }
Example #14
0
        private static UsingResult GetUsingValueFromTuple(MutableTuple tuple, int index)
        {
            PSBoundParametersDictionary automaticVariable = tuple.GetAutomaticVariable(AutomaticVariable.PSBoundParameters) as PSBoundParametersDictionary;

            if (automaticVariable != null)
            {
                IList implicitUsingParameters = automaticVariable.ImplicitUsingParameters;
                if ((implicitUsingParameters != null) && (index <= (implicitUsingParameters.Count - 1)))
                {
                    return(new UsingResult {
                        Value = implicitUsingParameters[index]
                    });
                }
            }
            return(null);
        }
Example #15
0
        internal static int FindMatchingHandler(MutableTuple tuple, RuntimeException rte, Type[] types, ExecutionContext context)
        {
            Exception replaceParentContainsErrorRecordException = rte;
            Exception innerException = rte.InnerException;
            int       index          = -1;

            if (innerException != null)
            {
                index = FindMatchingHandlerByType(innerException.GetType(), types);
                replaceParentContainsErrorRecordException = innerException;
            }
            if ((index == -1) || types[index].Equals(typeof(CatchAll)))
            {
                index = FindMatchingHandlerByType(rte.GetType(), types);
                replaceParentContainsErrorRecordException = rte;
            }
            if ((index == -1) || types[index].Equals(typeof(CatchAll)))
            {
                ActionPreferenceStopException exception3 = rte as ActionPreferenceStopException;
                if (exception3 != null)
                {
                    replaceParentContainsErrorRecordException = exception3.ErrorRecord.Exception;
                    if (replaceParentContainsErrorRecordException is RuntimeException)
                    {
                        return(FindMatchingHandler(tuple, (RuntimeException)replaceParentContainsErrorRecordException, types, context));
                    }
                    if (replaceParentContainsErrorRecordException != null)
                    {
                        index = FindMatchingHandlerByType(replaceParentContainsErrorRecordException.GetType(), types);
                    }
                }
                else if ((rte is CmdletInvocationException) && (innerException != null))
                {
                    replaceParentContainsErrorRecordException = innerException.InnerException;
                    if (replaceParentContainsErrorRecordException != null)
                    {
                        index = FindMatchingHandlerByType(replaceParentContainsErrorRecordException.GetType(), types);
                    }
                }
            }
            if (index != -1)
            {
                ErrorRecord record = new ErrorRecord(rte.ErrorRecord, replaceParentContainsErrorRecordException);
                tuple.SetAutomaticVariable(AutomaticVariable.Underbar, record, context);
            }
            return(index);
        }
Example #16
0
 public PSScriptCmdlet(ScriptBlock scriptBlock, bool useNewScope, bool fromScriptFile, System.Management.Automation.ExecutionContext context)
 {
     this._scriptBlock = scriptBlock;
     this._useLocalScope = useNewScope;
     this._fromScriptFile = fromScriptFile;
     this._runOptimized = this._scriptBlock.Compile((context._debuggingMode <= 0) && useNewScope);
     this._localsTuple = this._scriptBlock.MakeLocalsTuple(this._runOptimized);
     this._localsTuple.SetAutomaticVariable(AutomaticVariable.PSCmdlet, this, context);
     this._scriptBlock.SetPSScriptRootAndPSCommandPath(this._localsTuple, context);
     FunctionContext context2 = new FunctionContext {
         _localsTuple = this._localsTuple,
         _scriptBlock = this._scriptBlock,
         _sequencePoints = this._scriptBlock.SequencePoints,
         _executionContext = context
     };
     this._functionContext = context2;
     this._rethrowExitException = context.ScriptCommandProcessorShouldRethrowExit;
     context.ScriptCommandProcessorShouldRethrowExit = false;
 }
Example #17
0
        public PSScriptCmdlet(ScriptBlock scriptBlock, bool useNewScope, bool fromScriptFile, System.Management.Automation.ExecutionContext context)
        {
            this._scriptBlock    = scriptBlock;
            this._useLocalScope  = useNewScope;
            this._fromScriptFile = fromScriptFile;
            this._runOptimized   = this._scriptBlock.Compile((context._debuggingMode <= 0) && useNewScope);
            this._localsTuple    = this._scriptBlock.MakeLocalsTuple(this._runOptimized);
            this._localsTuple.SetAutomaticVariable(AutomaticVariable.PSCmdlet, this, context);
            this._scriptBlock.SetPSScriptRootAndPSCommandPath(this._localsTuple, context);
            FunctionContext context2 = new FunctionContext {
                _localsTuple      = this._localsTuple,
                _scriptBlock      = this._scriptBlock,
                _sequencePoints   = this._scriptBlock.SequencePoints,
                _executionContext = context
            };

            this._functionContext      = context2;
            this._rethrowExitException = context.ScriptCommandProcessorShouldRethrowExit;
            context.ScriptCommandProcessorShouldRethrowExit = false;
        }
Example #18
0
        private static MutableTuple MakeTuple(Type tupleType, int size, BitArray bitArray)
        {
            MutableTuple tuple = (MutableTuple)Activator.CreateInstance(tupleType);

            tuple._size      = size;
            tuple._valuesSet = bitArray;
            if (size > 0x80)
            {
                while (size > 0x80)
                {
                    size = ((size + 0x80) - 1) / 0x80;
                }
                for (int i = 0; i < size; i++)
                {
                    PropertyInfo property = tupleType.GetProperty("Item" + string.Format(CultureInfo.InvariantCulture, "{0:D3}", new object[] { i }));
                    tuple.SetValueImpl(i, MakeTuple(property.PropertyType, null));
                }
            }
            return(tuple);
        }
Example #19
0
 private void SetNestedValue(int size, int index, object value)
 {
     if (size < 0x80)
     {
         this.SetValueImpl(index, value);
     }
     else
     {
         MutableTuple valueImpl = this;
         int          num       = -1;
         foreach (int num2 in GetAccessPath(size, index))
         {
             if (num != -1)
             {
                 valueImpl = (MutableTuple)valueImpl.GetValueImpl(num);
             }
             num = num2;
         }
         valueImpl.SetValueImpl(num, value);
     }
 }
Example #20
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);
        }
Example #21
0
        /// <summary>
        /// Gets the values from a tuple including unpacking nested values.
        /// </summary>
        public static object[] GetTupleValues(MutableTuple tuple)
        {
            //ContractUtils.RequiresNotNull(tuple, "tuple");

            List<object> res = new List<object>();

            GetTupleValues(tuple, res);

            return res.ToArray();
        }
Example #22
0
        internal static PowerShell Convert(ScriptBlockAst body, IEnumerable <ParameterAst> functionParameters, ExecutionContext context, Dictionary <string, object> variables, bool filterNonUsingVariables, bool?createLocalScope, object[] args)
        {
            string     str;
            string     str2;
            PowerShell shell;

            ExecutionContext.CheckStackDepth();
            if (args == null)
            {
                args = ScriptBlock.EmptyArray;
            }
            body.GetSimplePipeline(false, out str, out str2);
            if (str != null)
            {
                throw new ScriptBlockToPowerShellNotSupportedException(str, null, str2, new object[0]);
            }
            ScriptBlockToPowerShellChecker visitor = new ScriptBlockToPowerShellChecker {
                ScriptBeingConverted = body
            };

            if (functionParameters != null)
            {
                foreach (ParameterAst ast in functionParameters)
                {
                    ast.InternalVisit(visitor);
                }
            }
            body.InternalVisit(visitor);
            if (((context == null) && (visitor.HasUsingExpr || visitor.UsesParameter)) && (variables == null))
            {
                throw new PSInvalidOperationException(AutomationExceptions.CantConvertScriptBlockWithNoContext);
            }
            try
            {
                ScriptBlockToPowerShellConverter converter = new ScriptBlockToPowerShellConverter {
                    _context          = context,
                    _createLocalScope = createLocalScope
                };
                if (visitor.HasUsingExpr)
                {
                    converter._usingValues = GetUsingValues(body, context, variables, filterNonUsingVariables);
                }
                if (visitor.UsesParameter)
                {
                    SessionStateScope scope = context.EngineSessionState.NewScope(false);
                    context.EngineSessionState.CurrentScope             = scope;
                    context.EngineSessionState.CurrentScope.ScopeOrigin = CommandOrigin.Internal;
                    MutableTuple locals            = MutableTuple.MakeTuple(Compiler.DottedLocalsTupleType, Compiler.DottedLocalsNameIndexMap);
                    bool         usesCmdletBinding = false;
                    object[]     objArray          = ScriptBlock.BindArgumentsForScripblockInvoke((RuntimeDefinedParameter[])((IParameterMetadataProvider)body).GetParameterMetadata(true, ref usesCmdletBinding).Data, args, context, false, null, locals);
                    locals.SetAutomaticVariable(AutomaticVariable.Args, objArray, context);
                    scope.LocalsTuple = locals;
                }
                foreach (PipelineAst ast2 in body.EndBlock.Statements.OfType <PipelineAst>())
                {
                    converter._powershell.AddStatement();
                    converter.ConvertPipeline(ast2);
                }
                shell = converter._powershell;
            }
            finally
            {
                if (visitor.UsesParameter)
                {
                    context.EngineSessionState.RemoveScope(context.EngineSessionState.CurrentScope);
                }
            }
            return(shell);
        }
 private void Init()
 {
     this._scriptBlock      = base._scriptBlock;
     this._runOptimizedCode = this._scriptBlock.Compile((base._context._debuggingMode <= 0) && base.UseLocalScope);
     this._localsTuple      = this._scriptBlock.MakeLocalsTuple(this._runOptimizedCode);
 }
Example #24
0
 public PSScriptCmdlet(ScriptBlock scriptBlock, bool useNewScope, bool fromScriptFile, ExecutionContext context)
 {
     _scriptBlock = scriptBlock;
     _useLocalScope = useNewScope;
     _fromScriptFile = fromScriptFile;
     _runOptimized = _scriptBlock.Compile(optimized: context._debuggingMode > 0 ? false : useNewScope);
     _localsTuple = _scriptBlock.MakeLocalsTuple(_runOptimized);
     _localsTuple.SetAutomaticVariable(AutomaticVariable.PSCmdlet, this, context);
     _scriptBlock.SetPSScriptRootAndPSCommandPath(_localsTuple, context);
     _functionContext = new FunctionContext
     {
         _localsTuple = _localsTuple,
         _scriptBlock = _scriptBlock,
         _file = _scriptBlock.File,
         _sequencePoints = _scriptBlock.SequencePoints,
         _debuggerHidden = _scriptBlock.DebuggerHidden,
         _debuggerStepThrough = _scriptBlock.DebuggerStepThrough,
         _executionContext = context,
     };
     _rethrowExitException = context.ScriptCommandProcessorShouldRethrowExit;
     context.ScriptCommandProcessorShouldRethrowExit = false;
 }
 private void Init()
 {
     this._scriptBlock = base._scriptBlock;
     this._runOptimizedCode = this._scriptBlock.Compile((base._context._debuggingMode <= 0) && base.UseLocalScope);
     this._localsTuple = this._scriptBlock.MakeLocalsTuple(this._runOptimizedCode);
 }
Example #26
0
 private static void GetTupleValues(MutableTuple tuple, List<object> args)
 {
     Type[] genericArguments = tuple.GetType().GetGenericArguments();
     for (int i = 0; i < genericArguments.Length; i++)
     {
         if (typeof(MutableTuple).IsAssignableFrom(genericArguments[i]))
         {
             GetTupleValues((MutableTuple) tuple.GetValue(i), args);
         }
         else if (genericArguments[i] != typeof(LanguagePrimitives.Null))
         {
             args.Add(tuple.GetValue(i));
         }
     }
 }
Example #27
0
 internal static void SetAutomaticVariable(AutomaticVariable variable, object value, MutableTuple locals)
 {
     locals.SetValue((int)variable, value);
 }
Example #28
0
 internal static int FindMatchingHandler(MutableTuple tuple, RuntimeException rte, Type[] types, ExecutionContext context)
 {
     Exception replaceParentContainsErrorRecordException = rte;
     Exception innerException = rte.InnerException;
     int index = -1;
     if (innerException != null)
     {
         index = FindMatchingHandlerByType(innerException.GetType(), types);
         replaceParentContainsErrorRecordException = innerException;
     }
     if ((index == -1) || types[index].Equals(typeof(CatchAll)))
     {
         index = FindMatchingHandlerByType(rte.GetType(), types);
         replaceParentContainsErrorRecordException = rte;
     }
     if ((index == -1) || types[index].Equals(typeof(CatchAll)))
     {
         ActionPreferenceStopException exception3 = rte as ActionPreferenceStopException;
         if (exception3 != null)
         {
             replaceParentContainsErrorRecordException = exception3.ErrorRecord.Exception;
             if (replaceParentContainsErrorRecordException is RuntimeException)
             {
                 return FindMatchingHandler(tuple, (RuntimeException) replaceParentContainsErrorRecordException, types, context);
             }
             if (replaceParentContainsErrorRecordException != null)
             {
                 index = FindMatchingHandlerByType(replaceParentContainsErrorRecordException.GetType(), types);
             }
         }
         else if ((rte is CmdletInvocationException) && (innerException != null))
         {
             replaceParentContainsErrorRecordException = innerException.InnerException;
             if (replaceParentContainsErrorRecordException != null)
             {
                 index = FindMatchingHandlerByType(replaceParentContainsErrorRecordException.GetType(), types);
             }
         }
     }
     if (index != -1)
     {
         ErrorRecord record = new ErrorRecord(rte.ErrorRecord, replaceParentContainsErrorRecordException);
         tuple.SetAutomaticVariable(AutomaticVariable.Underbar, record, context);
     }
     return index;
 }
Example #29
0
        private static ActionPreference ProcessTraps(FunctionContext funcContext, RuntimeException rte)
        {
            int       index = -1;
            Exception replaceParentContainsErrorRecordException = null;
            Exception innerException = rte.InnerException;

            Type[] types = funcContext._traps.Last <Tuple <Type[], Action <FunctionContext>[], Type[]> >().Item1;
            Action <FunctionContext>[] actionArray = funcContext._traps.Last <Tuple <Type[], Action <FunctionContext>[], Type[]> >().Item2;
            if (innerException != null)
            {
                index = FindMatchingHandlerByType(innerException.GetType(), types);
                replaceParentContainsErrorRecordException = innerException;
            }
            if ((index == -1) || types[index].Equals(typeof(CatchAll)))
            {
                int num2 = FindMatchingHandlerByType(rte.GetType(), types);
                if (num2 != index)
                {
                    index = num2;
                    replaceParentContainsErrorRecordException = rte;
                }
            }
            if (index != -1)
            {
                try
                {
                    ErrorRecord      errorRecord = rte.ErrorRecord;
                    ExecutionContext context     = funcContext._executionContext;
                    if (context.CurrentCommandProcessor != null)
                    {
                        context.CurrentCommandProcessor.ForgetScriptException();
                    }
                    try
                    {
                        MutableTuple tuple = MutableTuple.MakeTuple(funcContext._traps.Last <Tuple <Type[], Action <FunctionContext>[], Type[]> >().Item3[index], Compiler.DottedLocalsNameIndexMap);
                        tuple.SetAutomaticVariable(AutomaticVariable.Underbar, new ErrorRecord(errorRecord, replaceParentContainsErrorRecordException), context);
                        for (int i = 1; i < 9; i++)
                        {
                            tuple.SetValue(i, funcContext._localsTuple.GetValue(i));
                        }
                        SessionStateScope scope = context.EngineSessionState.NewScope(false);
                        context.EngineSessionState.CurrentScope = scope;
                        scope.LocalsTuple = tuple;
                        FunctionContext context2 = new FunctionContext {
                            _scriptBlock      = funcContext._scriptBlock,
                            _sequencePoints   = funcContext._sequencePoints,
                            _executionContext = funcContext._executionContext,
                            _boundBreakpoints = funcContext._boundBreakpoints,
                            _outputPipe       = funcContext._outputPipe,
                            _breakPoints      = funcContext._breakPoints,
                            _localsTuple      = tuple
                        };
                        actionArray[index](context2);
                    }
                    catch (TargetInvocationException exception3)
                    {
                        throw exception3.InnerException;
                    }
                    finally
                    {
                        context.EngineSessionState.RemoveScope(context.EngineSessionState.CurrentScope);
                    }
                    return(QueryForAction(rte, replaceParentContainsErrorRecordException.Message, context));
                }
                catch (ContinueException)
                {
                    return(ActionPreference.SilentlyContinue);
                }
                catch (BreakException)
                {
                    return(ActionPreference.Stop);
                }
            }
            return(ActionPreference.Stop);
        }
Example #30
0
        private static UsingResult GetUsingValueFromTuple(MutableTuple tuple, string usingExpressionKey, int index)
        {
            var boundParameters =
                tuple.GetAutomaticVariable(AutomaticVariable.PSBoundParameters) as PSBoundParametersDictionary;
            if (boundParameters != null)
            {
                var implicitUsingParameters = boundParameters.ImplicitUsingParameters;
                if (implicitUsingParameters != null)
                {
                    if (implicitUsingParameters.Contains(usingExpressionKey))
                    {
                        return new UsingResult { Value = implicitUsingParameters[usingExpressionKey] };
                    }
                    else if (implicitUsingParameters.Contains(index))
                    {
                        // Handle downlevel (V4) using variables by using index to look up using value.
                        return new UsingResult { Value = implicitUsingParameters[index] };
                    }
                }
            }

            return null;
        }
 public LocalVariable(string name, MutableTuple tuple, int tupleSlot)
     : base(name, false)
 {
     _tuple     = tuple;
     _tupleSlot = tupleSlot;
 }
Example #32
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);
        }
Example #33
0
 internal static object[] BindArgumentsForScripblockInvoke(RuntimeDefinedParameter[] parameters, object[] args, ExecutionContext context, bool dotting, Dictionary<string, PSVariable> backupWhenDotting, MutableTuple locals)
 {
     object value;
     CommandLineParameters commandLineParameter = new CommandLineParameters();
     if ((int)parameters.Length != 0)
     {
         for (int i = 0; i < (int)parameters.Length; i++)
         {
             RuntimeDefinedParameter variableAtScope = parameters[i];
             bool flag = false;
             if (i < (int)args.Length)
             {
                 value = args[i];
             }
             else
             {
                 value = variableAtScope.Value;
                 if (value as Compiler.DefaultValueExpressionWrapper != null)
                 {
                     value = ((Compiler.DefaultValueExpressionWrapper)value).GetValue(context, null, null);
                 }
                 flag = true;
             }
             bool flag1 = false;
             if (!dotting || backupWhenDotting == null)
             {
                 flag1 = locals.TrySetParameter(variableAtScope.Name, value);
             }
             else
             {
                 backupWhenDotting[variableAtScope.Name] = context.EngineSessionState.GetVariableAtScope(variableAtScope.Name, "local");
             }
             if (!flag1)
             {
                 PSVariable pSVariable = new PSVariable(variableAtScope.Name, value, ScopedItemOptions.None, variableAtScope.Attributes);
                 context.EngineSessionState.SetVariable(pSVariable, false, CommandOrigin.Internal);
             }
             if (!flag)
             {
                 commandLineParameter.Add(variableAtScope.Name, value);
                 commandLineParameter.MarkAsBoundPositionally(variableAtScope.Name);
             }
         }
         locals.SetAutomaticVariable(AutomaticVariable.PSBoundParameters, commandLineParameter.GetValueToBindToPSBoundParameters(), context);
         int length = (int)args.Length - (int)parameters.Length;
         if (length > 0)
         {
             object[] objArray = new object[length];
             Array.Copy(args, (int)parameters.Length, objArray, 0, (int)objArray.Length);
             return objArray;
         }
         else
         {
             return ScriptBlock.EmptyArray;
         }
     }
     else
     {
         return args;
     }
 }
Example #34
0
 private void Init()
 {
     _scriptBlock = base._scriptBlock;
     _obsoleteAttribute = _scriptBlock.ObsoleteAttribute;
     _runOptimizedCode = _scriptBlock.Compile(optimized: _context._debuggingMode > 0 ? false : UseLocalScope);
     _localsTuple = _scriptBlock.MakeLocalsTuple(_runOptimizedCode);
 }
Example #35
0
 public LocalVariable(string name, MutableTuple tuple, int tupleSlot)
     : base(name, false)
 {
     _tuple = tuple;
     _tupleSlot = tupleSlot;
 }
Example #36
0
        internal static object[] BindArgumentsForScriptblockInvoke(
            RuntimeDefinedParameter[] parameters,
            object[] args,
            ExecutionContext context,
            bool dotting,
            Dictionary<string, PSVariable> backupWhenDotting,
            MutableTuple locals)
        {
            var boundParameters = new CommandLineParameters();

            if (parameters.Length == 0)
            {
                return args;
            }

            for (int i = 0; i < parameters.Length; i++)
            {
                var parameter = parameters[i];
                object valueToBind;
                bool wasDefaulted = false;
                if (i >= args.Length)
                {
                    valueToBind = parameter.Value;
                    if (valueToBind is Compiler.DefaultValueExpressionWrapper)
                    {
                        // We pass in a null SessionStateInternal because the current scope is already set correctly.
                        valueToBind = ((Compiler.DefaultValueExpressionWrapper)valueToBind).GetValue(context, null);
                    }
                    wasDefaulted = true;
                }
                else
                {
                    valueToBind = args[i];
                }

                bool valueSet = false;
                if (dotting && backupWhenDotting != null)
                {
                    backupWhenDotting[parameter.Name] = context.EngineSessionState.GetVariableAtScope(parameter.Name, "local");
                }
                else
                {
                    valueSet = locals.TrySetParameter(parameter.Name, valueToBind);
                }

                if (!valueSet)
                {
                    var variable = new PSVariable(parameter.Name, valueToBind, ScopedItemOptions.None, parameter.Attributes);
                    context.EngineSessionState.SetVariable(variable, false, CommandOrigin.Internal);
                }

                if (!wasDefaulted)
                {
                    boundParameters.Add(parameter.Name, valueToBind);
                    boundParameters.MarkAsBoundPositionally(parameter.Name);
                }
            }

            locals.SetAutomaticVariable(AutomaticVariable.PSBoundParameters, boundParameters.GetValueToBindToPSBoundParameters(), context);

            var leftOverArgs = args.Length - parameters.Length;
            if (leftOverArgs <= 0)
            {
                return Utils.EmptyArray<object>();
            }

            object[] result = new object[leftOverArgs];
            Array.Copy(args, parameters.Length, result, 0, result.Length);
            return result;
        }
Example #37
0
 private void WriteToCurrentErrorPipe(bool createLocalScope, Pipe outputPipe, ref object[] args, ExecutionContext contextFromTLS, Action<FunctionContext> codeToInvoke, MutableTuple mutableTuple, PSLanguageMode? languageMode, ref Dictionary<string, PSVariable> strs)
 {
     if (!createLocalScope)
     {
         if (contextFromTLS.EngineSessionState.CurrentScope.LocalsTuple != null)
         {
             contextFromTLS.EngineSessionState.CurrentScope.DottedScopes.Push(mutableTuple);
             strs = new Dictionary<string, PSVariable>();
         }
         else
         {
             contextFromTLS.EngineSessionState.CurrentScope.LocalsTuple = mutableTuple;
         }
     }
     else
     {
         SessionStateScope sessionStateScope = contextFromTLS.EngineSessionState.NewScope(false);
         contextFromTLS.EngineSessionState.CurrentScope = sessionStateScope;
         sessionStateScope.LocalsTuple = mutableTuple;
     }
     if (languageMode.HasValue)
     {
         contextFromTLS.LanguageMode = languageMode.Value;
     }
     args = ScriptBlock.BindArgumentsForScripblockInvoke((RuntimeDefinedParameter[])this.RuntimeDefinedParameters.Data, args, contextFromTLS, !createLocalScope, strs, mutableTuple);
     mutableTuple.SetAutomaticVariable(AutomaticVariable.Args, args, contextFromTLS);
     contextFromTLS.EngineSessionState.CurrentScope.ScopeOrigin = CommandOrigin.Internal;
     FunctionContext functionContext = new FunctionContext();
     functionContext._executionContext = contextFromTLS;
     functionContext._outputPipe = outputPipe;
     functionContext._localsTuple = mutableTuple;
     functionContext._scriptBlock = this;
     functionContext._sequencePoints = this.SequencePoints;
     FunctionContext functionContext1 = functionContext;
     codeToInvoke(functionContext1);
 }
Example #38
0
 public static object[] GetTupleValues(MutableTuple tuple)
 {
     List<object> args = new List<object>();
     GetTupleValues(tuple, args);
     return args.ToArray();
 }
Example #39
0
        internal static PowerShell Convert(ScriptBlockAst body,
                                           ReadOnlyCollection <ParameterAst> functionParameters,
                                           bool isTrustedInput,
                                           ExecutionContext context,
                                           Dictionary <string, object> variables,
                                           bool filterNonUsingVariables,
                                           bool?createLocalScope,
                                           object[] args)
        {
            ExecutionContext.CheckStackDepth();

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

            // Perform validations on the ScriptBlock.  GetSimplePipeline can allow for more than one
            // pipeline if the first parameter is true, but Invoke-Command doesn't yet support multiple
            // pipelines in a PowerShell (it just grabs the last command directly.)  The rest of this
            // code properly supports multiple pipelines, so it should just work to change the false to true
            // if/when Invoke-Command can support multiple pipelines.
            string errorId;
            string errorMsg;

            body.GetSimplePipeline(true, out errorId, out errorMsg);
            if (errorId != null)
            {
                throw new ScriptBlockToPowerShellNotSupportedException(errorId, null, errorMsg);
            }

            var checker = new ScriptBlockToPowerShellChecker {
                ScriptBeingConverted = body
            };

            if (functionParameters != null)
            {
                foreach (var parameter in functionParameters)
                {
                    parameter.InternalVisit(checker);
                }
            }

            body.InternalVisit(checker);

            // When the context is null (or they haven't supplied any variables), throw, but only if we really need the
            // context (basically, if we have some variable reference to resolve).
            if (context == null && (checker.HasUsingExpr || checker.UsesParameter) && (variables == null))
            {
                throw new PSInvalidOperationException(AutomationExceptions.CantConvertScriptBlockWithNoContext);
            }

            try
            {
                var converter = new ScriptBlockToPowerShellConverter {
                    _context = context, _createLocalScope = createLocalScope
                };

                if (checker.HasUsingExpr)
                {
                    converter._usingValueMap = GetUsingValues(body, isTrustedInput, context, variables, filterNonUsingVariables).Item1;
                }

                if (checker.UsesParameter)
                {
                    // If any parameters are used, we create a new scope and bind the parameters.

                    var newScope = context.EngineSessionState.NewScope(false);
                    context.EngineSessionState.CurrentScope             = newScope;
                    context.EngineSessionState.CurrentScope.ScopeOrigin = CommandOrigin.Internal;

                    var locals =
                        MutableTuple.MakeTuple(Compiler.DottedLocalsTupleType, Compiler.DottedLocalsNameIndexMap);

                    // Get the parameter metadata for the script block.
                    // If 'functionParameters' is not null, then the ScriptBlockAst is actually the body of a FunctionDefinitionAst, and it doesn't have a ParamBlock.
                    // If 'functionParameters' is null, then the ScriptBlockAst may have parameters defined in its ParamBlock.
                    bool usesCmdletBinding = false;
                    var  parameters        = functionParameters != null
                                         ? Compiler.GetParameterMetaData(functionParameters, true, ref usesCmdletBinding)
                                         : ((IParameterMetadataProvider)body).GetParameterMetadata(true, ref usesCmdletBinding);

                    object[] remainingArgs = ScriptBlock.BindArgumentsForScriptblockInvoke(
                        (RuntimeDefinedParameter[])parameters.Data, args, context, false, null, locals);
                    locals.SetAutomaticVariable(AutomaticVariable.Args, remainingArgs, context);
                    newScope.LocalsTuple = locals;
                }

                foreach (var pipeline in body.EndBlock.Statements.OfType <PipelineAst>())
                {
                    converter._powershell.AddStatement();
                    converter.ConvertPipeline(pipeline, isTrustedInput);
                }

                return(converter._powershell);
            }
            finally
            {
                if (checker.UsesParameter)
                {
                    context.EngineSessionState.RemoveScope(context.EngineSessionState.CurrentScope);
                }
            }
        }
Example #40
0
 internal void SetPSScriptRootAndPSCommandPath(MutableTuple locals, ExecutionContext context)
 {
     string empty = string.Empty;
     string file = string.Empty;
     if (!string.IsNullOrEmpty(this.File))
     {
         empty = Path.GetDirectoryName(this.File);
         file = this.File;
     }
     locals.SetAutomaticVariable(AutomaticVariable.PSScriptRoot, empty, context);
     locals.SetAutomaticVariable(AutomaticVariable.PSCommandPath, file, context);
 }