public Collection <PSObject> InvokeScript( SessionState sessionState, ScriptBlock scriptBlock, params object[] args) { if (scriptBlock == null) { throw PSTraceSource.NewArgumentNullException(nameof(scriptBlock)); } if (sessionState == null) { throw PSTraceSource.NewArgumentNullException(nameof(sessionState)); } SessionStateInternal _oldSessionState = _context.EngineSessionState; try { _context.EngineSessionState = sessionState.Internal; return(InvokeScript( sb: scriptBlock, useNewScope: false, writeToPipeline: PipelineResultTypes.None, input: null, args: args)); } finally { _context.EngineSessionState = _oldSessionState; } }
public FunctionScopeItemSearcher( SessionStateInternal sessionState, VariablePath lookupPath, CommandOrigin origin) : base(sessionState, lookupPath) { _origin = origin; }
/// <summary> /// Set the SessionState of the script block appropriately. /// </summary> private void PrepareScriptBlockToInvoke(object instance, object sessionStateInternal) { SessionStateInternal sessionStateToUse = null; if (instance != null) { // Use the SessionState passed in, which is the one associated with the instance. sessionStateToUse = (SessionStateInternal)sessionStateInternal; } else { // For static method, it's a little complex. // - Check if the current default runspace is registered with the SessionStateKeeper. If so, use the registered SessionState. // - Otherwise, check if default SessionState is still alive. If so, use the default SessionState. // - Otherwise, the 'SessionStateInternal' property will be set to null, and thus the default runspace of the current thread will be used. // If the current thread doesn't have a default Runspace, then an InvalidOperationException will be thrown when invoking the // script block, which is expected. sessionStateToUse = (SessionStateInternal)_sessionStateKeeper.GetSessionState(); if (sessionStateToUse == null) { lock (_defaultSessionStateToUse) { _defaultSessionStateToUse.TryGetTarget(out sessionStateToUse); } } } _boundScriptBlock.Value.SessionStateInternal = sessionStateToUse; }
/// <summary> /// This method should be called only from generated ctors for PowerShell classes. /// It's not intended to be a public API, but because we generate type in a different assembly it has to be public. /// Return type should be SessionStateInternal, but it violates accessibility consistency, so we use object. /// </summary> /// <remarks> /// By default, PowerShell class instantiation usually happens in the same Runspace where the class is defined. In /// that case, the created instance will be bound to the session state used to define that class in the Runspace. /// However, if the instantiation happens in a different Runspace where the class is not defined, then the created /// instance won't be bound to any session state. /// </remarks> /// <returns>SessionStateInternal</returns> public object GetSessionState() { SessionStateInternal ss = null; _stateMap.TryGetValue(Runspace.DefaultRunspace, out ss); return(ss); }
/// <summary> /// This method should be called only from generated ctors for PowerShell classes. /// It's not intended to be a public API, but because we generate type in a different assembly it has to be public. /// Return type should be SessionStateInternal, but it violates accessibility consistency, so we use object. /// </summary> /// <returns>SessionStateInternal</returns> public object GetSessionState() { SessionStateInternal ss = null; bool found = _stateMap.TryGetValue(Runspace.DefaultRunspace, out ss); Diagnostics.Assert(found, "We always should be able to find corresponding SessionState"); return(ss); }
public VariableScopeItemSearcher( SessionStateInternal sessionState, ScopedItemLookupPath lookupPath, CommandOrigin origin) : base(sessionState, lookupPath) { this._origin = origin; }
/// <summary> /// Initialize default values of preference vars. /// </summary> /// <returns>Does not return a value.</returns> private void InitializeDefaults() { SessionStateInternal ss = _engine.Context.EngineSessionState; Dbg.Assert(ss != null, "SessionState should not be null"); // Add the variables that must always be there... ss.InitializeFixedVariables(); }
private ProviderInfo GetProvider() { ExecutionContext executionContext = GetExecutionContext(); SessionStateInternal sessionState = new SessionStateInternal(executionContext); SessionStateProviderEntry providerEntry = new SessionStateProviderEntry("FileSystem", typeof(FileSystemProvider), null); sessionState.AddSessionStateEntry(providerEntry); ProviderInfo matchingProvider = sessionState.ProviderList.ToList()[0]; return(matchingProvider); }
public void TestDrives() { CultureInfo currentCulture = CultureInfo.CurrentCulture; PSHost hostInterface = new DefaultHost(currentCulture, currentCulture); InitialSessionState iss = InitialSessionState.CreateDefault2(); AutomationEngine engine = new AutomationEngine(hostInterface, iss); ExecutionContext executionContext = new ExecutionContext(engine, hostInterface, iss); SessionStateInternal sessionState = new SessionStateInternal(executionContext); Collection <PSDriveInfo> drives = sessionState.Drives(null); Assert.NotNull(drives); }
/// <summary> /// This method should be called only from /// - generated ctors for PowerShell classes, AND /// - ScriptBlockMemberMethodWrapper when invoking static methods of PowerShell classes. /// It's not intended to be a public API, but because we generate type in a different assembly it has to be public. /// Return type should be SessionStateInternal, but it violates accessibility consistency, so we use object. /// </summary> /// <remarks> /// By default, PowerShell class instantiation usually happens in the same Runspace where the class is defined. In /// that case, the created instance will be bound to the session state used to define that class in the Runspace. /// However, if the instantiation happens in a different Runspace where the class is not defined, or it happens on /// a thread without a default Runspace, then the created instance won't be bound to any session state. /// </remarks> /// <returns>SessionStateInternal</returns> public object GetSessionState() { SessionStateInternal ss = null; // DefaultRunspace could be null when we reach here. For example, create instance of // a PowerShell class by using reflection on a thread without DefaultRunspace. // Make sure we call 'TryGetValue' with a non-null key, otherwise ArgumentNullException will be thrown. Runspace defaultRunspace = Runspace.DefaultRunspace; if (defaultRunspace != null) { _stateMap.TryGetValue(defaultRunspace, out ss); } return(ss); }
/// <summary> /// Constructs a scoped item searcher. /// </summary> /// <param name="sessionState"> /// The state of the engine instance to enumerate through the scopes. /// </param> /// <param name="lookupPath"> /// The parsed name of the item to lookup. /// </param> /// <exception cref="ArgumentNullException"> /// If <paramref name="sessionState"/> or <paramref name="lookupPath"/> /// is null. /// </exception> internal ScopedItemSearcher( SessionStateInternal sessionState, VariablePath lookupPath) { if (sessionState == null) { throw PSTraceSource.NewArgumentNullException(nameof(sessionState)); } if (lookupPath == null) { throw PSTraceSource.NewArgumentNullException(nameof(lookupPath)); } this.sessionState = sessionState; _lookupPath = lookupPath; InitializeScopeEnumerator(); }
private void InitializeDefaults() { SessionStateInternal engineSessionState = this._engine.Context.EngineSessionState; engineSessionState.InitializeFixedVariables(); if (this.RunspaceConfiguration != null) { bool addSetStrictMode = true; foreach (RunspaceConfigurationEntry entry in this.RunspaceConfiguration.Cmdlets) { if (entry.Name.Equals("Set-StrictMode", StringComparison.OrdinalIgnoreCase)) { addSetStrictMode = false; break; } } engineSessionState.AddBuiltInEntries(addSetStrictMode); } }
internal void RegisterRunspace() { SessionStateInternal sessionStateInMap = null; Runspace runspaceToUse = Runspace.DefaultRunspace; SessionStateInternal sessionStateToUse = runspaceToUse.ExecutionContext.EngineSessionState; // Different threads will operate on different key/value pairs (default-runspace/session-state pairs), // and a ConditionalWeakTable itself is thread safe, so there won't be race condition here. if (!_stateMap.TryGetValue(runspaceToUse, out sessionStateInMap)) { // If the key doesn't exist yet, add it _stateMap.Add(runspaceToUse, sessionStateToUse); } else if (sessionStateInMap != sessionStateToUse) { // If the key exists but the corresponding value is not what we should use, then remove the key/value pair and add the new pair. // This could happen when a powershell class is defined in a module and the module gets reloaded. In such case, the same TypeDefinitionAst // instance will get reused, but should be associated with the SessionState from the new module, instead of the one from the old module. _stateMap.AddOrUpdate(runspaceToUse, sessionStateToUse); } // If the key exists and the corresponding value is the one we should use, then do nothing. }
public AliasScopeItemSearcher( SessionStateInternal sessionState, VariablePath lookupPath) : base(sessionState, lookupPath) { }
public DriveScopeItemSearcher( SessionStateInternal sessionState, ScopedItemLookupPath lookupPath) : base(sessionState, lookupPath) { }
private void ResolveCurrentDirectoryInLookupPaths() { var indexesToRemove = new SortedDictionary <int, int>(); int removalListCount = 0; string fileSystemProviderName = _context.ProviderNames.FileSystem; SessionStateInternal sessionState = _context.EngineSessionState; // Only use the directory if it gets resolved by the FileSystemProvider bool isCurrentDriveValid = sessionState.CurrentDrive != null && sessionState.CurrentDrive.Provider.NameEquals(fileSystemProviderName) && sessionState.IsProviderLoaded(fileSystemProviderName); string environmentCurrentDirectory = Directory.GetCurrentDirectory(); LocationGlobber pathResolver = _context.LocationGlobber; // Loop through the relative paths and resolve them foreach (int index in _lookupPaths.IndexOfRelativePath()) { string?resolvedDirectory = null; string?resolvedPath = null; CommandDiscovery.discoveryTracer.WriteLine( "Lookup directory \"{0}\" appears to be a relative path. Attempting resolution...", _lookupPaths[index]); if (isCurrentDriveValid) { try { ProviderInfo provider; resolvedPath = pathResolver.GetProviderPath( _lookupPaths[index], out provider); } catch (ProviderInvocationException providerInvocationException) { CommandDiscovery.discoveryTracer.WriteLine( "The relative path '{0}', could not be resolved because the provider threw an exception: '{1}'", _lookupPaths[index], providerInvocationException.Message); } catch (InvalidOperationException) { CommandDiscovery.discoveryTracer.WriteLine( "The relative path '{0}', could not resolve a home directory for the provider", _lookupPaths[index]); } // Note, if the directory resolves to multiple paths, only the first is used. if (!string.IsNullOrEmpty(resolvedPath)) { CommandDiscovery.discoveryTracer.TraceError( "The relative path resolved to: {0}", resolvedPath); resolvedDirectory = resolvedPath; } else { CommandDiscovery.discoveryTracer.WriteLine( "The relative path was not a file system path. {0}", _lookupPaths[index]); } } else { CommandDiscovery.discoveryTracer.TraceWarning( "The current drive is not set, using the process current directory: {0}", environmentCurrentDirectory); resolvedDirectory = environmentCurrentDirectory; } // If we successfully resolved the path, make sure it is unique. Remove // any duplicates found after the first occurrence of the path. if (resolvedDirectory != null) { int existingIndex = _lookupPaths.IndexOf(resolvedDirectory); if (existingIndex != -1) { if (existingIndex > index) { // The relative path index is less than the explicit path, // so remove the explicit path. indexesToRemove.Add(removalListCount++, existingIndex); _lookupPaths[index] = resolvedDirectory; } else { // The explicit path index is less than the relative path // index, so remove the relative path. indexesToRemove.Add(removalListCount++, index); } } else { // Change the relative path to the resolved path. _lookupPaths[index] = resolvedDirectory; } } else { // The directory couldn't be resolved so remove it from the // lookup paths. indexesToRemove.Add(removalListCount++, index); } } // Now remove all the duplicates starting from the back of the collection. // As each element is removed, elements that follow are moved up to occupy // the emptied index. for (int removeIndex = indexesToRemove.Count; removeIndex > 0; --removeIndex) { int indexToRemove = indexesToRemove[removeIndex - 1]; _lookupPaths.RemoveAt(indexToRemove); } }
internal object GetValue(ExecutionContext context, SessionStateInternal sessionStateInternal, IDictionary usingValues = null) { lock (this) { // Code written as part of a default value in a parameter is considered trusted return Compiler.GetExpressionValue(this.Expression, true, context, sessionStateInternal, usingValues, ref _delegate, ref _sequencePoints, ref _localsTupleType); } }
internal static object GetExpressionValue(ExpressionAst expressionAst, bool isTrustedInput, ExecutionContext context, SessionStateInternal sessionStateInternal, IDictionary usingValues = null) { Func<FunctionContext, object> lambda = null; IScriptExtent[] sequencePoints = null; Type localsTupleType = null; return GetExpressionValue(expressionAst, isTrustedInput, context, sessionStateInternal, usingValues, ref lambda, ref sequencePoints, ref localsTupleType); }
protected override void BeginProcessing() { SessionStateInternal.MountDefaultDrive("Cert", base.Context); SessionStateInternal.MountDefaultDrive("WSMan", base.Context); }
internal PSVariableIntrinsics(SessionStateInternal sessionState) { using (PSVariableIntrinsics.tracer.TraceConstructor((object)this)) this.sessionState = sessionState != null ? sessionState : throw PSVariableIntrinsics.tracer.NewArgumentException(nameof(sessionState)); }
private static object GetExpressionValue(ExpressionAst expressionAst, bool isTrustedInput, ExecutionContext context, SessionStateInternal sessionStateInternal, IDictionary usingValues, ref Func<FunctionContext, object> lambda, ref IScriptExtent[] sequencePoints, ref Type localsTupleType) { object constantValue; if (IsConstantValueVisitor.IsConstant(expressionAst, out constantValue)) { return constantValue; } // If this isn't trusted input, then just return. if (!isTrustedInput) { return null; } // Can't be exposed to untrusted input - exposing private variable names / etc. could be // information disclosure. var variableAst = expressionAst as VariableExpressionAst; if (variableAst != null) { // We can avoid creating a lambda for the common case of a simple variable expression. return VariableOps.GetVariableValue(variableAst.VariablePath, context, variableAst); } // Can't be exposed to untrusted input - invoking arbitrary code could result in remote code // execution. if (lambda == null) { lambda = (new Compiler()).CompileSingleExpression(expressionAst, out sequencePoints, out localsTupleType); } SessionStateInternal oldSessionState = context.EngineSessionState; try { if (sessionStateInternal != null && context.EngineSessionState != sessionStateInternal) { // If we're running a function from a module, we need to evaluate the initializers in the // module context, not the callers context... context.EngineSessionState = sessionStateInternal; } var resultList = new List<object>(); var pipe = new Pipe(resultList); try { var functionContext = new FunctionContext { _sequencePoints = sequencePoints, _executionContext = context, _file = expressionAst.Extent.File, _outputPipe = pipe, _localsTuple = MutableTuple.MakeTuple(localsTupleType, DottedLocalsNameIndexMap) }; if (usingValues != null) { var boundParameters = new PSBoundParametersDictionary { ImplicitUsingParameters = usingValues }; functionContext._localsTuple.SetAutomaticVariable(AutomaticVariable.PSBoundParameters, boundParameters, context); } var result = lambda(functionContext); if (result == AutomationNull.Value) { return resultList.Count == 0 ? null : PipelineOps.PipelineResult(resultList); } return result; } catch (TargetInvocationException tie) { throw tie.InnerException; } } catch (TerminateException) { // the debugger is terminating the execution; bubble up the exception throw; } catch (FlowControlException) { // ignore break, continue and return exceptions return null; } finally { context.EngineSessionState = oldSessionState; } }