private void InitializeScopeEnumerator()
        {
            // Define the lookup scope and if we have to do single
            // level or dynamic lookup based on the lookup variable

            _initialScope = sessionState.CurrentScope;

            if (_lookupPath.IsGlobal)
            {
                _initialScope        = sessionState.GlobalScope;
                _isSingleScopeLookup = true;
            }
            else if (_lookupPath.IsLocal ||
                     _lookupPath.IsPrivate)
            {
                _initialScope        = sessionState.CurrentScope;
                _isSingleScopeLookup = true;
            }
            else if (_lookupPath.IsScript)
            {
                _initialScope        = sessionState.ScriptScope;
                _isSingleScopeLookup = true;
            }

            _scopeEnumerable =
                new SessionStateScopeEnumerator(_initialScope);

            _isInitialized = true;
        }
        /// <summary>
        /// Derived classes override this method to return their
        /// particular type of scoped item.
        /// </summary>
        /// <param name="scope">
        /// The scope to look the item up in.
        /// </param>
        /// <param name="name">
        /// The name of the item to retrieve.
        /// </param>
        /// <param name="alias">
        /// The scope item that the derived class should return.
        /// </param>
        /// <returns>
        /// True if the scope item was found or false otherwise.
        /// </returns>
        protected override bool GetScopeItem(
            SessionStateScope scope,
            VariablePath name,
            out AliasInfo alias)
        {
            Diagnostics.Assert(name is not FunctionLookupPath,
                               "name was scanned incorrect if we get here and it is a FunctionLookupPath");

            bool result = true;

            alias = scope.GetAlias(name.QualifiedName);

            // If the alias is private and the lookup scope
            // isn't the current scope, claim that the alias
            // doesn't exist so that the lookup continues.

            if (alias == null ||
                ((alias.Options & ScopedItemOptions.Private) != 0 &&
                 scope != sessionState.CurrentScope))
            {
                result = false;
            }

            return(result);
        }
Exemple #3
0
        /// <summary>
        /// Gets an IEnumerable for the cmdlet table for a given scope.
        /// </summary>
        /// <param name="scopeID">
        /// A scope identifier that is either one of the "special" scopes like
        /// "global", "script", "local", or "private, or a numeric ID of a relative scope
        /// to the current scope.
        /// </param>
        /// <exception cref="ArgumentException">
        /// If <paramref name="scopeID"/> is less than zero, or not
        /// a number and not "script", "global", "local", or "private"
        /// </exception>
        /// <exception cref="ArgumentOutOfRangeException">
        /// If <paramref name="scopeID"/> is less than zero or greater than the number of currently
        /// active scopes.
        /// </exception>
        internal IDictionary <string, List <CmdletInfo> > GetCmdletTableAtScope(string scopeID)
        {
            Dictionary <string, List <CmdletInfo> > result =
                new Dictionary <string, List <CmdletInfo> >(StringComparer.OrdinalIgnoreCase);

            SessionStateScope scope = GetScopeByID(scopeID);

            foreach (KeyValuePair <string, List <CmdletInfo> > entry in scope.CmdletTable)
            {
                // Make sure the alias isn't private or if it is that the current
                // scope is the same scope the alias was retrieved from.
                List <CmdletInfo> toBeAdded = new List <CmdletInfo>();
                foreach (CmdletInfo cmdletInfo in entry.Value)
                {
                    if ((cmdletInfo.Options & ScopedItemOptions.Private) == 0 ||
                        scope == _currentScope)
                    {
                        toBeAdded.Add(cmdletInfo);
                    }
                }

                result.Add(entry.Key, toBeAdded);
            }

            return(result);
        }
Exemple #4
0
        /// <summary>
        /// Gets the value of the specified cmdlet from the cmdlet table.
        /// </summary>
        /// <param name="cmdletName">
        /// The name of the cmdlet value to retrieve.
        /// </param>
        /// <param name="scopeID">
        /// A scope identifier that is either one of the "special" scopes like
        /// "global", "script", "local", or "private, or a numeric ID of a relative scope
        /// to the current scope.
        /// </param>
        /// <returns>
        /// The CmdletInfo representing the cmdlet.
        /// </returns>
        /// <exception cref="ArgumentException">
        /// If <paramref name="scopeID"/> is less than zero, or not
        /// a number and not "script", "global", "local", or "private"
        /// </exception>
        /// <exception cref="ArgumentOutOfRangeException">
        /// If <paramref name="scopeID"/> is less than zero or greater than the number of currently
        /// active scopes.
        /// </exception>
        internal CmdletInfo GetCmdletAtScope(string cmdletName, string scopeID)
        {
            CmdletInfo result = null;

            if (string.IsNullOrEmpty(cmdletName))
            {
                return(null);
            }

            SessionStateScope scope = GetScopeByID(scopeID);

            result = scope.GetCmdlet(cmdletName);

            // Make sure the alias isn't private or if it is that the current
            // scope is the same scope the alias was retrieved from.

            if (result != null &&
                (result.Options & ScopedItemOptions.Private) != 0 &&
                scope != _currentScope)
            {
                result = null;
            }

            return(result);
        }
        /// <summary>
        /// Derived classes override this method to return their
        /// particular type of scoped item.
        /// </summary>
        /// <param name="scope">
        /// The scope to look the item up in.
        /// </param>
        /// <param name="name">
        /// The name of the item to retrieve.
        /// </param>
        /// <param name="variable">
        /// The scope item that the derived class should return.
        /// </param>
        /// <returns>
        /// True if the scope item was found or false otherwise.
        /// </returns>
        protected override bool GetScopeItem(
            SessionStateScope scope,
            VariablePath name,
            out PSVariable variable)
        {
            Diagnostics.Assert(name is not FunctionLookupPath,
                               "name was scanned incorrect if we get here and it is a FunctionLookupPath");

            bool result = true;

            variable = scope.GetVariable(name.QualifiedName, _origin);

            // If the variable is private and the lookup scope
            // isn't the current scope, claim that the variable
            // doesn't exist so that the lookup continues.

            if (variable == null ||
                (variable.IsPrivate &&
                 scope != sessionState.CurrentScope))
            {
                result = false;
            }

            return(result);
        }
Exemple #6
0
        public void QualifiedNameTest(string name, string specifier, string unqualifiedName)
        {
            var qualName = new SessionStateScope <PSVariable> .QualifiedName(name);

            Assert.AreEqual(specifier, qualName.ScopeSpecifier);
            Assert.AreEqual(unqualifiedName, qualName.UnqualifiedName);
        }
 internal void SetVariable(PSVariable variable, SessionStateScope varScope, int slot)
 {
     if (varScope != this._scope)
     {
         return;
     }
     this.variables[slot] = variable;
 }
        private bool TryGetNewScopeItem(
            SessionStateScope lookupScope,
            out T newCurrentItem)
        {
            bool result = GetScopeItem(
                lookupScope,
                _lookupPath,
                out newCurrentItem);

            return(result);
        }
        protected override bool GetScopeItem(
            SessionStateScope scope,
            ScopedItemLookupPath name,
            out PSVariable variable)
        {
            bool flag = true;

            variable = scope.GetVariable(name.LookupPath.ToString(), this._origin);
            if (variable == null || variable.IsPrivate && scope != this.sessionState.CurrentScope)
            {
                flag = false;
            }
            return(flag);
        }
        protected override bool GetScopeItem(
            SessionStateScope scope,
            ScopedItemLookupPath name,
            out PSDriveInfo drive)
        {
            bool flag = true;

            drive = scope.GetDrive(name.LookupPath.NamespaceID);
            if (drive == (PSDriveInfo)null)
            {
                flag = false;
            }
            return(flag);
        }
 internal ActivationRecord(int pipelineSlots, int variableSlots, SessionStateScope scope)
 {
     if (pipelineSlots < 0)
     {
         throw new ArgumentOutOfRangeException(nameof(pipelineSlots));
     }
     if (variableSlots < 0)
     {
         throw new ArgumentOutOfRangeException(nameof(variableSlots));
     }
     this.pipelineFailed = new bool[pipelineSlots];
     this.variables      = new PSVariable[variableSlots];
     this._scope         = scope;
 }
Exemple #12
0
        protected override bool GetScopeItem(
            SessionStateScope scope,
            ScopedItemLookupPath name,
            out AliasInfo alias)
        {
            bool flag = true;

            alias = scope.GetAlias(name.ToString());
            if (alias == null || (alias.Options & ScopedItemOptions.Private) != ScopedItemOptions.None && scope != this.sessionState.CurrentScope)
            {
                flag = false;
            }
            return(flag);
        }
Exemple #13
0
        private static Type ResolveTypeNameWorker(TypeName typeName,
                                                  SessionStateScope currentScope,
                                                  IEnumerable <Assembly> loadedAssemblies,
                                                  HashSet <Assembly> searchedAssemblies,
                                                  TypeResolutionState typeResolutionState,
                                                  bool onlySearchInGivenAssemblies,
                                                  bool reportAmbiguousException,
                                                  out Exception exception)
        {
            Type result;

            exception = null;

            if (!onlySearchInGivenAssemblies)
            {
                while (currentScope != null)
                {
                    result = currentScope.LookupType(typeName.Name);
                    if (result != null)
                    {
                        return(result);
                    }

                    currentScope = currentScope.Parent;
                }

                if (TypeAccelerators.builtinTypeAccelerators.TryGetValue(typeName.Name, out result))
                {
                    return(result);
                }
            }

            result = LookForTypeInAssemblies(typeName, loadedAssemblies, searchedAssemblies, typeResolutionState, reportAmbiguousException, out exception);
            if (exception != null)
            {
                // skip the rest of lookups, if exception reported.
                return(result);
            }

            if (!onlySearchInGivenAssemblies && result == null)
            {
                lock (TypeAccelerators.userTypeAccelerators)
                {
                    TypeAccelerators.userTypeAccelerators.TryGetValue(typeName.Name, out result);
                }
            }

            return(result);
        }
        /// <summary>
        /// Derived classes override this method to return their
        /// particular type of scoped item.
        /// </summary>
        /// <param name="scope">
        /// The scope to look the item up in.
        /// </param>
        /// <param name="path">
        /// The name of the item to retrieve.
        /// </param>
        /// <param name="script">
        /// The scope item that the derived class should return.
        /// </param>
        /// <returns>
        /// True if the scope item was found or false otherwise.
        /// </returns>
        protected override bool GetScopeItem(
            SessionStateScope scope,
            VariablePath path,
            out FunctionInfo script)
        {
            Diagnostics.Assert(path is FunctionLookupPath,
                               "name was scanned incorrect if we get here and it is not a FunctionLookupPath");

            bool result = true;

            _name = path.IsFunction ? path.UnqualifiedPath : path.QualifiedName;

            script = scope.GetFunction(_name);

            if (script != null)
            {
                bool       isPrivate;
                FilterInfo filterInfo = script as FilterInfo;
                if (filterInfo != null)
                {
                    isPrivate = (filterInfo.Options & ScopedItemOptions.Private) != 0;
                }
                else
                {
                    isPrivate = (script.Options & ScopedItemOptions.Private) != 0;
                }

                // If the function is private and the lookup scope
                // isn't the current scope, claim that the function
                // doesn't exist so that the lookup continues.

                if (isPrivate &&
                    scope != sessionState.CurrentScope)
                {
                    result = false;
                }
                else
                {
                    // Now check the visibility of the variable...
                    SessionState.ThrowIfNotVisible(_origin, script);
                }
            }
            else
            {
                result = false;
            }

            return(result);
        }
Exemple #15
0
        /// <summary>
        /// Creates a new scope in the scope tree and assigns the parent
        /// and child scopes appropriately.
        /// </summary>
        /// <param name="isScriptScope">
        /// If true, the new scope is pushed on to the script scope stack and
        /// can be referenced using $script:
        /// </param>
        /// <returns>
        /// A new SessionStateScope which is a child of the current scope.
        /// </returns>
        internal SessionStateScope NewScope(bool isScriptScope)
        {
            Diagnostics.Assert(
                _currentScope != null,
                "The currentScope should always be set.");

            // Create the new child scope.

            SessionStateScope newScope = new SessionStateScope(_currentScope);

            if (isScriptScope)
            {
                newScope.ScriptScope = newScope;
            }

            return(newScope);
        }
Exemple #16
0
 private void Dispose(bool disposing)
 {
     if (!this.disposed)
     {
         if (disposing)
         {
             this.DisposeCommands();
             this.localPipeline         = null;
             this.externalSuccessOutput = null;
             this.externalErrorOutput   = null;
             this.executionScope        = null;
             this.SecurityContext.Dispose();
             this.SecurityContext = null;
             this.logBuffer       = null;
         }
         this.disposed = true;
     }
 }
        /// <summary>
        /// Derived classes override this method to return their
        /// particular type of scoped item.
        /// </summary>
        /// <param name="scope">
        /// The scope to look the item up in.
        /// </param>
        /// <param name="name">
        /// The name of the item to retrieve.
        /// </param>
        /// <param name="drive">
        /// The scope item that the derived class should return.
        /// </param>
        /// <returns>
        /// True if the scope item was found or false otherwise.
        /// </returns>
        protected override bool GetScopeItem(
            SessionStateScope scope,
            VariablePath name,
            out PSDriveInfo drive)
        {
            Diagnostics.Assert(name is not FunctionLookupPath,
                               "name was scanned incorrect if we get here and it is a FunctionLookupPath");

            bool result = true;

            drive = scope.GetDrive(name.DriveName);

            if (drive == null)
            {
                result = false;
            }

            return(result);
        }
Exemple #18
0
        private void Dispose(bool disposing)
        {
            if (_disposed)
                return;

            if (disposing)
            {
                DisposeCommands();
                _localPipeline = null;
                _externalSuccessOutput = null;
                _externalErrorOutput = null;
                _executionScope = null;
                _eventLogBuffer = null;
#if !CORECLR // Impersonation Not Supported On CSS
                SecurityContext.Dispose();
                SecurityContext = null;
#endif
            }

            _disposed = true;
        }
Exemple #19
0
        /// <summary>
        /// Given a scope ID, walks the scope list to the appropriate scope and returns it.
        /// </summary>
        /// <param name="scopeID">
        /// The numeric indexer to the scope relative to the current scope.
        /// </param>
        /// <returns>
        /// The scope at the index specified.  The index is relative to the current
        /// scope.
        /// </returns>
        /// <exception cref="ArgumentOutOfRangeException">
        /// If <paramref name="scopeID"/> is less than zero or greater than the number of currently
        /// active scopes.
        /// </exception>
        internal SessionStateScope GetScopeByID(int scopeID)
        {
            SessionStateScope processingScope = _currentScope;
            int originalID = scopeID;

            while (scopeID > 0 && processingScope != null)
            {
                processingScope = processingScope.Parent;
                scopeID--;
            }

            if (processingScope == null && scopeID >= 0)
            {
                ArgumentOutOfRangeException outOfRange =
                    PSTraceSource.NewArgumentOutOfRangeException(
                        ScopeParameterName,
                        originalID,
                        SessionStateStrings.ScopeIDExceedsAvailableScopes,
                        originalID);
                throw outOfRange;
            }

            return(processingScope);
        }
Exemple #20
0
        protected override bool GetScopeItem(
            SessionStateScope scope,
            ScopedItemLookupPath path,
            out FunctionInfo script)
        {
            bool flag = true;

            this.name = path.ToString();
            if (path.IsScopedItem)
            {
                this.name = path.LookupPath.NamespaceSpecificString;
            }
            script = scope.GetFunction(this.name);
            if (script != null)
            {
                if ((!(script is FilterInfo filterInfo) ? (script.Options & ScopedItemOptions.Private) != ScopedItemOptions.None : (filterInfo.Options & ScopedItemOptions.Private) != ScopedItemOptions.None) && scope != this.sessionState.CurrentScope)
                {
                    flag = false;
                }
                else
                {
                    SessionState.ThrowIfNotVisible(this._origin, (object)script);
                }
            }
Exemple #21
0
 private void Start(bool incomingStream)
 {
     if (this.disposed)
     {
         throw PSTraceSource.NewObjectDisposedException("PipelineProcessor");
     }
     if (this.Stopping)
     {
         throw new PipelineStoppedException();
     }
     if (!this.executionStarted)
     {
         if ((this._commands == null) || (this._commands.Count == 0))
         {
             throw PSTraceSource.NewInvalidOperationException("PipelineStrings", "PipelineExecuteRequiresAtLeastOneCommand", new object[0]);
         }
         CommandProcessorBase base2 = this._commands[0];
         if ((base2 == null) || (base2.CommandRuntime == null))
         {
             throw PSTraceSource.NewInvalidOperationException("PipelineStrings", "PipelineExecuteRequiresAtLeastOneCommand", new object[0]);
         }
         if (this.executionScope == null)
         {
             this.executionScope = base2.Context.EngineSessionState.CurrentScope;
         }
         CommandProcessorBase base3 = this._commands[this._commands.Count - 1];
         if ((base3 == null) || (base3.CommandRuntime == null))
         {
             throw PSTraceSource.NewInvalidOperationException();
         }
         if (this.ExternalSuccessOutput != null)
         {
             base3.CommandRuntime.OutputPipe.ExternalWriter = this.ExternalSuccessOutput;
         }
         this.SetExternalErrorOutput();
         if ((this.ExternalInput == null) && !incomingStream)
         {
             base2.CommandRuntime.IsClosed = true;
         }
         IDictionary variableValue = base2.Context.GetVariableValue(SpecialVariables.PSDefaultParameterValuesVarPath, false) as IDictionary;
         this.executionStarted = true;
         int[] numArray = new int[this._commands.Count + 1];
         for (int i = 0; i < this._commands.Count; i++)
         {
             CommandProcessorBase base4 = this._commands[i];
             if (base4 == null)
             {
                 throw PSTraceSource.NewInvalidOperationException();
             }
             Guid engineActivityId = base4.Context.CurrentRunspace.EngineActivityId;
             Guid activityId       = EtwActivity.CreateActivityId();
             EtwActivity.SetActivityId(activityId);
             base4.PipelineActivityId = activityId;
             MshLog.LogCommandLifecycleEvent(base4.Context, CommandState.Started, base4.Command.MyInvocation);
             InvocationInfo myInvocation = base4.Command.MyInvocation;
             myInvocation.PipelinePosition      = i + 1;
             myInvocation.PipelineLength        = this._commands.Count;
             myInvocation.PipelineIterationInfo = numArray;
             base4.DoPrepare(variableValue);
             myInvocation.ExpectingInput = base4.IsPipelineInputExpected();
         }
         this.SetupOutErrorVariable();
         for (int j = 0; j < this._commands.Count; j++)
         {
             this._commands[j].DoBegin();
         }
     }
 }
        internal static Type ResolveTypeNameWithContext(TypeName typeName, out Exception exception, Assembly[] assemblies, TypeResolutionState typeResolutionState)
        {
            ExecutionContext context = null;

            exception = null;

            if (typeResolutionState == null)
            {
                // Usings from script scope (and if no script scope, fall back to default 'using namespace system')
                context             = LocalPipeline.GetExecutionContextFromTLS();
                typeResolutionState = TypeResolutionState.GetDefaultUsingState(context);
            }

            // We can do the cache lookup only if we don't define type in the current scope (cache would be invalid in this case).
            var result = typeResolutionState.ContainsTypeDefined(typeName.Name)
                ? null
                : TypeCache.Lookup(typeName, typeResolutionState);

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

            if (typeName.AssemblyName != null)
            {
                result = ResolveAssemblyQualifiedTypeName(typeName, out exception);
                TypeCache.Add(typeName, typeResolutionState, result);
                return(result);
            }

            // Simple typename (no generics, no arrays, no assembly name)
            // We use the following search order, using the specified name (assumed to be fully namespace qualified):
            //
            //     * Search scope table (includes 'using type x = ...' aliases)
            //     * Built in type accelerators (implicit 'using type x = ...' aliases that are effectively in global scope
            //     * typeResolutionState.assemblies, which contains:
            //          - Assemblies with PS types, added by 'using module'
            //          - Assemblies added by 'using assembly'.
            //          For this case, we REPORT ambiguity, since user explicitly specifies the set of assemblies.
            //     * All other loaded assemblies (excluding dynamic assemblies created for PS defined types).
            //          IGNORE ambiguity. It mimics PS v4. There are two reasons:
            //          1) If we report ambiguity, we need to fix our caching logic accordingly.
            //             Consider this code
            //                  Add-Type 'public class Q {}' # ok
            //                  Add-Type 'public class Q { }' # get error about the same name
            //                  [Q] # we would get error about ambiguous type, because we added assembly with duplicated type
            //                      # before we can report TYPE_ALREADY_EXISTS error.
            //
            //                  Add-Type 'public class Q2 {}' # ok
            //                  [Q2] # caching Q2 type
            //                  Add-Type 'public class Q2 { }' # get error about the same name
            //                  [Q2] # we don't get an error about ambiguous type, because it's cached already
            //          2) NuGet (VS Package Management console) uses MEF extensibility model.
            //             Different assemblies includes same interface (i.e. NuGet.VisualStudio.IVsPackageInstallerServices),
            //             where they include only methods that they are interested in the interface declaration (result interfaces are different!).
            //             Then, at runtime VS provides an instance. Everything work as far as instance has compatible API.
            //             So [NuGet.VisualStudio.IVsPackageInstallerServices] can be resolved to several different assemblies and it's ok.
            //     * User defined type accelerators (rare - interface was never public)
            //
            // If nothing is found, we search again, this time applying any 'using namespace ...' declarations including the implicit 'using namespace System'.
            // We must search all using aliases and REPORT an error if there is an ambiguity.

            var assemList = assemblies ?? ClrFacade.GetAssemblies(typeResolutionState, typeName);

            if (context == null)
            {
                context = LocalPipeline.GetExecutionContextFromTLS();
            }
            SessionStateScope currentScope = null;

            if (context != null)
            {
                currentScope = context.EngineSessionState.CurrentScope;
            }

            // If this is TypeDefinition we should not cache anything in TypeCache.
            if (typeName._typeDefinitionAst != null)
            {
                return(typeName._typeDefinitionAst.Type);
            }

            result = ResolveTypeNameWorker(typeName, currentScope, typeResolutionState.assemblies, typeResolutionState, /* reportAmbiguousException */ true, out exception);
            if (exception == null && result == null)
            {
                result = ResolveTypeNameWorker(typeName, currentScope, assemList, typeResolutionState, /* reportAmbiguousException */ false, out exception);
            }

            if (result != null)
            {
                TypeCache.Add(typeName, typeResolutionState, result);
                return(result);
            }

            if (exception == null)
            {
                foreach (var ns in typeResolutionState.namespaces)
                {
                    var newTypeNameToSearch = ns + "." + typeName.Name;
                    newTypeNameToSearch = typeResolutionState.GetAlternateTypeName(newTypeNameToSearch) ??
                                          newTypeNameToSearch;
                    var newTypeName = new TypeName(typeName.Extent, newTypeNameToSearch);
#if CORECLR
                    if (assemblies == null)
                    {
                        // We called 'ClrFacade.GetAssemblies' to get assemblies. That means the assemblies to search from
                        // are not pre-defined, and thus we have to refetch assembly again based on the new type name.
                        assemList = ClrFacade.GetAssemblies(typeResolutionState, newTypeName);
                    }
#endif
                    var newResult = ResolveTypeNameWorker(newTypeName, currentScope, typeResolutionState.assemblies, typeResolutionState, /* reportAmbiguousException */ true, out exception);
                    if (exception == null && newResult == null)
                    {
                        newResult = ResolveTypeNameWorker(newTypeName, currentScope, assemList, typeResolutionState, /* reportAmbiguousException */ false, out exception);
                    }

                    if (exception != null)
                    {
                        break;
                    }

                    if (newResult != null)
                    {
                        if (result == null)
                        {
                            result = newResult;
                        }
                        else
                        {
                            exception = new AmbiguousTypeException(typeName, new string[] { result.FullName, newResult.FullName });
                            result    = null;
                            break;
                        }
                    }
                }
            }

            if (exception != null)
            {
                // AmbiguousTypeException is for internal representation only.
                var ambiguousException = exception as AmbiguousTypeException;
                if (ambiguousException != null)
                {
                    exception = new PSInvalidCastException("AmbiguousTypeReference", exception,
                                                           ParserStrings.AmbiguousTypeReference, ambiguousException.TypeName.Name,
                                                           ambiguousException.Candidates[0], ambiguousException.Candidates[1]);
                }
            }

            if (result != null)
            {
                TypeCache.Add(typeName, typeResolutionState, result);
            }
            return(result);
        }
        /// <summary>
        /// The main processing loop of the command.
        /// </summary>
        protected override void ProcessRecord()
        {
            string path = GetFilePath();

            if (path == null)
            {
                return;
            }

            if (!File.Exists(path))
            {
                InvalidOperationException ioe =
                    PSTraceSource.NewInvalidOperationException(
                        ImportLocalizedDataStrings.FileNotExist,
                        path);
                WriteError(new ErrorRecord(ioe, "ImportLocalizedData", ErrorCategory.ObjectNotFound, path));
                return;
            }

            // Prevent additional commands in ConstrainedLanguage mode
            if (Context.LanguageMode == PSLanguageMode.ConstrainedLanguage)
            {
                if (_setSupportedCommand)
                {
                    NotSupportedException nse =
                        PSTraceSource.NewNotSupportedException(
                            ImportLocalizedDataStrings.CannotDefineSupportedCommand);
                    ThrowTerminatingError(
                        new ErrorRecord(nse, "CannotDefineSupportedCommand", ErrorCategory.PermissionDenied, null));
                }
            }

            string script = GetScript(path);

            if (script == null)
            {
                return;
            }

            try
            {
                var scriptBlock = Context.Engine.ParseScriptBlock(script, false);
                scriptBlock.CheckRestrictedLanguage(SupportedCommand, null, false);
                object         result;
                PSLanguageMode oldLanguageMode = Context.LanguageMode;
                Context.LanguageMode = PSLanguageMode.RestrictedLanguage;
                try
                {
                    result = scriptBlock.InvokeReturnAsIs();
                    if (result == AutomationNull.Value)
                    {
                        result = null;
                    }
                }
                finally
                {
                    Context.LanguageMode = oldLanguageMode;
                }

                if (_bindingVariable != null)
                {
                    VariablePath variablePath = new(_bindingVariable);
                    if (variablePath.IsUnscopedVariable)
                    {
                        variablePath = variablePath.CloneAndSetLocal();
                    }

                    if (string.IsNullOrEmpty(variablePath.UnqualifiedPath))
                    {
                        InvalidOperationException ioe = PSTraceSource.NewInvalidOperationException(
                            ImportLocalizedDataStrings.IncorrectVariableName, _bindingVariable);
                        WriteError(new ErrorRecord(ioe, "ImportLocalizedData", ErrorCategory.InvalidArgument,
                                                   _bindingVariable));
                        return;
                    }

                    SessionStateScope scope    = null;
                    PSVariable        variable = SessionState.Internal.GetVariableItem(variablePath, out scope);

                    if (variable == null)
                    {
                        variable = new PSVariable(variablePath.UnqualifiedPath, result, ScopedItemOptions.None);
                        Context.EngineSessionState.SetVariable(variablePath, variable, false, CommandOrigin.Internal);
                    }
                    else
                    {
                        variable.Value = result;

                        if (Context.LanguageMode == PSLanguageMode.ConstrainedLanguage)
                        {
                            // Mark untrusted values for assignments to 'Global:' variables, and 'Script:' variables in
                            // a module scope, if it's necessary.
                            ExecutionContext.MarkObjectAsUntrustedForVariableAssignment(variable, scope, Context.EngineSessionState);
                        }
                    }
                }

                // If binding variable is null, write the object to stream
                else
                {
                    WriteObject(result);
                }
            }
            catch (RuntimeException e)
            {
                PSInvalidOperationException ioe = PSTraceSource.NewInvalidOperationException(e,
                                                                                             ImportLocalizedDataStrings.ErrorLoadingDataFile,
                                                                                             path,
                                                                                             e.Message);

                throw ioe;
            }

            return;
        }
Exemple #24
0
        /// <summary>
        /// Removes the current scope from the scope tree and
        /// changes the current scope to the parent scope.
        /// </summary>
        /// <param name="scope">
        /// The scope to cleanup and remove.
        /// </param>
        /// <exception cref="SessionStateUnauthorizedAccessException">
        /// The global scope cannot be removed.
        /// </exception>
        internal void RemoveScope(SessionStateScope scope)
        {
            Diagnostics.Assert(
                _currentScope != null,
                "The currentScope should always be set.");

            if (scope == GlobalScope)
            {
                SessionStateUnauthorizedAccessException e =
                    new SessionStateUnauthorizedAccessException(
                        StringLiterals.Global,
                        SessionStateCategory.Scope,
                        "GlobalScopeCannotRemove",
                        SessionStateStrings.GlobalScopeCannotRemove);

                throw e;
            }

            // Give the provider a chance to cleanup the drive data associated
            // with drives in this scope

            foreach (PSDriveInfo drive in scope.Drives)
            {
                if (drive == null)
                {
                    continue;
                }

                CmdletProviderContext context = new CmdletProviderContext(this.ExecutionContext);

                // Call CanRemoveDrive to give the provider a chance to cleanup
                // but ignore the return value and exceptions

                try
                {
                    CanRemoveDrive(drive, context);
                }
                catch (LoopFlowException)
                {
                    throw;
                }
                catch (PipelineStoppedException)
                {
                    throw;
                }
                catch (ActionPreferenceStopException)
                {
                    throw;
                }
                catch (Exception) // Catch-all OK, 3rd party callout.
                {
                    // Ignore all exceptions from the provider as we are
                    // going to force the removal anyway
                }
            }

            scope.RemoveAllDrives();

            // If the scope being removed is the current scope,
            // then it must be removed from the tree.

            if (scope == _currentScope && _currentScope.Parent != null)
            {
                _currentScope = _currentScope.Parent;
            }

            scope.Parent = null;
        }
Exemple #25
0
        /// <summary>
        /// Given a scope identifier, returns the proper session state scope.
        /// </summary>
        /// <param name="scopeID">
        /// A scope identifier that is either one of the "special" scopes like
        /// "global", "local", or "private, or a numeric ID of a relative scope
        /// to the current scope.
        /// </param>
        /// <returns>
        /// The scope identified by the scope ID or the current scope if the
        /// scope ID is not defined as a special or numeric scope identifier.
        /// </returns>
        /// <exception cref="ArgumentException">
        /// If <paramref name="scopeID"/> is less than zero, or not
        /// a number and not "script", "global", "local", or "private"
        /// </exception>
        /// <exception cref="ArgumentOutOfRangeException">
        /// If <paramref name="scopeID"/> is less than zero or greater than the number of currently
        /// active scopes.
        /// </exception>
        internal SessionStateScope GetScopeByID(string scopeID)
        {
            SessionStateScope result = _currentScope;

            if (!string.IsNullOrEmpty(scopeID))
            {
                if (string.Equals(
                        scopeID,
                        StringLiterals.Global,
                        StringComparison.OrdinalIgnoreCase))
                {
                    result = GlobalScope;
                }
                else if (string.Equals(
                             scopeID,
                             StringLiterals.Local,
                             StringComparison.OrdinalIgnoreCase))
                {
                    result = _currentScope;
                }
                else if (string.Equals(
                             scopeID,
                             StringLiterals.Private,
                             StringComparison.OrdinalIgnoreCase))
                {
                    result = _currentScope;
                }
                else if (string.Equals(
                             scopeID,
                             StringLiterals.Script,
                             StringComparison.OrdinalIgnoreCase))
                {
                    // Get the current script scope from the stack.
                    result = _currentScope.ScriptScope;
                }
                else
                {
                    // Since the scope is not any of the special scopes
                    // try parsing it as an ID

                    try
                    {
                        int scopeNumericID = Int32.Parse(scopeID, System.Globalization.CultureInfo.CurrentCulture);

                        if (scopeNumericID < 0)
                        {
                            throw PSTraceSource.NewArgumentOutOfRangeException(ScopeParameterName, scopeID);
                        }

                        result = GetScopeByID(scopeNumericID) ?? _currentScope;
                    }
                    catch (FormatException)
                    {
                        throw PSTraceSource.NewArgumentException(ScopeParameterName, AutomationExceptions.InvalidScopeIdArgument, ScopeParameterName);
                    }
                    catch (OverflowException)
                    {
                        throw PSTraceSource.NewArgumentOutOfRangeException(ScopeParameterName, scopeID);
                    }
                }
            }

            return(result);
        }
Exemple #26
0
        protected override void ProcessRecord()
        {
            string filePath = this.GetFilePath();

            if (filePath != null)
            {
                if (!File.Exists(filePath))
                {
                    InvalidOperationException exception = PSTraceSource.NewInvalidOperationException("ImportLocalizedData", "FileNotExist", new object[] { filePath });
                    base.WriteError(new ErrorRecord(exception, "ImportLocalizedData", ErrorCategory.ObjectNotFound, filePath));
                }
                else
                {
                    string script = this.GetScript(filePath);
                    if (script != null)
                    {
                        try
                        {
                            object      obj2;
                            ScriptBlock block = base.Context.Engine.ParseScriptBlock(script, false);
                            block.CheckRestrictedLanguage(this.SupportedCommand, null, false);
                            PSLanguageMode languageMode = base.Context.LanguageMode;
                            base.Context.LanguageMode = PSLanguageMode.RestrictedLanguage;
                            try
                            {
                                obj2 = block.InvokeReturnAsIs(new object[0]);
                                if (obj2 == AutomationNull.Value)
                                {
                                    obj2 = null;
                                }
                            }
                            finally
                            {
                                base.Context.LanguageMode = languageMode;
                            }
                            if (this._bindingVariable != null)
                            {
                                VariablePath variablePath = new VariablePath(this._bindingVariable);
                                if (variablePath.IsUnscopedVariable)
                                {
                                    variablePath = variablePath.CloneAndSetLocal();
                                }
                                if (string.IsNullOrEmpty(variablePath.UnqualifiedPath))
                                {
                                    InvalidOperationException exception2 = PSTraceSource.NewInvalidOperationException("ImportLocalizedData", "IncorrectVariableName", new object[] { this._bindingVariable });
                                    base.WriteError(new ErrorRecord(exception2, "ImportLocalizedData", ErrorCategory.InvalidArgument, this._bindingVariable));
                                }
                                else
                                {
                                    SessionStateScope scope        = null;
                                    PSVariable        variableItem = base.SessionState.Internal.GetVariableItem(variablePath, out scope);
                                    if (variableItem == null)
                                    {
                                        variableItem = new PSVariable(variablePath.UnqualifiedPath, obj2, ScopedItemOptions.None);
                                        base.Context.EngineSessionState.SetVariable(variablePath, variableItem, false, CommandOrigin.Internal);
                                    }
                                    else
                                    {
                                        variableItem.Value = obj2;
                                    }
                                }
                            }
                            else
                            {
                                base.WriteObject(obj2);
                            }
                        }
                        catch (RuntimeException exception3)
                        {
                            throw PSTraceSource.NewInvalidOperationException(exception3, "ImportLocalizedData", "ErrorLoadingDataFile", new object[] { filePath, exception3.Message });
                        }
                    }
                }
            }
        }
Exemple #27
0
        } // internal Array DoStepItems

        /// <summary>
        /// Prepares the pipeline for execution.
        /// </summary>
        /// <param name="incomingStream">
        /// Input objects are expected, so do not close the first command.
        /// This will prevent the one default call to ProcessRecord
        /// on the first command.
        /// </param>
        /// <remarks>
        /// Start must always be called in a context where terminating errors will
        /// be caught and result in DisposeCommands.
        /// </remarks>
        /// <exception cref="InvalidOperationException">
        /// PipelineExecuteRequiresAtLeastOneCommand
        /// </exception>
        /// <exception cref="ParameterBindingException">
        /// If any parameters fail to bind,
        /// or
        /// If any mandatory parameters are missing.
        /// </exception>
        /// <exception cref="MetadataException">
        /// If there is an error generating the metadata for dynamic parameters.
        /// </exception>
        /// <exception cref="PipelineStoppedException">
        /// The pipeline has already been stopped,
        /// or a terminating error occurred in a downstream cmdlet.
        /// </exception>
        /// <exception cref="ExtendedTypeSystemException">
        /// An error occurred clearing the error variable.
        /// </exception>
        private void Start(bool incomingStream)
        {
            // Every call to Step or SynchronousExecute will call Start.
            if (_disposed)
            {
                throw PSTraceSource.NewObjectDisposedException("PipelineProcessor");
            }
            if (Stopping)
            {
                throw new PipelineStoppedException();
            }

            if (_executionStarted)
                return;

            if (null == _commands || 0 == _commands.Count)
            {
                throw PSTraceSource.NewInvalidOperationException(
                    PipelineStrings.PipelineExecuteRequiresAtLeastOneCommand);
            }

            CommandProcessorBase firstcommandProcessor = _commands[0];
            if (null == firstcommandProcessor
                || null == firstcommandProcessor.CommandRuntime)
            {
                throw PSTraceSource.NewInvalidOperationException(
                    PipelineStrings.PipelineExecuteRequiresAtLeastOneCommand);
            }

            // Set the execution scope using the current scope
            if (_executionScope == null)
            {
                _executionScope = firstcommandProcessor.Context.EngineSessionState.CurrentScope;
            }

            // add ExternalSuccessOutput to the last command
            CommandProcessorBase LastCommandProcessor = _commands[_commands.Count - 1];
            if (null == LastCommandProcessor
                || null == LastCommandProcessor.CommandRuntime)
            {
                // "PipelineProcessor.Start(): LastCommandProcessor == null"
                throw PSTraceSource.NewInvalidOperationException();
            }
            if (null != ExternalSuccessOutput)
            {
                LastCommandProcessor.CommandRuntime.OutputPipe.ExternalWriter
                    = ExternalSuccessOutput;
            }

            // add ExternalErrorOutput to all commands whose error
            // output is not yet claimed
            SetExternalErrorOutput();

            if (null == ExternalInput && !incomingStream)
            {
                // no upstream cmdlet from the first command
                firstcommandProcessor.CommandRuntime.IsClosed = true;
            }

            // We want the value of PSDefaultParameterValues before possibly changing to the commands scopes.
            // This ensures we use the value from the callers scope, not the callees scope.
            IDictionary psDefaultParameterValues =
                firstcommandProcessor.Context.GetVariableValue(SpecialVariables.PSDefaultParameterValuesVarPath, false) as IDictionary;

            _executionStarted = true;

            //
            // Allocate the pipeline iteration array; note that the pipeline position for
            // each command starts at 1 so we need to allocate _commands.Count + 1 items.
            //
            int[] pipelineIterationInfo = new int[_commands.Count + 1];

            // Prepare all commands from Engine's side,
            // and make sure they are all valid
            for (int i = 0; i < _commands.Count; i++)
            {
                CommandProcessorBase commandProcessor = _commands[i];
                if (null == commandProcessor)
                {
                    // "null command " + i
                    throw PSTraceSource.NewInvalidOperationException();
                }

                // Generate new Activity Id for the thread
                Guid pipelineActivityId = EtwActivity.CreateActivityId();

                // commandProcess.PipelineActivityId = new Activity id
                EtwActivity.SetActivityId(pipelineActivityId);
                commandProcessor.PipelineActivityId = pipelineActivityId;

                // Log a command started event
                MshLog.LogCommandLifecycleEvent(
                    commandProcessor.Context,
                    CommandState.Started,
                    commandProcessor.Command.MyInvocation);

                //Microsoft.PowerShell.Telemetry.Internal.TelemetryAPI.TraceExecutedCommand(commandProcessor.Command.CommandInfo, commandProcessor.Command.CommandOrigin);

                // Log the execution of a command (not script chunks, as they
                // are not commands in and of themselves)
                if (commandProcessor.CommandInfo.CommandType != CommandTypes.Script)
                {
                    commandProcessor.CommandRuntime.PipelineProcessor.LogExecutionInfo(
                        commandProcessor.Command.MyInvocation, commandProcessor.CommandInfo.Name);
                }

                InvocationInfo myInfo = commandProcessor.Command.MyInvocation;
                myInfo.PipelinePosition = i + 1;
                myInfo.PipelineLength = _commands.Count;
                myInfo.PipelineIterationInfo = pipelineIterationInfo;
                commandProcessor.DoPrepare(psDefaultParameterValues);
                myInfo.ExpectingInput = commandProcessor.IsPipelineInputExpected();
            }

            // Clear ErrorVariable as appropriate
            SetupParameterVariables();

            // Prepare all commands from Command's side.
            // Note that DoPrepare() and DoBegin() should NOT be combined
            // in a single for loop.
            // Reason: Encoding of commandline parameters happen
            // as part of DoPrepare(). If they are combined,
            // the first command's DoBegin() will be called before
            // the next command's DoPrepare(). Since BeginProcessing()
            // can write objects to the downstream commandlet,
            // it will end up calling DoExecute() (from Pipe.Add())
            // before DoPrepare.
            for (int i = 0; i < _commands.Count; i++)
            {
                CommandProcessorBase commandProcessor = _commands[i];

                commandProcessor.DoBegin();
            }
        } // private void Start
 /// <summary>
 /// Derived classes override this method to return their
 /// particular type of scoped item.
 /// </summary>
 /// <param name="scope">
 /// The scope to look the item up in.
 /// </param>
 /// <param name="name">
 /// The name of the item to retrieve.
 /// </param>
 /// <param name="newCurrentItem">
 /// The scope item that the derived class should return.
 /// </param>
 /// <returns>
 /// True if the scope item was found or false otherwise.
 /// </returns>
 protected abstract bool GetScopeItem(
     SessionStateScope scope,
     VariablePath name,
     out T newCurrentItem);