/
NativeCommandProcessor.cs
2439 lines (2166 loc) · 92 KB
/
NativeCommandProcessor.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.
// Licensed under the MIT License.
#pragma warning disable 1634, 1691
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Management.Automation.Internal;
using System.Management.Automation.Runspaces;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
using Microsoft.PowerShell.Telemetry;
using Dbg = System.Management.Automation.Diagnostics;
namespace System.Management.Automation
{
/// <summary>
/// Various types of input/output supported by native commands.
/// </summary>
/// <remarks>
/// Most native commands only support text. Other formats
/// are supported by minishell
/// </remarks>
internal enum NativeCommandIOFormat
{
Text,
Xml
}
/// <summary>
/// Different streams produced by minishell output.
/// </summary>
internal enum MinishellStream
{
Output,
Error,
Verbose,
Warning,
Debug,
Progress,
Information,
Unknown
}
/// <summary>
/// Helper class which holds stream names and also provide conversion
/// method.
/// </summary>
internal static class StringToMinishellStreamConverter
{
internal const string OutputStream = "output";
internal const string ErrorStream = "error";
internal const string DebugStream = "debug";
internal const string VerboseStream = "verbose";
internal const string WarningStream = "warning";
internal const string ProgressStream = "progress";
internal const string InformationStream = "information";
internal static MinishellStream ToMinishellStream(string stream)
{
Dbg.Assert(stream != null, "caller should validate the parameter");
MinishellStream ms = MinishellStream.Unknown;
if (OutputStream.Equals(stream, StringComparison.OrdinalIgnoreCase))
{
ms = MinishellStream.Output;
}
else if (ErrorStream.Equals(stream, StringComparison.OrdinalIgnoreCase))
{
ms = MinishellStream.Error;
}
else if (DebugStream.Equals(stream, StringComparison.OrdinalIgnoreCase))
{
ms = MinishellStream.Debug;
}
else if (VerboseStream.Equals(stream, StringComparison.OrdinalIgnoreCase))
{
ms = MinishellStream.Verbose;
}
else if (WarningStream.Equals(stream, StringComparison.OrdinalIgnoreCase))
{
ms = MinishellStream.Warning;
}
else if (ProgressStream.Equals(stream, StringComparison.OrdinalIgnoreCase))
{
ms = MinishellStream.Progress;
}
else if (InformationStream.Equals(stream, StringComparison.OrdinalIgnoreCase))
{
ms = MinishellStream.Information;
}
return ms;
}
}
/// <summary>
/// An output object from the child process.
/// If it's from the error stream isError will be true.
/// </summary>
internal class ProcessOutputObject
{
/// <summary>
/// Get the data from this object.
/// </summary>
/// <value>The data</value>
internal object Data { get; }
/// <summary>
/// Stream to which data belongs.
/// </summary>
internal MinishellStream Stream { get; }
/// <summary>
/// Build an output object.
/// </summary>
/// <param name="data">The data to output.</param>
/// <param name="stream">Stream to which data belongs.</param>
internal ProcessOutputObject(object data, MinishellStream stream)
{
Data = data;
Stream = stream;
}
}
#nullable enable
/// <summary>
/// This exception is used by the NativeCommandProcessor to indicate an error
/// when a native command returns a non-zero exit code.
/// </summary>
public sealed class NativeCommandExitException : RuntimeException
{
// NOTE:
// When implementing the native error action preference integration,
// reusing ApplicationFailedException was rejected.
// Instead of reusing a type already used in another scenario
// it was decided instead to use a fresh type to avoid conflating the two scenarios:
// * ApplicationFailedException: PowerShell was not able to complete execution of the application.
// * NativeCommandExitException: the application completed execution but returned a non-zero exit code.
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="NativeCommandExitException"/> class with information on the native
/// command, a specified error message and a specified error ID.
/// </summary>
/// <param name="path">The full path of the native command.</param>
/// <param name="exitCode">The exit code returned by the native command.</param>
/// <param name="processId">The process ID of the process before it ended.</param>
/// <param name="message">The error message.</param>
/// <param name="errorId">The PowerShell runtime error ID.</param>
internal NativeCommandExitException(string path, int exitCode, int processId, string message, string errorId)
: base(message)
{
SetErrorId(errorId);
SetErrorCategory(ErrorCategory.NotSpecified);
Path = path;
ExitCode = exitCode;
ProcessId = processId;
}
#endregion Constructors
/// <summary>
/// Gets the path of the native command.
/// </summary>
public string? Path { get; }
/// <summary>
/// Gets the exit code returned by the native command.
/// </summary>
public int ExitCode { get; }
/// <summary>
/// Gets the native command's process ID.
/// </summary>
public int ProcessId { get; }
}
#nullable restore
/// <summary>
/// Provides way to create and execute native commands.
/// </summary>
internal class NativeCommandProcessor : CommandProcessorBase
{
// This is the list of files which will trigger Legacy behavior if
// PSNativeCommandArgumentPassing is set to "Windows".
private static readonly IReadOnlySet<string> s_legacyFileExtensions = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
{
".js",
".wsf",
".cmd",
".bat",
".vbs",
};
// The following native commands have non-standard behavior with regard to argument passing,
// so we use Legacy argument parsing for them when PSNativeCommandArgumentPassing is set to Windows.
private static readonly IReadOnlySet<string> s_legacyCommands = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
{
"cmd",
"cscript",
"find",
"sqlcmd",
"wscript",
};
#region ctor/native command properties
/// <summary>
/// Information about application which is invoked by this instance of
/// NativeCommandProcessor.
/// </summary>
private readonly ApplicationInfo _applicationInfo;
/// <summary>
/// Initializes the new instance of NativeCommandProcessor class.
/// </summary>
/// <param name="applicationInfo">
/// The information about the application to run.
/// </param>
/// <param name="context">
/// The execution context for this command.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="applicationInfo"/> or <paramref name="context"/> is null
/// </exception>
internal NativeCommandProcessor(ApplicationInfo applicationInfo, ExecutionContext context)
: base(applicationInfo)
{
if (applicationInfo == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(applicationInfo));
}
_applicationInfo = applicationInfo;
this._context = context;
this.Command = new NativeCommand();
this.Command.CommandInfo = applicationInfo;
this.Command.Context = context;
this.Command.commandRuntime = this.commandRuntime = new MshCommandRuntime(context, applicationInfo, this.Command);
this.CommandScope = context.EngineSessionState.CurrentScope;
// provide native command a backpointer to this object.
// When kill is called on the command object,
// it calls this NCP back to kill the process...
((NativeCommand)Command).MyCommandProcessor = this;
// Create input writer for providing input to the process.
_inputWriter = new ProcessInputWriter(Command);
_isTranscribing = this.Command.Context.EngineHostInterface.UI.IsTranscribing;
}
/// <summary>
/// Gets the NativeCommand associated with this command processor.
/// </summary>
private NativeCommand nativeCommand
{
get
{
NativeCommand command = this.Command as NativeCommand;
Diagnostics.Assert(command != null, "this.Command is created in the constructor.");
return command;
}
}
/// <summary>
/// Gets or sets the name of the native command.
/// </summary>
private string NativeCommandName
{
get
{
string name = _applicationInfo.Name;
return name;
}
}
/// <summary>
/// Gets or sets path to the native command.
/// </summary>
private string Path
{
get
{
string path = _applicationInfo.Path;
return path;
}
}
internal NativeCommandProcessor DownStreamNativeCommand { get; set; }
internal bool UpstreamIsNativeCommand { get; set; }
internal BytePipe StdOutDestination { get; set; }
#endregion ctor/native command properties
#region parameter binder
/// <summary>
/// Parameter binder used by this command processor.
/// </summary>
private NativeCommandParameterBinderController _nativeParameterBinderController;
/// <summary>
/// Gets a new instance of a ParameterBinderController using a NativeCommandParameterBinder.
/// </summary>
/// <param name="command">
/// The native command to be run.
/// </param>
/// <returns>
/// A new parameter binder controller for the specified command.
/// </returns>
internal ParameterBinderController NewParameterBinderController(InternalCommand command)
{
if (_isMiniShell)
{
_nativeParameterBinderController =
new MinishellParameterBinderController(
this.nativeCommand);
}
else
{
_nativeParameterBinderController =
new NativeCommandParameterBinderController(
this.nativeCommand);
}
return _nativeParameterBinderController;
}
internal NativeCommandParameterBinderController NativeParameterBinderController
{
get
{
if (_nativeParameterBinderController == null)
{
NewParameterBinderController(this.Command);
}
return _nativeParameterBinderController;
}
}
#endregion parameter binder
#region internal overrides
/// <summary>
/// Prepares the command for execution with the specified CommandParameterInternal.
/// </summary>
internal override void Prepare(IDictionary psDefaultParameterValues)
{
// Check if the application is minishell
_isMiniShell = IsMiniShell();
// For minishell parameter binding is done in Complete method because we need
// to know if output is redirected before we can bind parameters.
if (!_isMiniShell)
{
this.NativeParameterBinderController.BindParameters(arguments);
}
try
{
InitNativeProcess();
}
catch (Exception)
{
// Do cleanup in case of exception
CleanUp(killBackgroundProcess: true);
throw;
}
}
/// <summary>
/// Executes the command. This method assumes that Prepare is already called.
/// </summary>
internal override void ProcessRecord()
{
try
{
// If upstream is a native command it'll be writing directly to our stdin stream
// so we can skip reading here.
if (!UpstreamIsNativeCommand)
{
while (Read())
{
_inputWriter.Add(Command.CurrentPipelineObject);
}
}
ConsumeAvailableNativeProcessOutput(blocking: false);
}
catch (Exception)
{
// Do cleanup in case of exception
CleanUp(killBackgroundProcess: true);
throw;
}
}
/// <summary>
/// Process object for the invoked application.
/// </summary>
private System.Diagnostics.Process _nativeProcess;
/// <summary>
/// This is used for writing input to the process.
/// </summary>
private readonly ProcessInputWriter _inputWriter = null;
/// <summary>
/// Is true if this command is to be run "standalone" - that is, with
/// no redirection.
/// </summary>
private bool _runStandAlone;
/// <summary>
/// Indicate whether we need to consider redirecting the output/error of the current native command.
/// Usually a windows program which is the last command in a pipeline can be executed as 'background' -- we don't need to capture its output/error streams.
/// </summary>
private bool _isRunningInBackground;
/// <summary>
/// Indicate if we have called 'NotifyBeginApplication()' on the host, so that
/// we can call the counterpart 'NotifyEndApplication' as appropriate.
/// </summary>
private bool _hasNotifiedBeginApplication;
/// <summary>
/// This output queue helps us keep the output and error (if redirected) order correct.
/// We could do a blocking read in the Complete block instead,
/// but then we would not be able to restore the order reasonable.
/// </summary>
private BlockingCollection<ProcessOutputObject> _nativeProcessOutputQueue;
private static bool? s_supportScreenScrape = null;
private readonly bool _isTranscribing;
private Host.Coordinates _startPosition;
/// <summary>
/// Object used for synchronization between StopProcessing thread and
/// Pipeline thread.
/// </summary>
private readonly object _sync = new object();
private SemaphoreSlim _processInitialized;
internal async Task WaitForProcessInitializationAsync(CancellationToken cancellationToken)
{
SemaphoreSlim processInitialized = _processInitialized;
if (processInitialized is null)
{
lock (_sync)
{
processInitialized = _processInitialized ??= new SemaphoreSlim(0, 1);
}
}
try
{
await processInitialized.WaitAsync(cancellationToken);
}
finally
{
processInitialized.Release();
}
}
/// <summary>
/// Creates a pipe representing the streaming of unprocessed bytes.
/// </summary>
/// <param name="stdout">
/// The stream that the pipe should represent. <see langword="true" />
/// for stdout, <see langword="false" /> for stdin.
/// </param>
/// <returns>A new byte pipe representing the specified stream.</returns>
internal BytePipe CreateBytePipe(bool stdout) => new NativeCommandProcessorBytePipe(this, stdout);
/// <summary>
/// Gets the specified base <see cref="Stream" /> for the underlying
/// <see cref="Process" />.
/// </summary>
/// <param name="stdout">
/// The stream that should be retrieved. <see langword="true" /> for
/// stdout, <see langword="false" /> for stdin.
/// </param>
/// <returns>The specified <see cref="Stream" />.</returns>
internal Stream GetStream(bool stdout)
{
Debug.Assert(
_nativeProcess is not null,
"Caller should verify that initialization has completed before attempting to get the underlying stream.");
return stdout
? _nativeProcess.StandardOutput.BaseStream
: _nativeProcess.StandardInput.BaseStream;
}
/// <summary>
/// Executes the native command once all of the input has been gathered.
/// </summary>
/// <exception cref="PipelineStoppedException">
/// The pipeline is stopping
/// </exception>
/// <exception cref="ApplicationFailedException">
/// The native command could not be run
/// </exception>
private void InitNativeProcess()
{
// Figure out if we're going to run this process "standalone" i.e. without
// redirecting anything. This is a bit tricky as we always run redirected so
// we have to see if the redirection is actually being done at the topmost level or not.
// Calculate if input and output are redirected.
bool redirectOutput;
bool redirectError;
bool redirectInput;
_startPosition = new Host.Coordinates();
bool isWindowsApplication = IsWindowsApplication(this.Path);
CalculateIORedirection(isWindowsApplication, out redirectOutput, out redirectError, out redirectInput);
// Find out if it's the only command in the pipeline.
bool soloCommand = this.Command.MyInvocation.PipelineLength == 1;
// Get the start info for the process.
ProcessStartInfo startInfo = GetProcessStartInfo(redirectOutput, redirectError, redirectInput, soloCommand);
// Send Telemetry indicating what argument passing mode we are in.
ApplicationInsightsTelemetry.SendExperimentalUseData(
"PSWindowsNativeCommandArgPassing",
NativeParameterBinderController.ArgumentPassingStyle.ToString());
#if !UNIX
string commandPath = this.Path.ToLowerInvariant();
if (commandPath.EndsWith("powershell.exe") || commandPath.EndsWith("powershell_ise.exe"))
{
// if starting Windows PowerShell, need to remove PowerShell specific segments of PSModulePath
string psmodulepath = ModuleIntrinsics.GetWindowsPowerShellModulePath();
startInfo.Environment["PSModulePath"] = psmodulepath;
// must set UseShellExecute to false if we modify the environment block
startInfo.UseShellExecute = false;
}
#endif
if (this.Command.Context.CurrentPipelineStopping)
{
throw new PipelineStoppedException();
}
Exception exceptionToRethrow = null;
try
{
// Before start the executable, tell the host, which might want to save off the
// window title or other such state as might be tweaked by the native process.
Command.Context.EngineHostInterface.NotifyBeginApplication();
_hasNotifiedBeginApplication = true;
if (_runStandAlone)
{
// Store the Raw UI coordinates so that we can scrape the screen after
// if we are transcribing.
if (_isTranscribing && (s_supportScreenScrape == true))
{
_startPosition = this.Command.Context.EngineHostInterface.UI.RawUI.CursorPosition;
_startPosition.X = 0;
}
}
// Start the process. If stop has been called, throw exception.
// Note: if StopProcessing is called which this method has the lock,
// Stop thread will wait for nativeProcess to start.
// If StopProcessing gets the lock first, then it will set the stopped
// flag and this method will throw PipelineStoppedException when it gets
// the lock.
lock (_sync)
{
if (_stopped)
{
throw new PipelineStoppedException();
}
try
{
_nativeProcess = new Process() { StartInfo = startInfo };
_nativeProcess.Start();
}
catch (Win32Exception)
{
#if UNIX
// On Unix platforms, nothing can be further done, so just throw.
throw;
#else
// On headless Windows SKUs, there is no shell to fall back to, so just throw
if (!Platform.IsWindowsDesktop)
{
throw;
}
// on Windows desktops, see if there is a file association for this command. If so then we'll use that.
string executable = Interop.Windows.FindExecutable(startInfo.FileName);
bool notDone = true;
// check to see what mode we should be in for argument passing
if (!string.IsNullOrEmpty(executable))
{
isWindowsApplication = IsWindowsApplication(executable);
if (!isWindowsApplication)
{
// Allocate a console if there isn't one attached already...
ConsoleVisibility.AllocateHiddenConsole();
}
string oldArguments = startInfo.Arguments;
string oldFileName = startInfo.FileName;
// Check to see whether this executable should be using Legacy mode argument parsing
bool useSpecialArgumentPassing = UseSpecialArgumentPassing(oldFileName);
if (useSpecialArgumentPassing)
{
startInfo.Arguments = "\"" + oldFileName + "\" " + startInfo.Arguments;
}
else
{
startInfo.ArgumentList.Insert(0, oldFileName);
}
startInfo.FileName = executable;
try
{
_nativeProcess.Start();
notDone = false;
}
catch (Win32Exception)
{
// Restore the old filename and arguments to try shell execute last...
if (useSpecialArgumentPassing)
{
startInfo.Arguments = oldArguments;
}
else
{
startInfo.ArgumentList.RemoveAt(0);
}
startInfo.FileName = oldFileName;
}
}
// We got here because there was either no executable found for this
// file or we tried to launch the exe and it failed. In either case
// we will try launching one last time using ShellExecute...
if (notDone)
{
if (soloCommand && !startInfo.UseShellExecute)
{
startInfo.UseShellExecute = true;
startInfo.RedirectStandardInput = false;
startInfo.RedirectStandardOutput = false;
startInfo.RedirectStandardError = false;
_nativeProcess.Start();
}
else
{
throw;
}
}
#endif
}
if (UpstreamIsNativeCommand)
{
_processInitialized ??= new SemaphoreSlim(0, 1);
_processInitialized.Release();
}
}
if (this.Command.MyInvocation.PipelinePosition < this.Command.MyInvocation.PipelineLength)
{
// Never background unless you're at the end of a pipe.
// Something like
// ls | notepad | sort.exe
// should block until the notepad process is terminated.
_isRunningInBackground = false;
}
else
{
_isRunningInBackground = true;
if (!startInfo.UseShellExecute)
{
_isRunningInBackground = isWindowsApplication;
}
}
try
{
// If input is redirected, start input to process.
if (startInfo.RedirectStandardInput)
{
NativeCommandIOFormat inputFormat = NativeCommandIOFormat.Text;
if (_isMiniShell)
{
inputFormat = ((MinishellParameterBinderController)NativeParameterBinderController).InputFormat;
}
lock (_sync)
{
if (!_stopped && !UpstreamIsNativeCommand)
{
_inputWriter.Start(_nativeProcess, inputFormat);
}
}
}
}
catch (Exception)
{
StopProcessing();
throw;
}
if (!_isRunningInBackground)
{
InitOutputQueue();
}
}
catch (Win32Exception e)
{
exceptionToRethrow = e;
}
catch (PipelineStoppedException)
{
// If we're stopping the process, just rethrow this exception...
throw;
}
catch (Exception e)
{
exceptionToRethrow = e;
}
// An exception was thrown while attempting to run the program
// so wrap and rethrow it here...
if (exceptionToRethrow != null)
{
// It's a system exception so wrap it in one of ours and re-throw.
string message = StringUtil.Format(ParserStrings.ProgramFailedToExecute,
this.NativeCommandName, exceptionToRethrow.Message,
this.Command.MyInvocation.PositionMessage);
ApplicationFailedException appFailedException = new ApplicationFailedException(message, exceptionToRethrow);
// There is no need to set this exception here since this exception will eventually be caught by pipeline processor.
// this.commandRuntime.PipelineProcessor.ExecutionFailed = true;
throw appFailedException;
}
}
private AsyncByteStreamTransfer _stdOutByteTransfer;
private void InitOutputQueue()
{
// if output is redirected, start reading output of process in queue.
if (_nativeProcess.StartInfo.RedirectStandardOutput || _nativeProcess.StartInfo.RedirectStandardError)
{
lock (_sync)
{
if (!_stopped)
{
if (CommandRuntime.ErrorMergeTo is MshCommandRuntime.MergeDataStream.Output)
{
StdOutDestination = null;
if (DownStreamNativeCommand is not null)
{
DownStreamNativeCommand.UpstreamIsNativeCommand = false;
DownStreamNativeCommand = null;
}
}
_nativeProcessOutputQueue = new BlockingCollection<ProcessOutputObject>();
// we don't assign the handler to anything, because it's used only for objects marshaling
BytePipe stdOutDestination = StdOutDestination ?? DownStreamNativeCommand?.CreateBytePipe(stdout: false);
BytePipe stdOutSource = null;
if (stdOutDestination is not null)
{
stdOutSource = CreateBytePipe(stdout: true);
}
_ = new ProcessOutputHandler(
_nativeProcess,
_nativeProcessOutputQueue,
stdOutDestination,
stdOutSource,
out _stdOutByteTransfer);
}
}
}
}
private ProcessOutputObject DequeueProcessOutput(bool blocking)
{
if (blocking)
{
// If adding was completed and collection is empty (IsCompleted == true)
// there is no need to do a blocking Take(), we should just return.
if (!_nativeProcessOutputQueue.IsCompleted)
{
try
{
// If adding is not complete we need a try {} catch {}
// to mitigate a concurrent call to CompleteAdding().
return _nativeProcessOutputQueue.Take();
}
catch (InvalidOperationException)
{
// It's a normal situation: another thread can mark collection as CompleteAdding
// in a concurrent way and we will rise an exception in Take().
// Although it's a normal situation it's not the most common path
// and will be executed only on the race condtion case.
}
}
return null;
}
_nativeProcessOutputQueue.TryTake(out ProcessOutputObject record);
return record;
}
/// <summary>
/// Read the output from the native process and send it down the line.
/// </summary>
private void ConsumeAvailableNativeProcessOutput(bool blocking)
{
if (_isRunningInBackground)
{
return;
}
bool stdOutRedirected = _nativeProcess.StartInfo.RedirectStandardOutput;
bool stdErrRedirected = _nativeProcess.StartInfo.RedirectStandardError;
if (stdOutRedirected && _stdOutByteTransfer is not null)
{
if (blocking)
{
_stdOutByteTransfer.EOF.GetAwaiter().GetResult();
}
if (!stdErrRedirected)
{
return;
}
}
if (stdOutRedirected || stdErrRedirected)
{
ProcessOutputObject record;
while ((record = DequeueProcessOutput(blocking)) != null)
{
if (this.Command.Context.CurrentPipelineStopping)
{
this.StopProcessing();
return;
}
ProcessOutputRecord(record);
}
}
}
internal override void Complete()
{
Exception exceptionToRethrow = null;
try
{
if (!_isRunningInBackground)
{
// Wait for input writer to finish.
if (!UpstreamIsNativeCommand || _nativeProcess.StartInfo.RedirectStandardError)
{
_inputWriter.Done();
}
// read all the available output in the blocking way
ConsumeAvailableNativeProcessOutput(blocking: true);
_nativeProcess.WaitForExit();
// Capture screen output if we are transcribing and running stand alone
if (_isTranscribing && (s_supportScreenScrape == true) && _runStandAlone)
{
Host.Coordinates endPosition = this.Command.Context.EngineHostInterface.UI.RawUI.CursorPosition;
endPosition.X = this.Command.Context.EngineHostInterface.UI.RawUI.BufferSize.Width - 1;
// If the end position is before the start position, then capture the entire buffer.
if (endPosition.Y < _startPosition.Y)
{
_startPosition.Y = 0;
}
Host.BufferCell[,] bufferContents = this.Command.Context.EngineHostInterface.UI.RawUI.GetBufferContents(
new Host.Rectangle(_startPosition, endPosition));
StringBuilder lineContents = new StringBuilder();
StringBuilder bufferText = new StringBuilder();
for (int row = 0; row < bufferContents.GetLength(0); row++)
{
if (row > 0)
{
bufferText.Append(Environment.NewLine);
}
lineContents.Clear();
for (int column = 0; column < bufferContents.GetLength(1); column++)
{
lineContents.Append(bufferContents[row, column].Character);
}
bufferText.Append(lineContents.ToString().TrimEnd(Utils.Separators.SpaceOrTab));
}
this.Command.Context.InternalHost.UI.TranscribeResult(bufferText.ToString());
}
this.Command.Context.SetVariable(SpecialVariables.LastExitCodeVarPath, _nativeProcess.ExitCode);
if (_nativeProcess.ExitCode == 0)
{
return;
}
this.commandRuntime.PipelineProcessor.ExecutionFailed = true;
// We send telemetry information only if the feature is enabled.
// This shouldn't be done once, because it's a run-time check we should send telemetry every time.
// Report on the following conditions:
// - The variable is not present
// - The value is not set (variable is null)
// - The value is set to true or false
bool useDefaultSetting;
bool nativeErrorActionPreferenceSetting = Command.Context.GetBooleanPreference(
SpecialVariables.PSNativeCommandUseErrorActionPreferenceVarPath,
defaultPref: false,
out useDefaultSetting);
// The variable is unset
if (useDefaultSetting)
{
ApplicationInsightsTelemetry.SendExperimentalUseData("PSNativeCommandErrorActionPreference", "unset");
return;
}
// Send the value that was set.
ApplicationInsightsTelemetry.SendExperimentalUseData("PSNativeCommandErrorActionPreference", nativeErrorActionPreferenceSetting.ToString());
// if it was explicitly set to false, return
if (!nativeErrorActionPreferenceSetting)
{
return;
}
const string errorId = nameof(CommandBaseStrings.ProgramExitedWithNonZeroCode);
string errorMsg = StringUtil.Format(
CommandBaseStrings.ProgramExitedWithNonZeroCode,
NativeCommandName,
_nativeProcess.ExitCode);
var exception = new NativeCommandExitException(
Path,
_nativeProcess.ExitCode,
_nativeProcess.Id,
errorMsg,
errorId);
var errorRecord = new ErrorRecord(exception, errorId, ErrorCategory.NotSpecified, targetObject: Path);
this.commandRuntime._WriteErrorSkipAllowCheck(errorRecord);
}
}
catch (Win32Exception e)
{
exceptionToRethrow = e;
}
catch (PipelineStoppedException)
{
// If we're stopping the process, just rethrow this exception...
throw;
}