internal void CaptureLocals() { if (this._sessionState == null) { throw PSTraceSource.NewInvalidOperationException("Modules", "InvalidOperationOnBinaryModule", new object[0]); } ExecutionContext executionContextFromTLS = LocalPipeline.GetExecutionContextFromTLS(); MutableTuple localsTuple = executionContextFromTLS.EngineSessionState.CurrentScope.LocalsTuple; IEnumerable <PSVariable> values = executionContextFromTLS.EngineSessionState.CurrentScope.Variables.Values; if (localsTuple != null) { Dictionary <string, PSVariable> result = new Dictionary <string, PSVariable>(); localsTuple.GetVariableTable(result, false); values = result.Values.Concat <PSVariable>(values); } foreach (PSVariable variable in values) { try { if (variable.Options == ScopedItemOptions.None) { PSVariable variable2 = new PSVariable(variable.Name, variable.Value, variable.Options, variable.Attributes, variable.Description); this._sessionState.Internal.NewVariable(variable2, false); } } catch (SessionStateException) { } } }
internal static object InvokeAdaptedSetMember(object obj, string methodName, object[] args, object valueToSet) { TypeTable typeTable; ExecutionContext executionContextFromTLS = LocalPipeline.GetExecutionContextFromTLS(); object obj1 = obj; if (executionContextFromTLS != null) { typeTable = executionContextFromTLS.TypeTable; } else { typeTable = null; } PSObject.AdapterSet mappedAdapter = PSObject.GetMappedAdapter(obj1, typeTable); PSParameterizedProperty pSParameterizedProperty = mappedAdapter.OriginalAdapter.BaseGetMember <PSParameterizedProperty>(obj, methodName); if (pSParameterizedProperty == null && mappedAdapter.DotNetAdapter != null) { pSParameterizedProperty = mappedAdapter.DotNetAdapter.BaseGetMember <PSParameterizedProperty>(obj, methodName); } if (pSParameterizedProperty == null) { object[] typeFullName = new object[2]; typeFullName[0] = ParserOps.GetTypeFullName(obj); typeFullName[1] = methodName; throw InterpreterError.NewInterpreterException(methodName, typeof(RuntimeException), null, "MethodNotFound", ParserStrings.MethodNotFound, typeFullName); } else { pSParameterizedProperty.InvokeSet(valueToSet, args); return(valueToSet); } }
internal static object GetNonIndexable(object target, object[] indices) { // We want to allow: // $x[0] // and // $x[-1] // to be the same as // $x // But disallow anything else: // if in the strict mode, throw exception // otherwise, return AutomationNull.Value to signal no result if (indices.Length == 1) { var index = indices[0]; if (index != null && (LanguagePrimitives.Equals(0, index) || LanguagePrimitives.Equals(-1, index))) { return(target); } } var context = LocalPipeline.GetExecutionContextFromTLS(); if (context == null || !context.IsStrictVersion(2)) { return(AutomationNull.Value); } throw InterpreterError.NewInterpreterException(target, typeof(RuntimeException), null, "CannotIndex", ParserStrings.CannotIndex, target.GetType()); }
public PSModuleInfo(ScriptBlock scriptBlock) { this._context = LocalPipeline.GetExecutionContextFromTLS(); if (this._context == null) { throw new InvalidOperationException(nameof(PSModuleInfo)); } PSModuleInfo.SetDefaultDynamicNameAndPath(this); this._sessionState = new SessionState(this._context.EngineSessionState, true, true); this._sessionState.Internal.Module = this; SessionStateInternal engineSessionState = this._context.EngineSessionState; try { ArrayList resultList = (ArrayList)null; this._context.EngineSessionState = this._sessionState.Internal; this._context.EngineSessionState.SetVariableValue("PSScriptRoot", (object)this._path); scriptBlock = scriptBlock.Clone(true); scriptBlock.SessionState = this._sessionState; if (scriptBlock == null) { throw PSModuleInfo.tracer.NewInvalidOperationException(); } scriptBlock.InvokeWithPipe(false, true, (object)AutomationNull.Value, (object)AutomationNull.Value, (object)AutomationNull.Value, (Pipe)null, ref resultList); } finally { this._context.EngineSessionState = engineSessionState; } }
internal static object GetAdaptedValue(object obj, string member) { ExecutionContext executionContextFromTLS = LocalPipeline.GetExecutionContextFromTLS(); PSMemberInfo memberInfo = null; if ((executionContextFromTLS != null) && (executionContextFromTLS.TypeTable != null)) { ConsolidatedString typeNames = PSObject.GetTypeNames(obj); memberInfo = executionContextFromTLS.TypeTable.GetMembers <PSMemberInfo>(typeNames)[member]; if (memberInfo != null) { memberInfo = CloneMemberInfo(memberInfo, obj); } } PSObject.AdapterSet mappedAdapter = PSObject.GetMappedAdapter(obj, (executionContextFromTLS != null) ? executionContextFromTLS.TypeTable : null); if (memberInfo == null) { memberInfo = mappedAdapter.OriginalAdapter.BaseGetMember <PSMemberInfo>(obj, member); } if ((memberInfo == null) && (mappedAdapter.DotNetAdapter != null)) { memberInfo = mappedAdapter.DotNetAdapter.BaseGetMember <PSMemberInfo>(obj, member); } if (memberInfo != null) { return(memberInfo.Value); } if ((executionContextFromTLS != null) && executionContextFromTLS.IsStrictVersion(2)) { throw new PropertyNotFoundException("PropertyNotFoundStrict", null, ParserStrings.PropertyNotFoundStrict, new object[] { LanguagePrimitives.ConvertTo <string>(member) }); } return(null); }
internal static int FormatEnumerationLimit() { object enumLimitVal = null; try { // Win8: 192504 if (LocalPipeline.GetExecutionContextFromTLS() != null) { enumLimitVal = LocalPipeline.GetExecutionContextFromTLS() .SessionState.PSVariable .GetValue("global:" + InitialSessionState.FormatEnumerationLimit); } } // Eat the following exceptions, enumerationLimit will use the default value catch (ProviderNotFoundException) { } catch (ProviderInvocationException) { } // if $global:FormatEnumerationLimit is an int, overwrite the default value return(enumLimitVal is int?(int)enumLimitVal : InitialSessionState.DefaultFormatEnumerationLimit); }
// Keep in sync: // S.M.A.CommandProcessorBase.CheckForSevereException // S.M.A.Internal.ConsoleHost.CheckForSevereException // S.M.A.Commands.CommandsCommon.CheckForSevereException // S.M.A.Commands.UtilityCommon.CheckForSevereException /// <summary> /// Checks whether the exception is a severe exception which should /// cause immediate process failure. /// </summary> /// <param name="cmdlet">can be null</param> /// <param name="e"></param> /// <remarks> /// CB says 02/23/2005: I personally would err on the side /// of treating OOM like an application exception, rather than /// a critical system failure.I think this will be easier to justify /// in Orcas, if we tease apart the two cases of OOM better. /// But even in Whidbey, how likely is it that we couldnt JIT /// some backout code? At that point, the process or possibly /// the machine is likely to stop executing soon no matter /// what you do in this routine. So I would just consider /// AccessViolationException. (I understand why you have SO here, /// at least temporarily). /// </remarks> internal static void CheckForSevereException(PSCmdlet cmdlet, Exception e) { if (e is AccessViolationException || e is StackOverflowException) { try { if (!alreadyFailing) { alreadyFailing = true; // Get the ExecutionContext from the thread. ExecutionContext context = (null != cmdlet) ? cmdlet.Context : LocalPipeline.GetExecutionContextFromTLS(); // Log a command health event for this critical error. MshLog.LogCommandHealthEvent(context, e, Severity.Critical); } } finally { if (!designForTestability_SkipFailFast) { WindowsErrorReporting.FailFast(e); } } } }
internal static object GetMDArrayValue(Array array, int[] indexes, bool slicing) { if (array.Rank != indexes.Length) { ReportIndexingError(array, indexes, null); } for (int i = 0; i < indexes.Length; ++i) { int ub = array.GetUpperBound(i); int lb = array.GetLowerBound(i); if (indexes[i] < lb) { indexes[i] = indexes[i] + ub + 1; } if (indexes[i] < lb || indexes[i] > ub) { // In strict mode, don't return, fall through and let Array.GetValue raise an exception. var context = LocalPipeline.GetExecutionContextFromTLS(); if (context != null && !context.IsStrictVersion(3)) { // If we're slicing, return AutomationNull.Value to signal no result) return(slicing ? AutomationNull.Value : null); } } } // All indexes have been validated, so this won't raise an exception. return(array.GetValue(indexes)); }
internal static object GetMDArrayValue(Array array, int[] indexes, bool slicing) { if (array.Rank != indexes.Length) { ReportIndexingError(array, indexes, null); } for (int i = 0; i < indexes.Length; i++) { int upperBound = array.GetUpperBound(i); int lowerBound = array.GetLowerBound(i); if (indexes[i] < lowerBound) { indexes[i] = (indexes[i] + upperBound) + 1; } if ((indexes[i] < lowerBound) || (indexes[i] > upperBound)) { ExecutionContext executionContextFromTLS = LocalPipeline.GetExecutionContextFromTLS(); if ((executionContextFromTLS != null) && !executionContextFromTLS.IsStrictVersion(3)) { if (!slicing) { return(null); } return(AutomationNull.Value); } } } return(array.GetValue(indexes)); }
/// <summary> /// Efficiently multiplies collection by integer. /// </summary> /// <param name="array">Collection to multiply.</param> /// <param name="times">Number of times the collection is to be multiplied/copied.</param> /// <returns>Collection multiplied by integer.</returns> internal static T[] Multiply <T>(T[] array, uint times) { Diagnostics.Assert(array != null, "Caller should verify the arguments for array multiplication"); if (times == 1) { return(array); } if (times == 0 || array.Length == 0) { #pragma warning disable CA1825 // Avoid zero-length array allocations // Don't use Array.Empty<T>(); always return a new instance. return(new T[0]); #pragma warning restore CA1825 // Avoid zero-length array allocations } var context = LocalPipeline.GetExecutionContextFromTLS(); if (context != null && context.LanguageMode == PSLanguageMode.RestrictedLanguage && (array.Length * times) > 1024) { throw InterpreterError.NewInterpreterException(times, typeof(RuntimeException), null, "ArrayMultiplyToolongInDataSection", ParserStrings.ArrayMultiplyToolongInDataSection, 1024); } var uncheckedLength = array.Length * times; int elements = -1; try { elements = checked ((int)uncheckedLength); } catch (OverflowException) { LanguagePrimitives.ThrowInvalidCastException(uncheckedLength, typeof(int)); } // Make the minimum number of calls to Array.Copy by doubling the array up to // the most significant bit in times, then do one final Array.Copy to get the // remaining copies. T[] result = new T[elements]; int resultLength = array.Length; Array.Copy(array, 0, result, 0, resultLength); times >>= 1; while (times != 0) { Array.Copy(result, 0, result, resultLength, resultLength); resultLength *= 2; times >>= 1; } if (result.Length != resultLength) { Array.Copy(result, 0, result, resultLength, (result.Length - resultLength)); } return(result); }
/// <summary> /// Constructs the MergedCommandParameterMetadata, using any arguments that /// may have been specified so that dynamic parameters can be determined, if any. /// </summary> /// <returns></returns> private MergedCommandParameterMetadata GetMergedCommandParameterMetadataSafely() { if (_context == null) { return(null); } MergedCommandParameterMetadata result; if (_context != LocalPipeline.GetExecutionContextFromTLS()) { // In the normal case, _context is from the thread we're on, and we won't get here. // But, if it's not, we can't safely get the parameter metadata without running on // on the correct thread, because that thread may be busy doing something else. // One of the things we do here is change the current scope in execution context, // that can mess up the runspace our CommandInfo object came from. var runspace = (RunspaceBase)_context.CurrentRunspace; if (runspace.CanRunActionInCurrentPipeline()) { GetMergedCommandParameterMetadata(out result); } else { _context.Events.SubscribeEvent( source: null, eventName: PSEngineEvent.GetCommandInfoParameterMetadata, sourceIdentifier: PSEngineEvent.GetCommandInfoParameterMetadata, data: null, handlerDelegate: new PSEventReceivedEventHandler(OnGetMergedCommandParameterMetadataSafelyEventHandler), supportEvent: true, forwardEvent: false, shouldQueueAndProcessInExecutionThread: true, maxTriggerCount: 1); var eventArgs = new GetMergedCommandParameterMetadataSafelyEventArgs(); _context.Events.GenerateEvent( sourceIdentifier: PSEngineEvent.GetCommandInfoParameterMetadata, sender: null, args: new[] { eventArgs }, extraData: null, processInCurrentThread: true, waitForCompletionInCurrentThread: true); if (eventArgs.Exception != null) { // An exception happened on a different thread, rethrow it here on the correct thread. eventArgs.Exception.Throw(); } return(eventArgs.Result); } } GetMergedCommandParameterMetadata(out result); return(result); }
internal static void Trace(int level, string messageId, string resourceString, params object[] args) { ExecutionContext executionContextFromTLS = LocalPipeline.GetExecutionContextFromTLS(); if (executionContextFromTLS != null) { Trace(executionContextFromTLS, level, messageId, resourceString, args); } }
private static CommandCompletion CompleteInputImpl(Ast ast, Token[] tokens, IScriptPosition positionOfCursor, Hashtable options) { PowerShell powershell = PowerShell.Create(RunspaceMode.CurrentRunspace); int replacementIndex = -1; int replacementLength = -1; List <CompletionResult> list = null; if (NeedToInvokeLegacyTabExpansion(powershell)) { Tuple <string, int, int> inputAndCursorFromAst = GetInputAndCursorFromAst(positionOfCursor); list = InvokeLegacyTabExpansion(powershell, inputAndCursorFromAst.Item1, inputAndCursorFromAst.Item2, false, out replacementIndex, out replacementLength); replacementIndex += inputAndCursorFromAst.Item3; } if ((list == null) || (list.Count == 0)) { ExecutionContext executionContextFromTLS = LocalPipeline.GetExecutionContextFromTLS(); MutableTuple tuple2 = null; foreach (CallStackFrame frame in executionContextFromTLS.Debugger.GetCallStack()) { dynamic obj2 = PSObject.AsPSObject(frame); var site1 = CallSite <Func <CallSite, object, bool> > .Create(Binder.UnaryOperation(CSharpBinderFlags.None, ExpressionType.IsTrue, typeof(CommandCompletion), new CSharpArgumentInfo[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) })); if (site1.Target(site1, obj2.Command.Equals("TabExpansion2", StringComparison.OrdinalIgnoreCase))) { tuple2 = frame.FunctionContext._localsTuple; break; } } SessionStateScope currentScope = null; if (tuple2 != null) { currentScope = executionContextFromTLS.EngineSessionState.CurrentScope; SessionStateScope parent = executionContextFromTLS.EngineSessionState.CurrentScope; while ((parent != null) && (parent.LocalsTuple != tuple2)) { parent = parent.Parent; } if (parent != null) { executionContextFromTLS.EngineSessionState.CurrentScope = parent.Parent; } } try { list = new CompletionAnalysis(ast, tokens, positionOfCursor, options).GetResults(powershell, out replacementIndex, out replacementLength); } finally { if (currentScope != null) { executionContextFromTLS.EngineSessionState.CurrentScope = currentScope; } } } return(new CommandCompletion(new Collection <CompletionResult>(list ?? EmptyCompletionResult), -1, replacementIndex, replacementLength)); }
internal static TypeTable GetTypeTableFromTLS() { ExecutionContext executionContextFromTLS = LocalPipeline.GetExecutionContextFromTLS(); if (executionContextFromTLS == null) { return(null); } return(executionContextFromTLS.TypeTable); }
private static Assembly PowerShellAssemblyResolveHandler(object sender, ResolveEventArgs args) { ExecutionContext executionContextFromTLS = LocalPipeline.GetExecutionContextFromTLS(); if (((executionContextFromTLS != null) && (executionContextFromTLS._assemblyCache != null)) && executionContextFromTLS._assemblyCache.ContainsKey(args.Name)) { return(executionContextFromTLS._assemblyCache[args.Name]); } return(null); }
internal static void Trace(int level, string messageId, params object[] args) { ExecutionContext executionContextFromTls = LocalPipeline.GetExecutionContextFromTLS(); if (executionContextFromTls == null) { return; } ScriptTrace.Trace(executionContextFromTls, level, messageId, args); }
public SessionState() { ExecutionContext executionContextFromTLS = LocalPipeline.GetExecutionContextFromTLS(); if (executionContextFromTLS == null) { throw new InvalidOperationException("ExecutionContext"); } this.sessionState = new SessionStateInternal(executionContextFromTLS); this.sessionState.PublicSessionState = this; }
/// <summary> /// This method calls all Validate attributes for the property to validate value. /// Called from class property setters with ValidateArgumentsAttribute attributes. /// </summary> /// <param name="type"></param> /// <param name="propertyName"></param> /// <param name="value"></param> public static void ValidateSetProperty(Type type, string propertyName, object value) { var validateAttributes = type.GetProperty(propertyName).GetCustomAttributes <ValidateArgumentsAttribute>(); var executionContext = LocalPipeline.GetExecutionContextFromTLS(); var engineIntrinsics = executionContext == null ? null : executionContext.EngineIntrinsics; foreach (var validateAttribute in validateAttributes) { validateAttribute.InternalValidate(value, engineIntrinsics); } }
internal SessionState(SessionStateInternal parent, bool createAsChild, bool linkToGlobal) { ExecutionContext executionContextFromTls = LocalPipeline.GetExecutionContextFromTLS(); if (executionContextFromTls == null) { throw new InvalidOperationException("ExecutionContext"); } this.sessionState = !createAsChild ? new SessionStateInternal(executionContextFromTls) : new SessionStateInternal(parent, linkToGlobal, executionContextFromTls); this.sessionState.PublicSessionState = this; }
internal void DebuggerCheckVariableWrite() { var context = SessionState != null ? SessionState.ExecutionContext : LocalPipeline.GetExecutionContextFromTLS(); if (context != null && context._debuggingMode > 0) { context.Debugger.CheckVariableWrite(Name); } }
public PSModuleInfo(bool linkToGlobal) { this._context = LocalPipeline.GetExecutionContextFromTLS(); if (this._context == null) { throw new InvalidOperationException(nameof(PSModuleInfo)); } PSModuleInfo.SetDefaultDynamicNameAndPath(this); this._sessionState = new SessionState(this._context.EngineSessionState, true, linkToGlobal); this._sessionState.Internal.Module = this; }
internal static bool IsStrictVersion(ExecutionContext context, int majorVersion) { if (context == null) { context = LocalPipeline.GetExecutionContextFromTLS(); } if (context == null) { return(false); } return(context.IsStrictVersion(majorVersion)); }
internal static SteppablePipeline GetSteppablePipeline(PipelineAst pipelineAst, CommandOrigin commandOrigin) { PipelineProcessor pipe = new PipelineProcessor(); System.Management.Automation.ExecutionContext executionContextFromTLS = LocalPipeline.GetExecutionContextFromTLS(); foreach (CommandAst ast in pipelineAst.PipelineElements.Cast <CommandAst>()) { List <CommandParameterInternal> list = new List <CommandParameterInternal>(); foreach (CommandElementAst ast2 in ast.CommandElements) { CommandParameterAst commandParameterAst = ast2 as CommandParameterAst; if (commandParameterAst != null) { list.Add(GetCommandParameter(commandParameterAst, executionContextFromTLS)); } else { ExpressionAst expressionAst = (ExpressionAst)ast2; object obj2 = Compiler.GetExpressionValue(expressionAst, executionContextFromTLS, (IList)null); bool splatted = (expressionAst is VariableExpressionAst) && ((VariableExpressionAst)expressionAst).Splatted; list.Add(CommandParameterInternal.CreateArgument(expressionAst.Extent, obj2, splatted)); } } List <CommandRedirection> list2 = new List <CommandRedirection>(); foreach (RedirectionAst ast5 in ast.Redirections) { list2.Add(GetCommandRedirection(ast5, executionContextFromTLS)); } CommandProcessorBase base2 = AddCommand(pipe, list.ToArray(), ast, list2.ToArray(), executionContextFromTLS); base2.Command.CommandOriginInternal = commandOrigin; base2.CommandScope.ScopeOrigin = commandOrigin; base2.Command.MyInvocation.CommandOrigin = commandOrigin; CallStackFrame[] frameArray = executionContextFromTLS.Debugger.GetCallStack().ToArray <CallStackFrame>(); if ((frameArray.Length > 0) && Regex.IsMatch(frameArray[0].Position.Text, "GetSteppablePipeline", RegexOptions.IgnoreCase)) { InvocationInfo myInvocation = base2.Command.MyInvocation; myInvocation.InvocationName = frameArray[0].InvocationInfo.InvocationName; if (frameArray.Length > 1) { IScriptExtent position = frameArray[1].Position; if ((position != null) && (position != PositionUtilities.EmptyExtent)) { myInvocation.DisplayScriptPosition = position; } } } if ((executionContextFromTLS.CurrentCommandProcessor != null) && (executionContextFromTLS.CurrentCommandProcessor.CommandRuntime != null)) { base2.CommandRuntime.SetMergeFromRuntime(executionContextFromTLS.CurrentCommandProcessor.CommandRuntime); } } return(new SteppablePipeline(executionContextFromTLS, pipe)); }
public WmiBaseCmdlet() { string[] strArrays = new string[1]; strArrays[0] = "localhost"; this.computerName = strArrays; this.nameSpace = "root\\cimv2"; this.impersonationLevel = ImpersonationLevel.Impersonate; this.authenticationLevel = AuthenticationLevel.Packet; this.async = false; this.throttleLimit = WmiBaseCmdlet.DEFAULT_THROTTLE_LIMIT; this._context = LocalPipeline.GetExecutionContextFromTLS(); }
public PSModuleInfo(ScriptBlock scriptBlock) { this._name = string.Empty; this._path = string.Empty; this._description = string.Empty; this._version = new System.Version(0, 0); this._detectedFunctionExports = new List <string>(); this._detectedWorkflowExports = new List <string>(); this._detectedCmdletExports = new List <string>(); this._compiledExports = new List <CmdletInfo>(); this._fileList = new List <string>(); this._moduleList = new Collection <object>(); this._nestedModules = new List <PSModuleInfo>(); this._scripts = new List <string>(); this._requiredAssemblies = new Collection <string>(); this._requiredModules = new List <PSModuleInfo>(); this._requiredModulesSpecification = new List <ModuleSpecification>(); this._detectedAliasExports = new Dictionary <string, string>(); this._exportedFormatFiles = new ReadOnlyCollection <string>(new List <string>()); this._exportedTypeFiles = new ReadOnlyCollection <string>(new List <string>()); if (scriptBlock == null) { throw PSTraceSource.NewArgumentException("scriptBlock"); } ExecutionContext executionContextFromTLS = LocalPipeline.GetExecutionContextFromTLS(); if (executionContextFromTLS == null) { throw new InvalidOperationException("PSModuleInfo"); } SetDefaultDynamicNameAndPath(this); this._sessionState = new System.Management.Automation.SessionState(executionContextFromTLS, true, true); this._sessionState.Internal.Module = this; SessionStateInternal engineSessionState = executionContextFromTLS.EngineSessionState; try { executionContextFromTLS.EngineSessionState = this._sessionState.Internal; executionContextFromTLS.SetVariable(SpecialVariables.PSScriptRootVarPath, this._path); scriptBlock = scriptBlock.Clone(true); scriptBlock.SessionState = this._sessionState; Pipe outputPipe = new Pipe { NullPipe = true }; scriptBlock.InvokeWithPipe(false, ScriptBlock.ErrorHandlingBehavior.WriteToCurrentErrorPipe, AutomationNull.Value, AutomationNull.Value, AutomationNull.Value, outputPipe, null, new object[0]); } finally { executionContextFromTLS.EngineSessionState = engineSessionState; } }
internal static BindingRestrictions GetLanguageModeCheckIfHasEverUsedConstrainedLanguage() { BindingRestrictions empty = BindingRestrictions.Empty; if (!ExecutionContext.HasEverUsedConstrainedLanguage) { return(empty); } if (LocalPipeline.GetExecutionContextFromTLS().LanguageMode == PSLanguageMode.ConstrainedLanguage) { return(BindingRestrictions.GetExpressionRestriction(Expression.Equal(Expression.Property(ExpressionCache.GetExecutionContextFromTLS, CachedReflectionInfo.ExecutionContext_LanguageMode), Expression.Constant(PSLanguageMode.ConstrainedLanguage)))); } return(BindingRestrictions.GetExpressionRestriction(Expression.NotEqual(Expression.Property(ExpressionCache.GetExecutionContextFromTLS, CachedReflectionInfo.ExecutionContext_LanguageMode), Expression.Constant(PSLanguageMode.ConstrainedLanguage)))); }
internal static TypeResolutionState GetDefaultUsingState(ExecutionContext context) { if (context == null) { context = LocalPipeline.GetExecutionContextFromTLS(); } if (context != null) { return(context.EngineSessionState.CurrentScope.TypeResolutionState); } return(TypeResolutionState.UsingSystem); }
internal ScriptBlockAst GetScriptBlockAst() { var scriptContents = ScriptContents; if (_scriptBlock == null) { this.ScriptBlock = ScriptBlock.TryGetCachedScriptBlock(_path, scriptContents); } if (_scriptBlock != null) { return((ScriptBlockAst)_scriptBlock.Ast); } if (_scriptBlockAst == null) { ParseError[] errors; Parser parser = new Parser(); // If we are in ConstrainedLanguage mode but the defining language mode is FullLanguage, then we need // to parse the script contents in FullLanguage mode context. Otherwise we will get bogus parsing errors // such as "Configuration or Class keyword not allowed". var context = LocalPipeline.GetExecutionContextFromTLS(); if (context != null && context.LanguageMode == PSLanguageMode.ConstrainedLanguage && DefiningLanguageMode == PSLanguageMode.FullLanguage) { context.LanguageMode = PSLanguageMode.FullLanguage; try { _scriptBlockAst = parser.Parse(_path, ScriptContents, null, out errors, ParseMode.Default); } finally { context.LanguageMode = PSLanguageMode.ConstrainedLanguage; } } else { _scriptBlockAst = parser.Parse(_path, ScriptContents, null, out errors, ParseMode.Default); } if (errors.Length == 0) { this.ScriptBlock = new ScriptBlock(_scriptBlockAst, isFilter: false); ScriptBlock.CacheScriptBlock(_scriptBlock.Clone(), _path, scriptContents); } } return(_scriptBlockAst); }
internal static object GetNonIndexable(object target, object[] indices) { if (indices.Length == 1) { object second = indices[0]; if ((second != null) && (LanguagePrimitives.Equals(0, second) || LanguagePrimitives.Equals(-1, second))) { return(target); } } ExecutionContext executionContextFromTLS = LocalPipeline.GetExecutionContextFromTLS(); if ((executionContextFromTLS != null) && executionContextFromTLS.IsStrictVersion(2)) { throw InterpreterError.NewInterpreterException(target, typeof(RuntimeException), null, "CannotIndex", ParserStrings.CannotIndex, new object[] { target.GetType() }); } return(AutomationNull.Value); }
internal static void CheckForSevereException(Exception e) { if ((e is AccessViolationException) || (e is StackOverflowException)) { try { if (!alreadyFailing) { alreadyFailing = true; MshLog.LogCommandHealthEvent(LocalPipeline.GetExecutionContextFromTLS(), e, Severity.Critical); } } finally { WindowsErrorReporting.FailFast(e); } } }