forked from PowerShell/PowerShell
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLocalPipeline.cs
More file actions
1485 lines (1322 loc) · 55.1 KB
/
Copy pathLocalPipeline.cs
File metadata and controls
1485 lines (1322 loc) · 55.1 KB
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.Diagnostics;
using System.Collections.Generic;
using System.Globalization;
using System.Threading;
using Microsoft.Win32;
using System.Management.Automation.Internal;
using System.Management.Automation.Internal.Host;
using System.Management.Automation.Tracing;
using Microsoft.PowerShell.Commands;
using Dbg = System.Management.Automation.Diagnostics;
namespace System.Management.Automation.Runspaces
{
/// <summary>
/// Pipeline class to be used for LocalRunspace
/// </summary>
internal sealed class LocalPipeline : PipelineBase
{
#region constructors
/// <summary>
/// Create a Pipeline with an existing command string.
/// </summary>
/// <param name="runspace">The LocalRunspace to associate with this
/// pipeline.
/// </param>
/// <param name="command">The command string to parse.</param>
/// <param name="addToHistory">if true, add pipeline to history</param>
/// <param name="isNested">True for nested pipeline</param>
internal LocalPipeline(LocalRunspace runspace, string command, bool addToHistory, bool isNested)
: base((Runspace)runspace, command, addToHistory, isNested)
{
_stopper = new PipelineStopper(this);
InitStreams();
}
/// <summary>
/// Create a Pipeline with an existing command string.
/// Caller should validate all the parameters.
/// </summary>
/// <param name="runspace">
/// The LocalRunspace to associate with this pipeline.
/// </param>
/// <param name="command">
/// The command to execute.
/// </param>
/// <param name="addToHistory">
/// If true, add the command(s) to the history list of the runspace.
/// </param>
/// <param name="isNested">
/// If true, mark this pipeline as a nested pipeline.
/// </param>
/// <param name="inputStream">
/// Stream to use for reading input objects.
/// </param>
/// <param name="errorStream">
/// Stream to use for writing error objects.
/// </param>
/// <param name="outputStream">
/// Stream to use for writing output objects.
/// </param>
/// <param name="infoBuffers">
/// Buffers used to write progress, verbose, debug, warning, information
/// information of an invocation.
/// </param>
internal LocalPipeline(LocalRunspace runspace,
CommandCollection command,
bool addToHistory,
bool isNested,
ObjectStreamBase inputStream,
ObjectStreamBase outputStream,
ObjectStreamBase errorStream,
PSInformationalBuffers infoBuffers)
: base(runspace, command, addToHistory, isNested, inputStream, outputStream, errorStream, infoBuffers)
{
_stopper = new PipelineStopper(this);
InitStreams();
}
/// <summary>
/// Copy constructor to support cloning
/// </summary>
/// <param name="pipeline">The source pipeline</param>
internal LocalPipeline(LocalPipeline pipeline)
: base((PipelineBase)(pipeline))
{
_stopper = new PipelineStopper(this);
InitStreams();
}
#endregion constructors
#region public_methods
/// <summary>
/// Creates a new <see cref="Pipeline"/> that is a copy of the current instance.
/// </summary>
/// <returns>A new <see cref="Pipeline"/> that is a copy of this instance.</returns>
public override Pipeline Copy()
{
// NTRAID#Windows Out Of Band Releases-915851-2005/09/13
if (_disposed)
{
throw PSTraceSource.NewObjectDisposedException("pipeline");
}
return (Pipeline)new LocalPipeline(this);
}
#endregion public_methods
#region private_methods
/// <summary>
/// Invoke the pipeline asynchronously with input.
/// </summary>
/// <remarks>
/// Results are returned through the <see cref="Pipeline.Output"/> reader.
/// </remarks>
protected override void StartPipelineExecution()
{
// NTRAID#Windows Out Of Band Releases-915851-2005/09/13
if (_disposed)
{
throw PSTraceSource.NewObjectDisposedException("pipeline");
}
//Note:This method is called from within a lock by parent class. There
//is no need to lock further.
//Use input stream in two cases:
//1)inputStream is open. In this case PipelineProcessor
//will call Invoke only if at least one object is added
//to inputStream.
//2)inputStream is closed but there are objects in the stream.
// NTRAID#Windows Out Of Band Releases-925566-2005/12/09-JonN
// Remember this here, in the synchronous thread,
// to avoid timing dependencies in the pipeline thread.
_useExternalInput = (InputStream.IsOpen || InputStream.Count > 0);
PSThreadOptions memberOptions = this.IsNested ? PSThreadOptions.UseCurrentThread : this.LocalRunspace.ThreadOptions;
switch (memberOptions)
{
case PSThreadOptions.Default:
case PSThreadOptions.UseNewThread:
{
#if CORECLR
//Start execution of pipeline in another thread
// No ApartmentState/ThreadStackSize In CoreCLR
Thread invokeThread = new Thread(new ThreadStart(this.InvokeThreadProc));
SetupInvokeThread(invokeThread, true);
#else
//Start execution of pipeline in another thread
// 2004/05/02-JonN Specify maxStack parameter
Thread invokeThread = new Thread(new ThreadStart(this.InvokeThreadProc), MaxStack);
SetupInvokeThread(invokeThread, true);
ApartmentState apartmentState;
if (InvocationSettings != null && InvocationSettings.ApartmentState != ApartmentState.Unknown)
{
apartmentState = InvocationSettings.ApartmentState; // set the user-defined apartmentstate.
}
else
{
apartmentState = this.LocalRunspace.ApartmentState; // use the Runspace apartment state
}
if (apartmentState != ApartmentState.Unknown)
{
invokeThread.SetApartmentState(apartmentState);
}
#endif
invokeThread.Start();
break;
}
case PSThreadOptions.ReuseThread:
{
if (this.IsNested)
{
// if this a nested pipeline we are already in the appropriate thread so we just execute the pipeline here
SetupInvokeThread(Thread.CurrentThread, true);
this.InvokeThreadProc();
}
else
{
// otherwise we execute the pipeline in the Runspace's thread
PipelineThread invokeThread = this.LocalRunspace.GetPipelineThread();
SetupInvokeThread(invokeThread.Worker, true);
invokeThread.Start(this.InvokeThreadProc);
}
break;
}
case PSThreadOptions.UseCurrentThread:
{
Thread oldNestedPipelineThread = NestedPipelineExecutionThread;
CultureInfo oldCurrentCulture = CultureInfo.CurrentCulture;
CultureInfo oldCurrentUICulture = CultureInfo.CurrentUICulture;
try
{
// prepare invoke thread
SetupInvokeThread(Thread.CurrentThread, false);
this.InvokeThreadProc();
}
finally
{
NestedPipelineExecutionThread = oldNestedPipelineThread;
Thread.CurrentThread.CurrentCulture = oldCurrentCulture;
Thread.CurrentThread.CurrentUICulture = oldCurrentUICulture;
}
break;
}
default:
Debug.Assert(false);
break;
}
}
/// <summary>
/// Prepares the invoke thread for execution
/// </summary>
private void SetupInvokeThread(Thread invokeThread, bool changeName)
{
NestedPipelineExecutionThread = invokeThread;
#if !CORECLR // No Thread.CurrentCulture In CoreCLR
invokeThread.CurrentCulture = this.LocalRunspace.ExecutionContext.EngineHostInterface.CurrentCulture;
invokeThread.CurrentUICulture = this.LocalRunspace.ExecutionContext.EngineHostInterface.CurrentUICulture;
#endif
if ((invokeThread.Name == null) && changeName) // setup the invoke thread only once
{
invokeThread.Name = "Pipeline Execution Thread";
}
}
#if !CORECLR
/// <summary>
/// Stack Reserve setting for pipeline threads
/// </summary>
internal static int MaxStack
{
get
{
int i = ReadRegistryInt("PipelineMaxStackSizeMB", 10);
if (i < 10)
i = 10; // minimum 10MB
else if (i > 100)
i = 100; // maximum 100MB
return i * 1000000;
}
}
internal static int ReadRegistryInt(string policyValueName, int defaultValue)
{
RegistryKey key;
try
{
key = Registry.LocalMachine.OpenSubKey(Utils.GetRegistryConfigurationPrefix());
}
catch (System.Security.SecurityException)
{
return defaultValue;
}
if (null == key)
return defaultValue;
object temp;
try
{
temp = key.GetValue(policyValueName);
}
catch (System.Security.SecurityException)
{
return defaultValue;
}
if (!(temp is int))
{
return defaultValue;
}
int i = (int)temp;
return i;
}
#endif
///<summary>
/// Helper method for asynchronous invoke
///<returns>Unhandled FlowControl exception if InvocationSettings.ExposeFlowControlExceptions is true.</returns>
///</summary>
private FlowControlException InvokeHelper()
{
FlowControlException flowControlException = null;
PipelineProcessor pipelineProcessor = null;
try
{
#if TRANSACTIONS_SUPPORTED
// 2004/11/08-JeffJon
//Transactions will not be supported for the Exchange release
//Add the transaction to this thread
System.Transactions.Transaction.Current = this.LocalRunspace.ExecutionContext.CurrentTransaction;
#endif
//Raise the event for Pipeline.Running
RaisePipelineStateEvents();
//Add this pipeline to history
RecordPipelineStartTime();
// Add automatic transcription, but don't transcribe nested commands
if (this.AddToHistory || !IsNested)
{
bool needToAddOutDefault = true;
CommandInfo outDefaultCommandInfo = new CmdletInfo("Out-Default", typeof(Microsoft.PowerShell.Commands.OutDefaultCommand), null, null, null);
foreach (Command command in this.Commands)
{
if (command.IsScript && (!this.IsPulsePipeline))
{
// Transcribe scripts, unless they are the pulse pipeline.
this.Runspace.GetExecutionContext.EngineHostInterface.UI.TranscribeCommand(command.CommandText, null);
}
// Don't need to add Out-Default if the pipeline already has it, or we've got a pipeline evaluating
// the PSConsoleHostReadLine command.
if (
String.Equals(outDefaultCommandInfo.Name, command.CommandText, StringComparison.OrdinalIgnoreCase) ||
String.Equals("PSConsoleHostReadLine", command.CommandText, StringComparison.OrdinalIgnoreCase) ||
String.Equals("TabExpansion2", command.CommandText, StringComparison.OrdinalIgnoreCase) ||
this.IsPulsePipeline)
{
needToAddOutDefault = false;
}
}
if (this.Runspace.GetExecutionContext.EngineHostInterface.UI.IsTranscribing)
{
if (needToAddOutDefault)
{
Command outDefaultCommand = new Command(outDefaultCommandInfo);
outDefaultCommand.Parameters.Add(new CommandParameter("Transcript", true));
outDefaultCommand.Parameters.Add(new CommandParameter("OutVariable", null));
Commands.Add(outDefaultCommand);
}
}
}
try
{
//Create PipelineProcessor to invoke this pipeline
pipelineProcessor = CreatePipelineProcessor();
}
catch (Exception ex)
{
if (this.SetPipelineSessionState)
{
SetHadErrors(true);
Runspace.ExecutionContext.AppendDollarError(ex);
}
throw;
}
//Supply input stream to PipelineProcessor
// NTRAID#Windows Out Of Band Releases-925566-2005/12/09-JonN
if (_useExternalInput)
{
pipelineProcessor.ExternalInput = InputStream.ObjectReader;
}
pipelineProcessor.ExternalSuccessOutput = OutputStream.ObjectWriter;
pipelineProcessor.ExternalErrorOutput = ErrorStream.ObjectWriter;
// Set Informational Buffers on the host only if this is not a child.
// Do not overwrite parent's informational buffers.
if (!this.IsChild)
LocalRunspace.ExecutionContext.InternalHost.
InternalUI.SetInformationalMessageBuffers(InformationalBuffers);
bool oldQuestionMarkValue = true;
bool savedIgnoreScriptDebug = this.LocalRunspace.ExecutionContext.IgnoreScriptDebug;
// preserve the trap behaviour state variable...
bool oldTrapState = this.LocalRunspace.ExecutionContext.PropagateExceptionsToEnclosingStatementBlock;
this.LocalRunspace.ExecutionContext.PropagateExceptionsToEnclosingStatementBlock = false;
try
{
//Add this pipeline to stopper
_stopper.Push(pipelineProcessor);
// Preserve the last value of $? across non-interactive commands.
if (!AddToHistory)
{
oldQuestionMarkValue = this.LocalRunspace.ExecutionContext.QuestionMarkVariableValue;
this.LocalRunspace.ExecutionContext.IgnoreScriptDebug = true;
}
else
{
this.LocalRunspace.ExecutionContext.IgnoreScriptDebug = false;
}
// Reset the redirection only if the pipeline is neither nested nor is a pulse pipeline (created by EventManager)
if (!this.IsNested && !this.IsPulsePipeline)
{
this.LocalRunspace.ExecutionContext.ResetRedirection();
}
//Invoke the pipeline.
//Note:Since we are using pipes for output, return array is
//be empty.
try
{
pipelineProcessor.SynchronousExecuteEnumerate(AutomationNull.Value);
SetHadErrors(pipelineProcessor.ExecutionFailed);
}
catch (ExitException ee)
{
// The 'exit' command was run so tell the host to exit.
// Use the finally clause to make sure that the call is actually made.
// We'll default the exit code to 1 instead or zero so that if, for some
// reason, we can't get the real error code, we'll indicate a failure.
SetHadErrors(pipelineProcessor.ExecutionFailed);
int exitCode = 1;
if (IsNested)
{
// set the global LASTEXITCODE to the value passed by exit <code>
try
{
exitCode = (int)ee.Argument;
this.LocalRunspace.ExecutionContext.SetVariable(SpecialVariables.LastExitCodeVarPath, exitCode);
}
finally
{
try
{
this.LocalRunspace.ExecutionContext.EngineHostInterface.ExitNestedPrompt();
}
catch (ExitNestedPromptException)
{
// Already at the top level so we just want to ignore this exception...
;
}
}
}
else
{
try
{
exitCode = (int)ee.Argument;
if ((InvocationSettings != null) && (InvocationSettings.ExposeFlowControlExceptions))
{
flowControlException = ee;
}
}
finally
{
this.LocalRunspace.ExecutionContext.EngineHostInterface.SetShouldExit(exitCode);
// close the remote runspaces available
/*foreach (RemoteRunspaceInfo remoteRunspaceInfo in
this.LocalRunspace.RunspaceRepository.Runspaces)
{
remoteRunspaceInfo.RemoteRunspace.CloseAsync();
}*/
}
}
}
catch (ExitNestedPromptException)
{
}
catch (FlowControlException e)
{
if ((InvocationSettings != null) && (InvocationSettings.ExposeFlowControlExceptions) &&
((e is BreakException) || (e is ContinueException) || (e is TerminateException)))
{
// Save FlowControl exception for return to caller.
flowControlException = e;
}
// Otherwise discard this type of exception generated by the debugger or from an unhandled break, continue or return.
;
}
catch (Exception)
{
// Indicate that there were errors then rethrow...
SetHadErrors(true);
throw;
}
}
finally
{
// Call StopProcessing() for all the commands.
if (pipelineProcessor != null && pipelineProcessor.Commands != null)
{
for (int i = 0; i < pipelineProcessor.Commands.Count; i++)
{
CommandProcessorBase commandProcessor = pipelineProcessor.Commands[i];
EtwActivity.SetActivityId(commandProcessor.PipelineActivityId);
// Log a command terminated event
MshLog.LogCommandLifecycleEvent(
commandProcessor.Context,
CommandState.Terminated,
commandProcessor.Command.MyInvocation);
}
}
PSLocalEventManager eventManager = LocalRunspace.Events as PSLocalEventManager;
if (eventManager != null)
{
eventManager.ProcessPendingActions();
}
// restore the trap state...
this.LocalRunspace.ExecutionContext.PropagateExceptionsToEnclosingStatementBlock = oldTrapState;
// clean the buffers on InternalHost only if this is not a child.
// Do not clear parent's informational buffers.
if (!IsChild)
LocalRunspace.ExecutionContext.InternalHost.InternalUI.SetInformationalMessageBuffers(null);
//Pop the pipeline processor from stopper.
_stopper.Pop(false);
if (!AddToHistory)
{
this.LocalRunspace.ExecutionContext.QuestionMarkVariableValue = oldQuestionMarkValue;
}
// Restore the IgnoreScriptDebug value.
this.LocalRunspace.ExecutionContext.IgnoreScriptDebug = savedIgnoreScriptDebug;
}
}
catch (FlowControlException)
{
// Discard this type of exception generated by the debugger or from an unhandled break, continue or return.
;
}
finally
{
// 2004/02/26-JonN added IDisposable to PipelineProcessor
if (null != pipelineProcessor)
{
pipelineProcessor.Dispose();
pipelineProcessor = null;
}
}
return flowControlException;
}
// NTRAID#Windows Out Of Band Releases-915506-2005/09/09
// Removed HandleUnexpectedExceptions infrastructure
/// <summary>
/// Start thread method for asynchronous pipeline execution.
/// </summary>
private void InvokeThreadProc()
{
bool incompleteParseException = false;
Runspace previousDefaultRunspace = Runspace.DefaultRunspace;
try
{
#if !CORECLR // Impersonation is not supported in CoreCLR.
// Used to store old impersonation context if we impersonate.
System.Security.Principal.WindowsImpersonationContext oldImpersonationCtxt = null;
try
{
if ((null != InvocationSettings) && (InvocationSettings.FlowImpersonationPolicy))
{
// we have a valid identity to impersonate.
System.Security.Principal.WindowsIdentity identityToImPersonate =
new System.Security.Principal.WindowsIdentity(InvocationSettings.WindowsIdentityToImpersonate.Token);
oldImpersonationCtxt = identityToImPersonate.Impersonate();
}
#endif
// Set up pipeline internal host if it is available.
if (InvocationSettings != null && InvocationSettings.Host != null)
{
InternalHost internalHost = InvocationSettings.Host as InternalHost;
if (internalHost != null) // if we are given an internal host, use the external host
{
LocalRunspace.ExecutionContext.InternalHost.SetHostRef(internalHost.ExternalHost);
}
else
{
LocalRunspace.ExecutionContext.InternalHost.SetHostRef(InvocationSettings.Host);
}
}
if (LocalRunspace.ExecutionContext.InternalHost.ExternalHost.ShouldSetThreadUILanguageToZero)
{
// BUG: 610329. Pipeline execution happens in a new thread. For
// Console applications SetThreadUILanguage(0) must be called
// inorder for the native MUI loader to load the resources correctly.
// ConsoleHost already does this in its entry point..but the same
// call is not performed in the Pipeline execution threads causing
// cmdlets that load native resources show unreadable messages on
// the console.
Microsoft.PowerShell.NativeCultureResolver.SetThreadUILanguage(0);
}
//Put Execution Context In TLS
Runspace.DefaultRunspace = this.LocalRunspace;
FlowControlException flowControlException = InvokeHelper();
if (flowControlException != null)
{
// Let pipeline propagate the BreakException.
SetPipelineState(Runspaces.PipelineState.Failed, flowControlException);
}
else
{
// Invoke finished successfully. Set state to Completed.
SetPipelineState(PipelineState.Completed);
}
#if !CORECLR
}
finally
{
// Impersonation is not supported in CoreCLR.
// This finally block is needed to handle fxcop CA2124
// If sensitive operations such as impersonation occur in the try block, and an
// exception is thrown, the filter can execute before the finally block. For the
// impersonation example, this means that the filter would execute as the impersonated user.
if (null != oldImpersonationCtxt)
{
try
{
oldImpersonationCtxt.Undo();
oldImpersonationCtxt.Dispose();
oldImpersonationCtxt = null;
}
catch (System.Security.SecurityException)
{
}
}
}
#endif
}
catch (PipelineStoppedException ex)
{
SetPipelineState(PipelineState.Stopped, ex);
}
catch (RuntimeException ex)
{
incompleteParseException = ex is IncompleteParseException;
SetPipelineState(PipelineState.Failed, ex);
SetHadErrors(true);
}
catch (ScriptCallDepthException ex)
{
SetPipelineState(PipelineState.Failed, ex);
SetHadErrors(true);
}
catch (System.Security.SecurityException ex)
{
SetPipelineState(PipelineState.Failed, ex);
SetHadErrors(true);
}
#if !CORECLR // No ThreadAbortException In CoreCLR
catch (ThreadAbortException ex)
{
SetPipelineState(PipelineState.Failed, ex);
SetHadErrors(true);
}
#endif
// 1021203-2005/05/09-JonN
// HaltCommandException will cause the command
// to stop, but not be reported as an error.
catch (HaltCommandException)
{
SetPipelineState(PipelineState.Completed);
}
finally
{
// Remove pipeline specific host if it was set.
// Win8:464422 Revert the host only if this pipeline invocation changed it
// with 464422 a nested pipeline reverts the host, although the nested pipeline did not set it.
if ((InvocationSettings != null && InvocationSettings.Host != null) &&
(LocalRunspace.ExecutionContext.InternalHost.IsHostRefSet))
{
LocalRunspace.ExecutionContext.InternalHost.RevertHostRef();
}
//Remove Execution Context From TLS
Runspace.DefaultRunspace = previousDefaultRunspace;
//If incomplete parse exception is hit, we should not add to history.
//This is ensure that in case of multiline commands, command is in the
//history only once.
if (!incompleteParseException)
{
try
{
// do not update the history if we are in the debugger and the history is locked, since that may go into a deadlock
bool skipIfLocked = LocalRunspace.ExecutionContext.Debugger.InBreakpoint;
if (_historyIdForThisPipeline == -1)
{
AddHistoryEntry(skipIfLocked);
}
else
{
UpdateHistoryEntryAddedByAddHistoryCmdlet(skipIfLocked);
}
}
// Updating the history may trigger variable breakpoints; the debugger may throw a TerminateException to
// indicate that the user wants to interrupt the variable access.
catch (TerminateException)
{
}
}
// IsChild makes it possible for LocalPipeline to differentiate
// between a true v1 nested pipeline and the "Cmdlets Calling Cmdlets" case.
//Close the output stream if it is not closed.
if (OutputStream.IsOpen && !IsChild)
{
try
{
OutputStream.Close();
}
catch (ObjectDisposedException)
{
}
}
//Close the error stream if it is not closed.
if (ErrorStream.IsOpen && !IsChild)
{
try
{
ErrorStream.Close();
}
catch (ObjectDisposedException)
{
}
}
//Close the input stream if it is not closed.
if (InputStream.IsOpen && !IsChild)
{
try
{
InputStream.Close();
}
catch (ObjectDisposedException)
{
}
}
// Clear stream links from ExecutionContext
ClearStreams();
//Runspace object maintains a list of pipelines in execution.
//Remove this pipeline from the list. This method also calls the
//pipeline finished event.
LocalRunspace.RemoveFromRunningPipelineList(this);
//If async call raise the event here. For sync invoke call,
//thread on which invoke is called will raise the event.
if (!SyncInvokeCall)
{
//This should be called after signaling PipelineFinishedEvent and
//RemoveFromRunningPipelineList. If it is done before, and in the
//Event, Runspace.Close is called which waits for pipeline to close.
//We will have deadlock
RaisePipelineStateEvents();
}
}
}
#region stop
/// <summary>
/// Stop the running pipeline.
/// </summary>
/// <param name="syncCall">If true pipeline is stoped synchronously
/// else asynchronously.</param>
protected override void ImplementStop(bool syncCall)
{
if (syncCall)
{
StopHelper();
}
else
{
Thread stopThread = new Thread(new ThreadStart(this.StopThreadProc));
stopThread.Start();
}
}
/// <summary>
/// Start method for asynchronous Stop
/// </summary>
private void StopThreadProc()
{
StopHelper();
}
private PipelineStopper _stopper;
/// <summary>
/// Gets PipelineStopper object which maintains stack of PipelineProcessor
/// for this pipeline
/// </summary>
/// <value></value>
internal PipelineStopper Stopper
{
get
{
return _stopper;
}
}
/// <summary>
/// Helper method for Stop functionality
/// </summary>
private void StopHelper()
{
// Ensure that any saved debugger stop is released
LocalRunspace.ReleaseDebugger();
//first stop all child pipelines of this pipeline
LocalRunspace.StopNestedPipelines(this);
//close the input pipe if it hasn't been closed.
//This would release the pipeline thread if it is
//waiting for input.
if (InputStream.IsOpen)
{
try
{
InputStream.Close();
}
catch (ObjectDisposedException)
{
}
}
_stopper.Stop();
//Wait for pipeline to finish
PipelineFinishedEvent.WaitOne();
}
/// <summary>
/// Returns true if pipeline is stopping
/// </summary>
/// <value></value>
internal bool IsStopping
{
get
{
return _stopper.IsStopping;
}
}
#endregion stop
/// <summary>
/// Creates a PipelineProcessor object from LocalPipeline object.
/// </summary>
/// <returns>Created PipelineProcessor object</returns>
private PipelineProcessor CreatePipelineProcessor()
{
CommandCollection commands = Commands;
if (commands == null || commands.Count == 0)
{
throw PSTraceSource.NewInvalidOperationException(RunspaceStrings.NoCommandInPipeline);
}
PipelineProcessor pipelineProcessor = new PipelineProcessor();
pipelineProcessor.TopLevel = true;
bool failed = false;
try
{
foreach (Command command in commands)
{
CommandProcessorBase commandProcessorBase;
// If CommandInfo is null, proceed with CommandDiscovery to resolve the command name
if (command.CommandInfo == null)
{
try
{
CommandOrigin commandOrigin = command.CommandOrigin;
if (IsNested)
{
commandOrigin = CommandOrigin.Internal;
}
commandProcessorBase =
command.CreateCommandProcessor
(
LocalRunspace.ExecutionContext,
AddToHistory,
commandOrigin
);
}
catch
{
// If we had an error creating a command processor and we are logging, then
// log the attempted command invocation anyways.
if (this.Runspace.GetExecutionContext.EngineHostInterface.UI.IsTranscribing)
{
// Don't need to log script commands, as they were already logged during pipeline
// setup
if (!command.IsScript)
{
this.Runspace.ExecutionContext.InternalHost.UI.TranscribeCommand(command.CommandText, null);
}
}
throw;
}
}
else
{
commandProcessorBase = CreateCommandProcessBase(command);
// Set the internal command origin member on the command object at this point...
commandProcessorBase.Command.CommandOriginInternal = CommandOrigin.Internal;
commandProcessorBase.Command.MyInvocation.InvocationName = command.CommandInfo.Name;
if (command.Parameters != null)
{
foreach (CommandParameter publicParameter in command.Parameters)
{
CommandParameterInternal internalParameter = CommandParameter.ToCommandParameterInternal(publicParameter, false);
commandProcessorBase.AddParameter(internalParameter);
}
}
}
commandProcessorBase.RedirectShellErrorOutputPipe = this.RedirectShellErrorOutputPipe;
pipelineProcessor.Add(commandProcessorBase);
}
return pipelineProcessor;
}
catch (RuntimeException)
{
failed = true;
throw;
}
catch (Exception e)
{
failed = true;
throw new RuntimeException(PipelineStrings.CannotCreatePipeline, e);
}
finally
{
if (failed)
{
this.SetHadErrors(true);
// 2004/02/26-JonN added IDisposable to PipelineProcessor
pipelineProcessor.Dispose();
}
}
}
/// <summary>
/// Resolves command.CommandInfo to an appropriate CommandProcessorBase implementation
/// </summary>
/// <param name="command">command to resolve</param>
/// <returns></returns>
private CommandProcessorBase CreateCommandProcessBase(Command command)
{
CommandInfo commandInfo = command.CommandInfo;
while (commandInfo is AliasInfo)
{
commandInfo = ((AliasInfo)commandInfo).ReferencedCommand;
}
CmdletInfo cmdletInfo = commandInfo as CmdletInfo;
if (cmdletInfo != null)
{
return new CommandProcessor(cmdletInfo, LocalRunspace.ExecutionContext);
}
IScriptCommandInfo functionInfo = commandInfo as IScriptCommandInfo;
if (functionInfo != null)
{