コード例 #1
0
 /// <summary>
 /// Add a parameter to the command invocation.
 /// It needs to be called before any execution takes place.
 /// </summary>
 /// <param name="parameterName">Name of the parameter.</param>
 /// <param name="parameterValue">Value of the parameter.</param>
 internal void AddNamedParameter(string parameterName, object parameterValue)
 {
     _commandParameterList.Add(
         CommandParameterInternal.CreateParameterWithArgument(
             /*parameterAst*/ null, parameterName, null,
             /*argumentAst*/ null, parameterValue,
             false));
 }
コード例 #2
0
 /// <summary>
 /// add a parameter to the command invocation.
 /// It needs to be called before any execution takes place
 /// </summary>
 /// <param name="parameterName">name of the parameter</param>
 /// <param name="parameterValue">value of the parameter</param>
 internal void AddNamedParameter(string parameterName, object parameterValue)
 {
     _commandParameterList.Add(
         CommandParameterInternal.CreateParameterWithArgument(
             PositionUtilities.EmptyExtent, parameterName, null,
             PositionUtilities.EmptyExtent, parameterValue,
             false));
 }
        /// <summary>
        /// Passes the binding directly through to the parameter binder.
        /// It does no verification against metadata.
        /// </summary>
        /// <param name="argument">
        /// The name and value of the variable to bind.
        /// </param>
        /// <param name="flags">
        /// Ignored.
        /// </param>
        /// <returns>
        /// True if the parameter was successfully bound. Any error condition
        /// produces an exception.
        /// </returns>
        internal override bool BindParameter(
            CommandParameterInternal argument,
            ParameterBindingFlags flags)
        {
            Diagnostics.Assert(false, "Unreachable code");

            throw new InvalidOperationException();
        }
コード例 #4
0
        internal static CommandParameter FromCommandParameterInternal(
            CommandParameterInternal internalParameter)
        {
            if (internalParameter == null)
            {
                throw CommandParameter._trace.NewArgumentNullException(nameof(internalParameter));
            }
            string name = (string)null;

            if (internalParameter.Name != null)
            {
                name = internalParameter.Token == null ? internalParameter.Name : (!internalParameter.Token.FollowedBySpace ? internalParameter.Token.ToString() : internalParameter.Token.ToString() + " ");
            }
            if (internalParameter.IsValidPair)
            {
                object obj = internalParameter.Value2;
                return(new CommandParameter(name, obj));
            }
            return(name != null ? new CommandParameter(name) : new CommandParameter((string)null, internalParameter.Value1));
        }
コード例 #5
0
        internal static CommandParameterInternal ToCommandParameterInternal(CommandParameter publicParameter, bool forNativeCommand)
        {
            string str2;

            if (publicParameter == null)
            {
                throw PSTraceSource.NewArgumentNullException("publicParameter");
            }
            string name = publicParameter.Name;
            object obj2 = publicParameter.Value;

            if (name == null)
            {
                return(CommandParameterInternal.CreateArgument(PositionUtilities.EmptyExtent, obj2, false));
            }
            if (!name[0].IsDash())
            {
                str2 = forNativeCommand ? name : ("-" + name);
                return(CommandParameterInternal.CreateParameterWithArgument(PositionUtilities.EmptyExtent, name, str2, PositionUtilities.EmptyExtent, obj2, true));
            }
            bool spaceAfterParameter = false;
            int  length = name.Length;

            while ((length > 0) && char.IsWhiteSpace(name[length - 1]))
            {
                spaceAfterParameter = true;
                length--;
            }
            str2 = name.Substring(0, length);
            bool   flag2         = name[length - 1] == ':';
            string parameterName = str2.Substring(1, str2.Length - (flag2 ? 2 : 1));

            if (!flag2 && (obj2 == null))
            {
                return(CommandParameterInternal.CreateParameter(PositionUtilities.EmptyExtent, parameterName, str2));
            }
            return(CommandParameterInternal.CreateParameterWithArgument(PositionUtilities.EmptyExtent, parameterName, str2, PositionUtilities.EmptyExtent, obj2, spaceAfterParameter));
        }
コード例 #6
0
ファイル: Command.cs プロジェクト: whatevergeek/poshvx
        CreateCommandProcessor
        (
            ExecutionContext executionContext,
            CommandFactory commandFactory,
            bool addToHistory,
            CommandOrigin origin
        )
        {
            Dbg.Assert(executionContext != null, "Caller should verify the parameters");
            Dbg.Assert(commandFactory != null, "Caller should verify the parameters");


            CommandProcessorBase commandProcessorBase;

            if (IsScript)
            {
                if ((executionContext.LanguageMode == PSLanguageMode.NoLanguage) &&
                    (origin == Automation.CommandOrigin.Runspace))
                {
                    throw InterpreterError.NewInterpreterException(CommandText, typeof(ParseException),
                                                                   null, "ScriptsNotAllowed", ParserStrings.ScriptsNotAllowed);
                }

                ScriptBlock scriptBlock = executionContext.Engine.ParseScriptBlock(CommandText, addToHistory);
                if (origin == Automation.CommandOrigin.Internal)
                {
                    scriptBlock.LanguageMode = PSLanguageMode.FullLanguage;
                }

                // If running in restricted language mode, verify that the parse tree represents on legitimate
                // constructions...
                switch (scriptBlock.LanguageMode)
                {
                case PSLanguageMode.RestrictedLanguage:
                    scriptBlock.CheckRestrictedLanguage(null, null, false);
                    break;

                case PSLanguageMode.FullLanguage:
                    // Interactive script commands are permitted in this mode.
                    break;

                case PSLanguageMode.ConstrainedLanguage:
                    // Constrained Language is checked at runtime.
                    break;

                default:
                    // This should never happen...
                    Diagnostics.Assert(false, "Invalid langage mode was set when building a ScriptCommandProcessor");
                    throw new InvalidOperationException("Invalid langage mode was set when building a ScriptCommandProcessor");
                }

                if (scriptBlock.UsesCmdletBinding)
                {
                    FunctionInfo functionInfo = new FunctionInfo("", scriptBlock, executionContext);
                    commandProcessorBase = new CommandProcessor(functionInfo, executionContext,
                                                                _useLocalScope ?? false, fromScriptFile: false, sessionState: executionContext.EngineSessionState);
                }
                else
                {
                    commandProcessorBase = new DlrScriptCommandProcessor(scriptBlock,
                                                                         executionContext, _useLocalScope ?? false,
                                                                         origin,
                                                                         executionContext.EngineSessionState);
                }
            }
            else
            {
                // RestrictedLanguage / NoLanguage do not support dot-sourcing when CommandOrigin is Runspace
                if ((_useLocalScope.HasValue) && (!_useLocalScope.Value))
                {
                    switch (executionContext.LanguageMode)
                    {
                    case PSLanguageMode.RestrictedLanguage:
                    case PSLanguageMode.NoLanguage:
                        string message = StringUtil.Format(RunspaceStrings.UseLocalScopeNotAllowed,
                                                           "UseLocalScope",
                                                           PSLanguageMode.RestrictedLanguage.ToString(),
                                                           PSLanguageMode.NoLanguage.ToString());
                        throw new RuntimeException(message);

                    case PSLanguageMode.FullLanguage:
                        // Interactive script commands are permitted in this mode...
                        break;
                    }
                }

                commandProcessorBase =
                    commandFactory.CreateCommand(CommandText, origin, _useLocalScope);
            }

            CommandParameterCollection parameters = Parameters;

            if (parameters != null)
            {
                bool isNativeCommand = commandProcessorBase is NativeCommandProcessor;
                foreach (CommandParameter publicParameter in parameters)
                {
                    CommandParameterInternal internalParameter = CommandParameter.ToCommandParameterInternal(publicParameter, isNativeCommand);
                    commandProcessorBase.AddParameter(internalParameter);
                }
            }

            string       helpTarget;
            HelpCategory helpCategory;

            if (commandProcessorBase.IsHelpRequested(out helpTarget, out helpCategory))
            {
                commandProcessorBase = CommandProcessorBase.CreateGetHelpCommandProcessor(
                    executionContext,
                    helpTarget,
                    helpCategory);
            }

            //Set the merge settings
            SetMergeSettingsOnCommandProcessor(commandProcessorBase);

            return(commandProcessorBase);
        }
コード例 #7
0
        /// <summary>
        /// Binds the specified parameters to the native command.
        /// </summary>
        /// <param name="parameters">
        /// The parameters to bind.
        /// </param>
        /// <param name="outputRedirected">
        /// true if minishell output is redirected.
        /// </param>
        /// <param name="hostName">
        /// name of the calling host.
        /// </param>
        /// <remarks>
        /// For any parameters that do not have a name, they are added to the command
        /// line arguments for the command
        /// </remarks>
        internal Collection<CommandParameterInternal> BindParameters(Collection<CommandParameterInternal> parameters, bool outputRedirected, string hostName)
        {
            MinishellParameters seen = 0;
            string inputFormat = null;
            string outputFormat = null;
            for (int i = 0; i < parameters.Count; i++)
            {
                var parameter = parameters[i];

                if (parameter.ParameterNameSpecified)
                {
                    var parameterName = parameter.ParameterName;

                    if (CommandParameter.StartsWith(parameterName, StringComparison.OrdinalIgnoreCase))
                    {
                        HandleSeenParameter(ref seen, MinishellParameters.Command, CommandParameter);

                        // Value must be specified for -Command parameter.
                        if (i + 1 >= parameters.Count)
                        {
                            throw NewParameterBindingException(null, ErrorCategory.InvalidArgument, CommandParameter,
                                                               typeof(ScriptBlock), null,
                                                               NativeCP.NoValueForCommandParameter,
                                                               "NoValueForCommandParameter");
                        }

                        i += 1;

                        // Value of -Command parameter must be scriptblock
                        var scriptBlockArgument = parameters[i];
                        var argumentValue = PSObject.Base(scriptBlockArgument.ArgumentValue);
                        if (!scriptBlockArgument.ArgumentSpecified || argumentValue is not ScriptBlock)
                        {
                            throw NewParameterBindingException(null, ErrorCategory.InvalidArgument, CommandParameter,
                                                               typeof(ScriptBlock), argumentValue.GetType(),
                                                               NativeCP.IncorrectValueForCommandParameter,
                                                               "IncorrectValueForCommandParameter");
                        }

                        // Replace the parameters with -EncodedCommand <base64 encoded scriptblock>
                        parameters[i - 1] = CommandParameterInternal.CreateParameter(EncodedCommandParameter, "-" + EncodedCommandParameter, parameter.ParameterAst);
                        string encodedScript = StringToBase64Converter.StringToBase64String(argumentValue.ToString());
                        parameters[i] = CommandParameterInternal.CreateArgument(encodedScript, scriptBlockArgument.ArgumentAst);
                    }
                    else if (InputFormatParameter.StartsWith(parameterName, StringComparison.OrdinalIgnoreCase))
                    {
                        HandleSeenParameter(ref seen, MinishellParameters.InputFormat, InputFormatParameter);

                        // Value for -Inputformat must be specified
                        if (i + 1 >= parameters.Count)
                        {
                            throw NewParameterBindingException(null, ErrorCategory.InvalidArgument, InputFormatParameter,
                                                               typeof(string), null,
                                                               NativeCP.NoValueForInputFormatParameter,
                                                               "NoValueForInputFormatParameter");
                        }

                        // Update the argument (partial arguments are allowed)
                        i += 1;
                        var inputFormatArg = parameters[i];
                        inputFormat = ProcessFormatParameterValue(InputFormatParameter, inputFormatArg.ArgumentValue);
                        parameters[i - 1] = CommandParameterInternal.CreateParameter(InputFormatParameter, "-" + InputFormatParameter, parameter.ParameterAst);
                        parameters[i] = CommandParameterInternal.CreateArgument(inputFormat, inputFormatArg.ArgumentAst);
                    }
                    else if (OutputFormatParameter.StartsWith(parameterName, StringComparison.OrdinalIgnoreCase))
                    {
                        HandleSeenParameter(ref seen, MinishellParameters.OutputFormat, OutputFormatParameter);

                        // Value for -Inputformat must be specified
                        if (i + 1 >= parameters.Count)
                        {
                            throw NewParameterBindingException(null, ErrorCategory.InvalidArgument, OutputFormatParameter,
                                                               typeof(string), null,
                                                               NativeCP.NoValueForOutputFormatParameter,
                                                               "NoValueForInputFormatParameter");
                        }

                        // Update the argument (partial arguments are allowed)
                        i += 1;
                        var outputFormatArg = parameters[i];
                        outputFormat = ProcessFormatParameterValue(OutputFormatParameter, outputFormatArg.ArgumentValue);
                        parameters[i - 1] = CommandParameterInternal.CreateParameter(OutputFormatParameter, "-" + OutputFormatParameter, parameter.ParameterAst);
                        parameters[i] = CommandParameterInternal.CreateArgument(outputFormat, outputFormatArg.ArgumentAst);
                    }
                    else if (ArgsParameter.StartsWith(parameterName, StringComparison.OrdinalIgnoreCase))
                    {
                        HandleSeenParameter(ref seen, MinishellParameters.Arguments, ArgsParameter);

                        // Value for -Args parameter must be specified
                        if (i + 1 >= parameters.Count)
                        {
                            throw NewParameterBindingException(null, ErrorCategory.InvalidArgument, ArgsParameter,
                                                               typeof(string), null, NativeCP.NoValuesSpecifiedForArgs,
                                                               "NoValuesSpecifiedForArgs");
                        }

                        // Get the encoded value for -args parameter
                        i += 1;
                        var argsArg = parameters[i];
                        var encodedArgs = ConvertArgsValueToEncodedString(argsArg.ArgumentValue);
                        parameters[i - 1] = CommandParameterInternal.CreateParameter(EncodedArgsParameter, "-" + EncodedArgsParameter, parameter.ParameterAst);
                        // NOTE: do not pass the ArgumentAst; it will fail validation in BindParameters if there
                        // are multiple arguments (array) but encodedArgs is an encoded string.
                        parameters[i] = CommandParameterInternal.CreateArgument(encodedArgs);
                    }
                }
                else
                {
                    // -Command is positional parameter. Bind first scriptblock to it, others are errors.
                    var scriptBlockArgument = parameters[i];
                    var argumentValue = PSObject.Base(scriptBlockArgument.ArgumentValue);
                    if (argumentValue is ScriptBlock)
                    {
                        HandleSeenParameter(ref seen, MinishellParameters.Command, CommandParameter);

                        // Replace the argument with -EncodedCommand <base64 encoded scriptblock>
                        string encodedScript = StringToBase64Converter.StringToBase64String(argumentValue.ToString());
                        parameters[i] = CommandParameterInternal.CreateParameterWithArgument(
                            parameter.ArgumentAst, EncodedCommandParameter, "-" + EncodedCommandParameter,
                            parameter.ArgumentAst, encodedScript,
                            spaceAfterParameter: true);
                    }
                }
            }

            // Add InputFormat and OutputFormat parameter if not specified
            if (inputFormat == null)
            {
                // For minishell default input format is xml
                parameters.Add(CommandParameterInternal.CreateParameter(InputFormatParameter, "-" + InputFormatParameter));
                parameters.Add(CommandParameterInternal.CreateArgument(XmlFormatValue));
                inputFormat = XmlFormatValue;
            }

            if (outputFormat == null)
            {
                // If output is redirected, output format should be xml
                outputFormat = outputRedirected ? XmlFormatValue : TextFormatValue;
                parameters.Add(CommandParameterInternal.CreateParameter(OutputFormatParameter, "-" + OutputFormatParameter));
                parameters.Add(CommandParameterInternal.CreateArgument(outputFormat));
            }

            // Set the output and input format class variable
            InputFormat = XmlFormatValue.StartsWith(inputFormat, StringComparison.OrdinalIgnoreCase)
                ? NativeCommandIOFormat.Xml
                : NativeCommandIOFormat.Text;
            OutputFormat = XmlFormatValue.StartsWith(outputFormat, StringComparison.OrdinalIgnoreCase)
                ? NativeCommandIOFormat.Xml
                : NativeCommandIOFormat.Text;

            // Note if a minishell is invoked from a non-console host, we need to
            // pass -nonInteractive flag. Our console host's name is "ConsoleHost".
            // Correct check would be see if current host has access to console and
            // pass noninteractive flag if doesn't.
            if (string.IsNullOrEmpty(hostName) || !hostName.Equals("ConsoleHost", StringComparison.OrdinalIgnoreCase))
            {
                NonInteractive = true;
                parameters.Insert(0, CommandParameterInternal.CreateParameter(NonInteractiveParameter, "-" + NonInteractiveParameter));
            }

            ((NativeCommandParameterBinder)DefaultParameterBinder).BindParameters(parameters);

            Diagnostics.Assert(s_emptyReturnCollection.Count == 0, "This list shouldn't be used for anything as it's shared.");

            return s_emptyReturnCollection;
        }
コード例 #8
0
ファイル: Parameter.cs プロジェクト: 5l1v3r1/PowerShell-7
        internal static CommandParameterInternal ToCommandParameterInternal(CommandParameter publicParameter, bool forNativeCommand)
        {
            if (publicParameter == null)
            {
                throw PSTraceSource.NewArgumentNullException(nameof(publicParameter));
            }

            string name  = publicParameter.Name;
            object value = publicParameter.Value;

            Debug.Assert((name == null) || (name.Trim().Length != 0), "Parameter name has to null or have some non-whitespace characters in it");

            if (name == null)
            {
                return(CommandParameterInternal.CreateArgument(value));
            }

            string parameterText;

            if (!name[0].IsDash())
            {
                parameterText = forNativeCommand ? name : "-" + name;
                return(CommandParameterInternal.CreateParameterWithArgument(
                           /*parameterAst*/ null, name, parameterText,
                           /*argumentAst*/ null, value,
                           true));
            }

            // if first character of name is '-', then we try to fake the original token
            // reconstructing dashes, colons and followed-by-space information

            // find the last non-whitespace character
            bool spaceAfterParameter = false;
            int  endPosition         = name.Length;

            while ((endPosition > 0) && char.IsWhiteSpace(name[endPosition - 1]))
            {
                spaceAfterParameter = true;
                endPosition--;
            }

            Debug.Assert(endPosition > 0, "parameter name should have some non-whitespace characters in it");

            // now make sure that parameterText doesn't have whitespace at the end,
            parameterText = name.Substring(0, endPosition);

            // parameterName should contain only the actual name of the parameter (no whitespace, colons, dashes)
            bool hasColon      = (name[endPosition - 1] == ':');
            var  parameterName = parameterText.Substring(1, parameterText.Length - (hasColon ? 2 : 1));

            // At this point we have rebuilt the token.  There are 3 strings that might be different:
            //           name = nameToken.Script = "-foo: " <- needed to fake FollowedBySpace=true (i.e. for "testecho.exe -a:b -c: d")
            // tokenString = nameToken.TokenText = "-foo:" <- needed to preserve full token text (i.e. for write-output)
            //                    nameToken.Data =  "foo" <- needed to preserve name of parameter so parameter binding works
            // Now we just need to use the token to build appropriate CommandParameterInternal object

            // is this a name+value pair, or is it just a name (of a parameter)?
            if (!hasColon && value == null)
            {
                // just a name
                return(CommandParameterInternal.CreateParameter(parameterName, parameterText));
            }

            // name+value pair
            return(CommandParameterInternal.CreateParameterWithArgument(
                       /*parameterAst*/ null, parameterName, parameterText,
                       /*argumentAst*/ null, value,
                       spaceAfterParameter));
        }
コード例 #9
0
        internal CommandProcessorBase CreateCommandProcessor(ExecutionContext executionContext, CommandFactory commandFactory, bool addToHistory, CommandOrigin origin)
        {
            CommandProcessorBase base2;
            string       str2;
            HelpCategory category;

            if (!this.IsScript)
            {
                if (this._useLocalScope.HasValue && !this._useLocalScope.Value)
                {
                    switch (executionContext.LanguageMode)
                    {
                    case PSLanguageMode.RestrictedLanguage:
                    case PSLanguageMode.NoLanguage:
                        throw new RuntimeException(StringUtil.Format(RunspaceStrings.UseLocalScopeNotAllowed, new object[] { "UseLocalScope", PSLanguageMode.RestrictedLanguage.ToString(), PSLanguageMode.NoLanguage.ToString() }));
                    }
                }
                base2 = commandFactory.CreateCommand(this.CommandText, origin, this._useLocalScope);
            }
            else
            {
                if (executionContext.LanguageMode == PSLanguageMode.NoLanguage)
                {
                    throw InterpreterError.NewInterpreterException(this.CommandText, typeof(ParseException), null, "ScriptsNotAllowed", ParserStrings.ScriptsNotAllowed, new object[0]);
                }
                ScriptBlock function = executionContext.Engine.ParseScriptBlock(this.CommandText, addToHistory);
                switch (executionContext.LanguageMode)
                {
                case PSLanguageMode.FullLanguage:
                case PSLanguageMode.ConstrainedLanguage:
                    break;

                case PSLanguageMode.RestrictedLanguage:
                    function.CheckRestrictedLanguage(null, null, false);
                    break;

                default:
                    throw new InvalidOperationException("Invalid langage mode was set when building a ScriptCommandProcessor");
                }
                if (function.UsesCmdletBinding)
                {
                    FunctionInfo scriptCommandInfo = new FunctionInfo("", function, executionContext);
                    bool?        nullable          = this._useLocalScope;
                    base2 = new CommandProcessor(scriptCommandInfo, executionContext, nullable.HasValue ? nullable.GetValueOrDefault() : false, false, executionContext.EngineSessionState);
                }
                else
                {
                    bool?nullable2 = this._useLocalScope;
                    base2 = new DlrScriptCommandProcessor(function, executionContext, nullable2.HasValue ? nullable2.GetValueOrDefault() : false, CommandOrigin.Runspace, executionContext.EngineSessionState);
                }
            }
            CommandParameterCollection parameters = this.Parameters;

            if (parameters != null)
            {
                bool forNativeCommand = base2 is NativeCommandProcessor;
                foreach (CommandParameter parameter in parameters)
                {
                    CommandParameterInternal internal2 = CommandParameter.ToCommandParameterInternal(parameter, forNativeCommand);
                    base2.AddParameter(internal2);
                }
            }
            if (base2.IsHelpRequested(out str2, out category))
            {
                base2 = CommandProcessorBase.CreateGetHelpCommandProcessor(executionContext, str2, category);
            }
            this.SetMergeSettingsOnCommandProcessor(base2);
            return(base2);
        }
コード例 #10
0
ファイル: LocalPipeline.cs プロジェクト: modulexcite/pash-1
        private PipelineProcessor CreatePipelineProcessor()
        {
            PipelineProcessor processor2;
            CommandCollection commands = base.Commands;

            if ((commands == null) || (commands.Count == 0))
            {
                throw PSTraceSource.NewInvalidOperationException("RunspaceStrings", "NoCommandInPipeline", new object[0]);
            }
            PipelineProcessor processor = new PipelineProcessor {
                TopLevel = true
            };
            bool flag = false;

            try
            {
                foreach (Command command in commands)
                {
                    CommandProcessorBase base2;
                    if (command.CommandInfo == null)
                    {
                        base2 = command.CreateCommandProcessor(this.LocalRunspace.ExecutionContext, this.LocalRunspace.CommandFactory, base.AddToHistory, this.IsNested ? CommandOrigin.Internal : CommandOrigin.Runspace);
                    }
                    else
                    {
                        CmdletInfo commandInfo = (CmdletInfo)command.CommandInfo;
                        base2 = new CommandProcessor(commandInfo, this.LocalRunspace.ExecutionContext);
                        PSSQMAPI.IncrementData(commandInfo.CommandType);
                        base2.Command.CommandOriginInternal       = CommandOrigin.Internal;
                        base2.Command.MyInvocation.InvocationName = commandInfo.Name;
                        if (command.Parameters != null)
                        {
                            foreach (CommandParameter parameter in command.Parameters)
                            {
                                CommandParameterInternal internal2 = CommandParameter.ToCommandParameterInternal(parameter, false);
                                base2.AddParameter(internal2);
                            }
                        }
                    }
                    base2.RedirectShellErrorOutputPipe = base.RedirectShellErrorOutputPipe;
                    processor.Add(base2);
                }
                processor2 = processor;
            }
            catch (RuntimeException)
            {
                flag = true;
                throw;
            }
            catch (Exception exception)
            {
                flag = true;
                CommandProcessorBase.CheckForSevereException(exception);
                throw new RuntimeException(PipelineStrings.CannotCreatePipeline, exception);
            }
            finally
            {
                if (flag)
                {
                    base.SetHadErrors(true);
                    processor.Dispose();
                }
            }
            return(processor2);
        }