forked from PowerShell/PowerShell
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ExecutionContext.cs
1729 lines (1537 loc) · 62.8 KB
/
ExecutionContext.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Management.Automation.Host;
using System.Management.Automation.Internal;
using System.Management.Automation.Internal.Host;
using System.Management.Automation.Runspaces;
using System.Runtime.CompilerServices;
using Microsoft.PowerShell;
using System.Reflection;
using System.Security;
using System.Diagnostics.CodeAnalysis;
using Microsoft.PowerShell.Commands.Internal.Format;
namespace System.Management.Automation
{
/// <summary>
/// This class contains the execution context that gets passed
/// around to commands. This is all of the information that lets you get
/// at session state and the host interfaces.
/// </summary>
internal class ExecutionContext
{
#region Properties
/// <summary>
/// The events received by this runspace
/// </summary>
internal PSLocalEventManager Events { get; private set; }
internal HashSet<String> AutoLoadingModuleInProgress { get; } = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
/// <summary>
/// The debugger for the interpreter
/// </summary>
internal ScriptDebugger Debugger
{
get { return _debugger; }
}
internal ScriptDebugger _debugger;
internal int _debuggingMode;
/// <summary>
/// Reset or clear the various context managers so the runspace can be reused without contamination.
/// </summary>
internal void ResetManagers()
{
if (_debugger != null)
{
_debugger.ResetDebugger();
}
if (Events != null)
{
Events.Dispose();
}
Events = new PSLocalEventManager(this);
if (this.transactionManager != null)
{
this.transactionManager.Dispose();
}
this.transactionManager = new PSTransactionManager();
}
/// <summary>
/// The tracing mode for the interpreter.
/// </summary>
/// <value>True if tracing is turned on, false if it's turned off.</value>
internal int PSDebugTraceLevel
{
get
{
// Pretend that tracing is off if ignoreScriptDebug is true
return IgnoreScriptDebug ? 0 : _debugTraceLevel;
}
set { _debugTraceLevel = value; }
}
private int _debugTraceLevel;
/// <summary>
/// The step mode for the interpreter.
/// </summary>
/// <value>True of stepping is turned on, false if it's turned off.</value>
internal bool PSDebugTraceStep
{
get
{
// Pretend that tracing is off if ignoreScriptDebug is true
return !IgnoreScriptDebug && _debugTraceStep;
}
set { _debugTraceStep = value; }
}
private bool _debugTraceStep;
// Helper for generated code to handle running w/ no execution context
internal static bool IsStrictVersion(ExecutionContext context, int majorVersion)
{
if (context == null)
{
context = LocalPipeline.GetExecutionContextFromTLS();
}
return (context != null)
? context.IsStrictVersion(majorVersion)
: false;
}
/// <summary>
/// Check to see a specific version of strict mode is enabled. The check is always scoped,
/// even though in version 1 the check was engine wide.
/// </summary>
/// <param name="majorVersion">The version for a strict check about to be performed.</param>
/// <returns></returns>
internal bool IsStrictVersion(int majorVersion)
{
SessionStateScope scope = EngineSessionState.CurrentScope;
while (scope != null)
{
// If StrictModeVersion is null, we haven't seen set-strictmode, so check the parent scope.
if (scope.StrictModeVersion != null)
{
// If StrictModeVersion is not null, just check the major version. A version of 0
// is the same as off to make this a simple check.
return (scope.StrictModeVersion.Major >= majorVersion);
}
// We shouldn't check global scope if we were in a module.
if (scope == EngineSessionState.ModuleScope)
{
break;
}
scope = scope.Parent;
}
// set-strictmode hasn't been used.
return false;
}
/// <summary>
/// Is true if the current statement in the interpreter should be traced...
/// </summary>
internal bool ShouldTraceStatement
{
get
{
// Pretend that tracing is off if ignoreScriptDebug is true
return !IgnoreScriptDebug && (_debugTraceLevel > 0 || _debugTraceStep);
}
}
/// <summary>
/// If true, then a script command processor should rethrow the exit exception instead of
/// simply capturing it. This is used by the -file option on the console host.
/// </summary>
internal bool ScriptCommandProcessorShouldRethrowExit { get; set; } = false;
/// <summary>
/// If this flag is set to true, script trace output
/// will not be generated regardless of the state of the
/// trace flag.
/// </summary>
/// <value>The current state of the IgnoreScriptDebug flag.</value>
internal bool IgnoreScriptDebug { set; get; } = true;
/// <summary>
/// Gets the automation engine instance.
/// </summary>
internal AutomationEngine Engine { get; private set; }
/// <summary>
/// Get the RunspaceConfiguration instance
/// </summary>
internal RunspaceConfiguration RunspaceConfiguration { get; }
internal InitialSessionState InitialSessionState { get; }
/// <summary>
/// True if the RunspaceConfiguration/InitialSessionState is for a single shell or false otherwise.
/// </summary>
///
internal bool IsSingleShell
{
get
{
RunspaceConfigForSingleShell runSpace = RunspaceConfiguration as RunspaceConfigForSingleShell;
return runSpace != null || InitialSessionState != null;
}
}
/// <summary>
/// Added for Win8: 336382
/// Contains the name of the previous module that was processed. This
/// allows you to skip this module when doing a lookup.
/// </summary>
internal string PreviousModuleProcessed { get; set; }
/// <summary>
/// Added for 4980967
/// Contains the name of the latest module that was imported,
/// Allows "module\function" to call the function from latest imported module instead of randomly choosing the first module in the moduletable.
/// </summary>
internal Hashtable previousModuleImported { get; set; } = new Hashtable();
/// <summary>
/// Contains the name of the module currently being processed. This
/// allows you to skip this module when doing a lookup.
/// </summary>
internal string ModuleBeingProcessed { get; set; }
private bool _responsibilityForModuleAnalysisAppDomainOwned;
internal bool TakeResponsibilityForModuleAnalysisAppDomain()
{
if (_responsibilityForModuleAnalysisAppDomainOwned)
{
return false;
}
Diagnostics.Assert(AppDomainForModuleAnalysis == null, "Invalid module analysis app domain state");
_responsibilityForModuleAnalysisAppDomainOwned = true;
return true;
}
internal void ReleaseResponsibilityForModuleAnalysisAppDomain()
{
Diagnostics.Assert(_responsibilityForModuleAnalysisAppDomainOwned, "Invalid module analysis app domain state");
if (AppDomainForModuleAnalysis != null)
{
AppDomain.Unload(AppDomainForModuleAnalysis);
AppDomainForModuleAnalysis = null;
}
_responsibilityForModuleAnalysisAppDomainOwned = false;
}
/// <summary>
/// The AppDomain currently being used for module analysis. It should only be created if needed,
/// but various callers need to take responsibility for unloading the domain via
/// the TakeResponsibilityForModuleAnalysisAppDomain.
/// </summary>
internal AppDomain AppDomainForModuleAnalysis { get; set; }
/// <summary>
/// Authorization manager for this runspace
/// </summary>
internal AuthorizationManager AuthorizationManager { get; private set; }
/// <summary>
/// Gets the appropriate provider names for the default
/// providers based on the type of the shell
/// (single shell or custom shell).
/// </summary>
///
internal ProviderNames ProviderNames
{
get
{
if (_providerNames == null)
{
if (IsSingleShell)
{
_providerNames = new SingleShellProviderNames();
}
else
{
_providerNames = new CustomShellProviderNames();
}
}
return _providerNames;
}
}
private ProviderNames _providerNames;
/// <summary>
/// The module information for this engine...
/// </summary>
internal ModuleIntrinsics Modules { get; private set; }
/// <summary>
/// Get the shellID for this runspace...
/// </summary>
internal string ShellID
{
get
{
if (_shellId == null)
{
// Use the ShellID from PSAuthorizationManager before everything else because that's what's used
// to check execution policy...
if (AuthorizationManager is PSAuthorizationManager && !String.IsNullOrEmpty(AuthorizationManager.ShellId))
{
_shellId = AuthorizationManager.ShellId;
}
else if (RunspaceConfiguration != null && !String.IsNullOrEmpty(RunspaceConfiguration.ShellId))
{
// Otherwise fall back to the runspace shell id if it's there...
_shellId = RunspaceConfiguration.ShellId;
}
else
{
// Finally fall back to the default shell id...
_shellId = Utils.DefaultPowerShellShellID;
}
}
return _shellId;
}
}
private string _shellId;
/// <summary>
/// Session State with which this instance of engine works
/// </summary>
///
internal SessionStateInternal EngineSessionState { get; set; }
/// <summary>
/// The default or top-level session state instance for the
/// engine.
/// </summary>
internal SessionStateInternal TopLevelSessionState { get; private set; }
/// <summary>
/// Get the SessionState facade for the internal session state APIs
/// </summary>
///
internal SessionState SessionState
{
get
{
return EngineSessionState.PublicSessionState;
}
}
/// <summary>
/// Get/set constraints for this execution environment
/// </summary>
internal PSLanguageMode LanguageMode
{
get
{
return _languageMode;
}
set
{
// If we're moving to ConstrainedLanguage, invalidate the binding
// caches. After that, the binding rules encode the language mode.
if (value == PSLanguageMode.ConstrainedLanguage)
{
ExecutionContext.HasEverUsedConstrainedLanguage = true;
HasRunspaceEverUsedConstrainedLanguageMode = true;
System.Management.Automation.Language.PSSetMemberBinder.InvalidateCache();
System.Management.Automation.Language.PSInvokeMemberBinder.InvalidateCache();
System.Management.Automation.Language.PSConvertBinder.InvalidateCache();
System.Management.Automation.Language.PSBinaryOperationBinder.InvalidateCache();
System.Management.Automation.Language.PSGetIndexBinder.InvalidateCache();
System.Management.Automation.Language.PSSetIndexBinder.InvalidateCache();
System.Management.Automation.Language.PSCreateInstanceBinder.InvalidateCache();
}
// Conversion caches don't have version info / binding rules, so must be
// cleared every time.
LanguagePrimitives.RebuildConversionCache();
_languageMode = value;
}
}
private PSLanguageMode _languageMode = PSLanguageMode.FullLanguage;
/// <summary>
/// True if this runspace has ever used constrained language mode
/// </summary>
internal bool HasRunspaceEverUsedConstrainedLanguageMode { get; private set; }
/// <summary>
/// True if we've ever used ConstrainedLanguage. If this is the case, then the binding restrictions
/// need to also validate against the language mode.
/// </summary>
internal static bool HasEverUsedConstrainedLanguage { get; private set; }
/// <summary>
/// If true the PowerShell debugger will use FullLanguage mode, otherwise it will use the current language mode
/// </summary>
internal bool UseFullLanguageModeInDebugger
{
get
{
return InitialSessionState != null ? InitialSessionState.UseFullLanguageModeInDebugger : false;
}
}
internal static List<string> ModulesWithJobSourceAdapters = new List<string>
{
Utils.WorkflowModule,
Utils.ScheduledJobModuleName,
};
/// <summary>
/// Is true the PSScheduledJob and PSWorkflow modules are loaded for this runspace
/// </summary>
internal bool IsModuleWithJobSourceAdapterLoaded
{
get; set;
}
/// <summary>
/// Gets the location globber for the session state for
/// this instance of the runspace.
/// </summary>
///
internal LocationGlobber LocationGlobber
{
get
{
_locationGlobber = new LocationGlobber(this.SessionState);
return _locationGlobber;
}
}
private LocationGlobber _locationGlobber;
/// <summary>
/// The assemblies that have been loaded for this runspace
/// </summary>
///
internal Dictionary<string, Assembly> AssemblyCache { get; private set; }
#endregion Properties
#region Engine State
/// <summary>
/// The state for current engine that is running.
/// </summary>
/// <value></value>
///
internal EngineState EngineState { get; set; } = EngineState.None;
#endregion
#region GetSetVariable methods
/// <summary>
/// Get a variable out of session state.
/// </summary>
internal object GetVariableValue(VariablePath path)
{
CmdletProviderContext context;
SessionStateScope scope;
return EngineSessionState.GetVariableValue(path, out context, out scope);
}
/// <summary>
/// Get a variable out of session state. This calls GetVariable(name) and returns the
/// value unless it is null in which case it returns the defaultValue provided by the caller
/// </summary>
internal object GetVariableValue(VariablePath path, object defaultValue)
{
CmdletProviderContext context;
SessionStateScope scope;
return EngineSessionState.GetVariableValue(path, out context, out scope) ?? defaultValue;
}
/// <summary>
/// Set a variable in session state.
/// </summary>
internal void SetVariable(VariablePath path, object newValue)
{
EngineSessionState.SetVariable(path, newValue, true, CommandOrigin.Internal);
} // SetVariable
internal T GetEnumPreference<T>(VariablePath preferenceVariablePath, T defaultPref, out bool defaultUsed)
{
CmdletProviderContext context = null;
SessionStateScope scope = null;
object val = EngineSessionState.GetVariableValue(preferenceVariablePath, out context, out scope);
if (val is T)
{
// We don't want to support "Ignore" as action preferences, as it leads to bad
// scripting habits. They are only supported as cmdlet overrides.
if (val is ActionPreference)
{
ActionPreference preference = (ActionPreference)val;
if ((preference == ActionPreference.Ignore) || (preference == ActionPreference.Suspend))
{
// Reset the variable value
EngineSessionState.SetVariableValue(preferenceVariablePath.UserPath, defaultPref);
string message = StringUtil.Format(ErrorPackage.UnsupportedPreferenceError, preference);
throw new NotSupportedException(message);
}
}
T convertedResult = (T)val;
defaultUsed = false;
return convertedResult;
}
defaultUsed = true;
T result = defaultPref;
if (val != null)
{
try
{
string valString = val as string;
if (valString != null)
{
result = (T)Enum.Parse(typeof(T), valString, true);
defaultUsed = false;
}
else
{
result = (T)PSObject.Base(val);
defaultUsed = false;
}
}
catch (InvalidCastException)
{
// default value is used
}
catch (ArgumentException)
{
// default value is used
}
}
return result;
}
/// <summary>
/// Same as GetEnumPreference, but for boolean values
/// </summary>
/// <param name="preferenceVariablePath"></param>
/// <param name="defaultPref"></param>
/// <param name="defaultUsed"></param>
/// <returns></returns>
internal bool GetBooleanPreference(VariablePath preferenceVariablePath, bool defaultPref, out bool defaultUsed)
{
CmdletProviderContext context = null;
SessionStateScope scope = null;
object val = EngineSessionState.GetVariableValue(preferenceVariablePath, out context, out scope);
if (val == null)
{
defaultUsed = true;
return defaultPref;
}
bool converted = defaultPref;
defaultUsed = !LanguagePrimitives.TryConvertTo<bool>
(val, out converted);
return (defaultUsed) ? defaultPref : converted;
}
#endregion GetSetVariable methods
#region HelpSystem
/// <summary>
/// Help system for this engine context.
/// </summary>
/// <value></value>
internal HelpSystem HelpSystem
{
get { return _helpSystem ?? (_helpSystem = new HelpSystem(this)); }
}
private HelpSystem _helpSystem;
#endregion
#region FormatAndOutput
internal Object FormatInfo { get; set; }
#endregion
internal Dictionary<string, ScriptBlock> CustomArgumentCompleters { get; set; }
internal Dictionary<string, ScriptBlock> NativeArgumentCompleters { get; set; }
private CommandFactory _commandFactory;
/// <summary>
/// Routine to create a command(processor) instance using the factory.
/// </summary>
/// <param name="command">The name of the command to lookup</param>
/// <param name="dotSource"></param>
/// <returns>The command processor object</returns>
internal CommandProcessorBase CreateCommand(string command, bool dotSource)
{
if (_commandFactory == null)
{
_commandFactory = new CommandFactory(this);
}
CommandProcessorBase commandProcessor = _commandFactory.CreateCommand(command,
this.EngineSessionState.CurrentScope.ScopeOrigin, !dotSource);
// Reset the command origin for script commands... //BUGBUG - dotting can get around command origin checks???
if (commandProcessor != null && commandProcessor is ScriptCommandProcessorBase)
commandProcessor.Command.CommandOriginInternal = CommandOrigin.Internal;
return commandProcessor;
}
/// <summary>
/// Hold the current command.
/// </summary>
/// <value>Reference to command discovery</value>
internal CommandProcessorBase CurrentCommandProcessor { get; set; }
/// <summary>
/// Redirect to the CommandDiscovery in the engine.
/// </summary>
/// <value>Reference to command discovery</value>
internal CommandDiscovery CommandDiscovery
{
get
{
return Engine.CommandDiscovery;
}
}
/// <summary>
/// Interface that should be used for interaction with host
/// </summary>
internal InternalHost EngineHostInterface { get; private set;
// set not provided: it's not meaningful to change the host post-construction.
}
/// <summary>
/// Interface to be used for interaction with internal
/// host. InternalHost wraps the host supplied
/// during construction. Use this wrapper to access
/// functionality specific to InternalHost.
/// </summary>
internal InternalHost InternalHost
{
get { return EngineHostInterface; }
}
/// <summary>
/// Interface to the public API for the engine
/// </summary>
internal EngineIntrinsics EngineIntrinsics
{
get { return _engineIntrinsics ?? (_engineIntrinsics = new EngineIntrinsics(this)); }
}
private EngineIntrinsics _engineIntrinsics;
/// <summary>
/// Log context cache
/// </summary>
internal LogContextCache LogContextCache { get; } = new LogContextCache();
#region Output pipes
/// <summary>
/// The PipelineWriter provided by the connection object for success output
/// </summary>
internal PipelineWriter ExternalSuccessOutput { get; set; }
/// <summary>
/// The PipelineWriter provided by the connection object for error output
/// </summary>
internal PipelineWriter ExternalErrorOutput { get; set; }
/// <summary>
/// The PipelineWriter provided by the connection object for progress output
/// </summary>
internal PipelineWriter ExternalProgressOutput { get; set; }
internal class SavedContextData
{
private bool _stepScript;
private bool _ignoreScriptDebug;
private int _PSDebug;
private Pipe _shellFunctionErrorOutputPipe;
public SavedContextData(ExecutionContext context)
{
_stepScript = context.PSDebugTraceStep;
_ignoreScriptDebug = context.IgnoreScriptDebug;
_PSDebug = context.PSDebugTraceLevel;
_shellFunctionErrorOutputPipe = context.ShellFunctionErrorOutputPipe;
}
public void RestoreContextData(ExecutionContext context)
{
context.PSDebugTraceStep = _stepScript;
context.IgnoreScriptDebug = _ignoreScriptDebug;
context.PSDebugTraceLevel = _PSDebug;
context.ShellFunctionErrorOutputPipe = _shellFunctionErrorOutputPipe;
}
}
/// <summary>
/// Host uses this to saves context data when entering a nested prompt
/// </summary>
/// <returns></returns>
internal SavedContextData SaveContextData()
{
return new SavedContextData(this);
}
internal void ResetShellFunctionErrorOutputPipe()
{
ShellFunctionErrorOutputPipe = null;
}
internal Pipe RedirectErrorPipe(Pipe newPipe)
{
Pipe oldPipe = ShellFunctionErrorOutputPipe;
ShellFunctionErrorOutputPipe = newPipe;
return oldPipe;
}
internal void RestoreErrorPipe(Pipe pipe)
{
ShellFunctionErrorOutputPipe = pipe;
}
/// <summary>
/// Reset all of the redirection book keeping variables. This routine should be called when starting to
/// execute a script.
/// </summary>
internal void ResetRedirection()
{
ShellFunctionErrorOutputPipe = null;
}
/// <summary>
/// Function and Script command processors will route their error output to
/// this pipe if set, unless explicitly routed elsewhere. We also keep track
/// of the first time this value is set so we can know if it's the default
/// error output or not.
/// </summary>
internal Pipe ShellFunctionErrorOutputPipe { get; set; }
/// <summary>
/// Supports expression Warning output redirection.
/// </summary>
internal Pipe ExpressionWarningOutputPipe { get; set; }
/// <summary>
/// Supports expression Verbose output redirection.
/// </summary>
internal Pipe ExpressionVerboseOutputPipe { get; set; }
/// <summary>
/// Supports expression Verbose output redirection.
/// </summary>
internal Pipe ExpressionDebugOutputPipe { get; set; }
/// <summary>
/// Supports expression Information output redirection.
/// </summary>
internal Pipe ExpressionInformationOutputPipe { get; set; }
#endregion Output pipes
#region Append to $error
/// <summary>
/// Appends the object to $global:error if it's an error record or exception.
/// </summary>
/// <param name="obj">
/// ErrorRecord or Exception to be written to $global:error
/// </param>
/// <exception cref="ExtendedTypeSystemException">
/// (get-only) An error occurred accessing $ERROR.
/// </exception>
internal void AppendDollarError(object obj)
{
ErrorRecord objAsErrorRecord = obj as ErrorRecord;
if (objAsErrorRecord == null && !(obj is Exception))
{
Diagnostics.Assert(false, "Object to append was neither an ErrorRecord nor an Exception in ExecutionContext.AppendDollarError");
return;
}
object old = this.DollarErrorVariable;
ArrayList arraylist = old as ArrayList;
if (null == arraylist)
{
Diagnostics.Assert(false, "$error should be a global constant ArrayList");
return;
}
// Don't add the same exception twice...
if (arraylist.Count > 0)
{
// There may be exceptions stored directly in which case
// the direct comparison will catch them...
if (arraylist[0] == obj)
return;
// otherwise check the exception members of the error records...
ErrorRecord er1 = arraylist[0] as ErrorRecord;
if (er1 != null && objAsErrorRecord != null && er1.Exception == objAsErrorRecord.Exception)
return;
}
const int maxErrorCount = 256;
int numToErase = arraylist.Count - (maxErrorCount - 1);
if (0 < numToErase)
{
arraylist.RemoveRange(
maxErrorCount - 1,
numToErase);
}
arraylist.Insert(0, obj);
} // AppendDollarError
#endregion
#region Scope or Commands (in pipeline) Depth Count
/// <summary>
/// Check if the stack would overflow soon, if so, throw ScriptCallDepthException.
/// </summary>
/// <exception cref="ScriptCallDepthException">
/// If the stack would overflow soon.
/// </exception>
internal static void CheckStackDepth()
{
try
{
RuntimeHelpers.EnsureSufficientExecutionStack();
}
catch (InsufficientExecutionStackException)
{
throw new ScriptCallDepthException();
}
}
#endregion
/// <summary>
/// The current connection object
/// </summary>
private Runspace _currentRunspace;
//This should be internal, but it need to be friend of remoting dll.
/// <summary>
/// The current connection object
/// </summary>
internal Runspace CurrentRunspace
{
get { return _currentRunspace; }
set { _currentRunspace = value; }
}
/// <summary>
/// Each pipeline has a stack of pipeline processor. This method
/// pushes pp in to stack for currently executing pipeline.
/// </summary>
/// <param name="pp"></param>
internal void PushPipelineProcessor(PipelineProcessor pp)
{
if (_currentRunspace == null)
return;
LocalPipeline lpl = (LocalPipeline)((RunspaceBase)_currentRunspace).GetCurrentlyRunningPipeline();
if (lpl == null)
return;
lpl.Stopper.Push(pp);
}
/// <summary>
/// Each pipeline has a stack of pipeline processor. This method pops the
/// top item from the stack
/// </summary>
internal void PopPipelineProcessor(bool fromSteppablePipeline)
{
if (_currentRunspace == null)
return;
LocalPipeline lpl = (LocalPipeline)((RunspaceBase)_currentRunspace).GetCurrentlyRunningPipeline();
if (lpl == null)
return;
lpl.Stopper.Pop(fromSteppablePipeline);
}
/// <summary>
/// This flag is checked by parser to stop loops etc.
/// </summary>
/// <returns></returns>
internal bool CurrentPipelineStopping
{
get
{
if (_currentRunspace == null)
return false;
LocalPipeline lpl = (LocalPipeline)((RunspaceBase)_currentRunspace).GetCurrentlyRunningPipeline();
if (lpl == null)
return false;
return lpl.IsStopping;
}
}
/// <summary>
/// True means one of these:
/// 1) there is a trap statement in a dynamically enclosing statement block that might catch an exception.
/// 2) execution happens inside a PS class and exceptions should be propagated all the way up, even if there is no enclosing try-catch-finally.
/// </summary>
/// <value></value>
internal bool PropagateExceptionsToEnclosingStatementBlock { get; set; }
internal RuntimeException CurrentExceptionBeingHandled { get; set; }
/// <summary>
/// Shortcut to get at $?
/// </summary>
/// <value>The current value of $? </value>
internal bool QuestionMarkVariableValue { get; set; } = true;
/// <summary>
/// Shortcut to get at $error
/// </summary>
/// <value>The current value of $global:error </value>
internal object DollarErrorVariable
{
get
{
CmdletProviderContext context = null;
SessionStateScope scope = null;
object resultItem = null;
if (!Events.IsExecutingEventAction)
{
resultItem = EngineSessionState.GetVariableValue(
SpecialVariables.ErrorVarPath, out context, out scope);
}
else
{
resultItem = EngineSessionState.GetVariableValue(
SpecialVariables.EventErrorVarPath, out context, out scope);
}
return resultItem;
}
set
{
EngineSessionState.SetVariable(
SpecialVariables.ErrorVarPath, value, true, CommandOrigin.Internal);
}
}
internal ActionPreference DebugPreferenceVariable
{
get
{
bool defaultUsed = false;
return this.GetEnumPreference<ActionPreference>(
SpecialVariables.DebugPreferenceVarPath,
InitialSessionState.defaultDebugPreference,
out defaultUsed);
}
set
{
this.EngineSessionState.SetVariable(
SpecialVariables.DebugPreferenceVarPath,
LanguagePrimitives.ConvertTo(value, typeof(ActionPreference), CultureInfo.InvariantCulture),
true,
CommandOrigin.Internal);
}
}
internal ActionPreference VerbosePreferenceVariable
{
get
{
bool defaultUsed = false;
return this.GetEnumPreference<ActionPreference>(
SpecialVariables.VerbosePreferenceVarPath,
InitialSessionState.defaultVerbosePreference,
out defaultUsed);
}
set
{
this.EngineSessionState.SetVariable(
SpecialVariables.VerbosePreferenceVarPath,
LanguagePrimitives.ConvertTo(value, typeof(ActionPreference), CultureInfo.InvariantCulture),
true,
CommandOrigin.Internal);
}
}
internal ActionPreference ErrorActionPreferenceVariable
{
get
{
bool defaultUsed = false;
return this.GetEnumPreference<ActionPreference>(
SpecialVariables.ErrorActionPreferenceVarPath,
InitialSessionState.defaultErrorActionPreference,
out defaultUsed);
}
set
{
this.EngineSessionState.SetVariable(