-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
ToolTask.cs
1772 lines (1555 loc) · 75.3 KB
/
ToolTask.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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Resources;
using System.Text;
using System.Threading;
using Microsoft.Build.Framework;
using Microsoft.Build.Shared;
using Microsoft.Build.Shared.FileSystem;
#nullable disable
namespace Microsoft.Build.Utilities
{
/// <summary>
/// The return value from InitializeHostObject. This enumeration defines what action the ToolTask
/// should take next, after we've tried to initialize the host object.
/// </summary>
public enum HostObjectInitializationStatus
{
/// <summary>
/// This means that there exists an appropriate host object for this task, it can support
/// all of the parameters passed in, and it should be invoked to do the real work of the task.
/// </summary>
UseHostObjectToExecute,
/// <summary>
/// This means that either there is no host object available, or that the host object is
/// not capable of supporting all of the features required for this build. Therefore,
/// ToolTask should fallback to an alternate means of doing the build, such as invoking
/// the command-line tool.
/// </summary>
UseAlternateToolToExecute,
/// <summary>
/// This means that the host object is already up-to-date, and no further action is necessary.
/// </summary>
NoActionReturnSuccess,
/// <summary>
/// This means that some of the parameters being passed into the task are invalid, and the
/// task should fail immediately.
/// </summary>
NoActionReturnFailure
}
/// <summary>
/// Base class used for tasks that spawn an executable. This class implements the ToolPath property which can be used to
/// override the default path.
/// </summary>
// INTERNAL WARNING: DO NOT USE the Log property in this class! Log points to resources in the task assembly itself, and
// we want to use resources from Utilities. Use LogPrivate (for private Utilities resources) and LogShared (for shared MSBuild resources)
public abstract class ToolTask : Task, IIncrementalTask, ICancelableTask
{
private static readonly bool s_preserveTempFiles = string.Equals(Environment.GetEnvironmentVariable("MSBUILDPRESERVETOOLTEMPFILES"), "1", StringComparison.Ordinal);
#region Constructors
/// <summary>
/// Protected constructor
/// </summary>
protected ToolTask()
{
LogPrivate = new TaskLoggingHelper(this)
{
TaskResources = AssemblyResources.PrimaryResources,
HelpKeywordPrefix = "MSBuild."
};
LogShared = new TaskLoggingHelper(this)
{
TaskResources = AssemblyResources.SharedResources,
HelpKeywordPrefix = "MSBuild."
};
// 5 second is the default termination timeout.
TaskProcessTerminationTimeout = 5000;
ToolCanceled = new ManualResetEvent(false);
}
/// <summary>
/// Protected constructor
/// </summary>
/// <param name="taskResources">The resource manager for task resources</param>
protected ToolTask(ResourceManager taskResources)
: this()
{
TaskResources = taskResources;
}
/// <summary>
/// Protected constructor
/// </summary>
/// <param name="taskResources">The resource manager for task resources</param>
/// <param name="helpKeywordPrefix">The help keyword prefix for task's messages</param>
protected ToolTask(ResourceManager taskResources, string helpKeywordPrefix)
: this(taskResources)
{
HelpKeywordPrefix = helpKeywordPrefix;
}
#endregion
#region Properties
/// <summary>
/// The return code of the spawned process. If the task logged any errors, but the process
/// had an exit code of 0 (success), this will be set to -1.
/// </summary>
[Output]
public int ExitCode { get; private set; }
/// <summary>
/// When set to true, this task will yield the node when its task is executing.
/// </summary>
public bool YieldDuringToolExecution { get; set; }
/// <summary>
/// When set to true, the tool task will create a batch file for the command-line and execute that using the command-processor,
/// rather than executing the command directly.
/// </summary>
public bool UseCommandProcessor { get; set; }
/// <summary>
/// When set to true, it passes /Q to the cmd.exe command line such that the command line does not get echo-ed on stdout
/// </summary>
public bool EchoOff { get; set; }
/// <summary>
/// A timeout to wait for a task to terminate before killing it. In milliseconds.
/// </summary>
protected int TaskProcessTerminationTimeout { get; set; }
/// <summary>
/// Used to signal when a tool has been cancelled.
/// </summary>
protected ManualResetEvent ToolCanceled { get; private set; }
/// <summary>
/// This is the batch file created when UseCommandProcessor is set to true.
/// </summary>
private string _temporaryBatchFile;
/// <summary>
/// The encoding set to the console code page.
/// </summary>
private Encoding _encoding;
/// <summary>
/// Implemented by the derived class. Returns a string which is the name of the underlying .EXE to run e.g. "resgen.exe"
/// Only used by the ToolExe getter.
/// </summary>
/// <value>Name of tool.</value>
protected abstract string ToolName { get; }
/// <summary>
/// Projects may set this to override a task's ToolName.
/// Tasks may override this to prevent that.
/// </summary>
public virtual string ToolExe
{
get
{
if (!string.IsNullOrEmpty(_toolExe))
{
// If the ToolExe has been overridden then return the value
return _toolExe;
}
else
{
// We have no override, so simply delegate to ToolName
return ToolName;
}
}
set => _toolExe = value;
}
/// <summary>
/// Project-visible property allows the user to override the path to the executable.
/// </summary>
/// <value>Path to tool.</value>
public string ToolPath { set; get; }
/// <summary>
/// Whether or not to use UTF8 encoding for the cmd file and console window.
/// Values: Always, Never, Detect
/// If set to Detect, the current code page will be used unless it cannot represent
/// the Command string. In that case, UTF-8 is used.
/// </summary>
public string UseUtf8Encoding { get; set; } = EncodingUtilities.UseUtf8Detect;
/// <summary>
/// Array of equals-separated pairs of environment
/// variables that should be passed to the spawned executable,
/// in addition to (or selectively overriding) the regular environment block.
/// </summary>
/// <remarks>
/// Using this instead of EnvironmentOverride as that takes a Dictionary,
/// which cannot be set from an MSBuild project.
/// </remarks>
public string[] EnvironmentVariables { get; set; }
/// <summary>
/// Project visible property that allows the user to specify an amount of time after which the task executable
/// is terminated.
/// </summary>
/// <value>Time-out in milliseconds. Default is <see cref="System.Threading.Timeout.Infinite"/> (no time-out).</value>
public virtual int Timeout { set; get; } = System.Threading.Timeout.Infinite;
/// <summary>
/// Overridable property specifying the encoding of the response file, UTF8 by default
/// </summary>
protected virtual Encoding ResponseFileEncoding => Encoding.UTF8;
/// <summary>
/// Overridable method to escape content of the response file
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "string", Justification = "Shipped this way in Dev11 Beta (go-live)")]
protected virtual string ResponseFileEscape(string responseString) => responseString;
/// <summary>
/// Overridable property specifying the encoding of the captured task standard output stream
/// </summary>
/// <remarks>
/// Console-based output uses the current system OEM code page by default. Note that we should not use Console.OutputEncoding
/// here since processes we run don't really have much to do with our console window (and also Console.OutputEncoding
/// doesn't return the OEM code page if the running application that hosts MSBuild is not a console application).
/// </remarks>
protected virtual Encoding StandardOutputEncoding
{
get
{
if (ChangeWaves.AreFeaturesEnabled(ChangeWaves.Wave17_10))
{
if (_encoding != null)
{
// Keep the encoding of standard output & error consistent with the console code page.
return _encoding;
}
}
return EncodingUtilities.CurrentSystemOemEncoding;
}
}
/// <summary>
/// Overridable property specifying the encoding of the captured task standard error stream
/// </summary>
/// <remarks>
/// Console-based output uses the current system OEM code page by default. Note that we should not use Console.OutputEncoding
/// here since processes we run don't really have much to do with our console window (and also Console.OutputEncoding
/// doesn't return the OEM code page if the running application that hosts MSBuild is not a console application).
/// </remarks>
protected virtual Encoding StandardErrorEncoding
{
get
{
if (ChangeWaves.AreFeaturesEnabled(ChangeWaves.Wave17_10))
{
if (_encoding != null)
{
// Keep the encoding of standard output & error consistent with the console code page.
return _encoding;
}
}
return EncodingUtilities.CurrentSystemOemEncoding;
}
}
/// <summary>
/// Gets the Path override value.
/// </summary>
/// <returns>The new value for the Environment for the task.</returns>
[Obsolete("Use EnvironmentVariables property")]
protected virtual Dictionary<string, string> EnvironmentOverride => null;
/// <summary>
/// Importance with which to log text from the
/// standard error stream.
/// </summary>
protected virtual MessageImportance StandardErrorLoggingImportance => MessageImportance.Normal;
/// <summary>
/// Whether this ToolTask has logged any errors
/// </summary>
protected virtual bool HasLoggedErrors => Log.HasLoggedErrors || LogPrivate.HasLoggedErrors || LogShared.HasLoggedErrors;
/// <summary>
/// Task Parameter: Importance with which to log text from the
/// standard out stream.
/// </summary>
public string StandardOutputImportance { get; set; } = null;
/// <summary>
/// Task Parameter: Importance with which to log text from the
/// standard error stream.
/// </summary>
public string StandardErrorImportance { get; set; } = null;
/// <summary>
/// Should ALL messages received on the standard error stream be logged as errors.
/// </summary>
public bool LogStandardErrorAsError { get; set; } = false;
/// <summary>
/// Importance with which to log text from in the
/// standard out stream.
/// </summary>
protected virtual MessageImportance StandardOutputLoggingImportance => MessageImportance.Low;
/// <summary>
/// The actual importance at which standard out messages will be logged.
/// </summary>
protected MessageImportance StandardOutputImportanceToUse => _standardOutputImportanceToUse;
/// <summary>
/// The actual importance at which standard error messages will be logged.
/// </summary>
protected MessageImportance StandardErrorImportanceToUse => _standardErrorImportanceToUse;
#endregion
#region Private properties
/// <summary>
/// Gets an instance of a private TaskLoggingHelper class containing task logging methods.
/// This is necessary because ToolTask lives in a different assembly than the task inheriting from it
/// and needs its own separate resources.
/// </summary>
/// <value>The logging helper object.</value>
private TaskLoggingHelper LogPrivate { get; }
// the private logging helper
/// <summary>
/// Gets an instance of a shared resources TaskLoggingHelper class containing task logging methods.
/// This is necessary because ToolTask lives in a different assembly than the task inheriting from it
/// and needs its own separate resources.
/// </summary>
/// <value>The logging helper object.</value>
private TaskLoggingHelper LogShared { get; }
// the shared resources logging helper
#endregion
#region Overridable methods
/// <summary>
/// Overridable function called after <see cref="Process.Start()"/> in <see cref="ExecuteTool"/>
/// </summary>
protected virtual void ProcessStarted() { }
/// <summary>
/// Gets the fully qualified tool name. Should return ToolExe if ToolTask should search for the tool
/// in the system path. If ToolPath is set, this is ignored.
/// </summary>
/// <returns>Path string.</returns>
protected abstract string GenerateFullPathToTool();
/// <summary>
/// Gets the working directory to use for the process. Should return null if ToolTask should use the
/// current directory.
/// </summary>
/// <remarks>This is a method rather than a property so that derived classes (like Exec) can choose to
/// expose a public WorkingDirectory property, and it would be confusing to have two properties.</remarks>
/// <returns></returns>
protected virtual string GetWorkingDirectory() => null;
/// <summary>
/// Implemented in the derived class
/// </summary>
/// <returns>true, if successful</returns>
protected internal virtual bool ValidateParameters()
{
if (TaskProcessTerminationTimeout < -1)
{
Log.LogWarningWithCodeFromResources("ToolTask.InvalidTerminationTimeout", TaskProcessTerminationTimeout);
return false;
}
return true;
}
/// <summary>
/// Returns true if task execution is not necessary. Executed after ValidateParameters
/// </summary>
/// <returns></returns>
protected virtual bool SkipTaskExecution() { canBeIncremental = false; return false; }
/// <summary>
/// ToolTask is not incremental by default. When a derived class overrides SkipTaskExecution, then Question feature can take into effect.
/// </summary>
protected bool canBeIncremental { get; set; } = true;
public bool FailIfNotIncremental { get; set; }
/// <summary>
/// Returns a string with those switches and other information that can go into a response file.
/// Called after ValidateParameters and SkipTaskExecution
/// </summary>
/// <returns></returns>
protected virtual string GenerateResponseFileCommands() => string.Empty; // Default is nothing. This is useful for tools that don't need or support response files.
/// <summary>
/// Returns a string with those switches and other information that can't go into a response file and
/// must go directly onto the command line.
/// Called after ValidateParameters and SkipTaskExecution
/// </summary>
/// <returns></returns>
protected virtual string GenerateCommandLineCommands() => string.Empty; // Default is nothing. This is useful for tools where all the parameters can go into a response file.
/// <summary>
/// Returns the command line switch used by the tool executable to specify the response file.
/// Will only be called if the task returned a non empty string from GetResponseFileCommands
/// Called after ValidateParameters, SkipTaskExecution and GetResponseFileCommands
/// </summary>
/// <param name="responseFilePath">full path to the temporarily created response file</param>
/// <returns></returns>
protected virtual string GetResponseFileSwitch(string responseFilePath) => "@\"" + responseFilePath + "\""; // by default, return @"<responseFilePath>"
/// <summary>
/// Allows tool to handle the return code.
/// This method will only be called with non-zero exitCode.
/// </summary>
/// <returns>The return value of this method will be used as the task return value</returns>
protected virtual bool HandleTaskExecutionErrors()
{
Debug.Assert(ExitCode != 0, "HandleTaskExecutionErrors should only be called if there were problems executing the task");
if (HasLoggedErrors)
{
// Emit a message.
LogPrivate.LogMessageFromResources(MessageImportance.Low, "General.ToolCommandFailedNoErrorCode", ExitCode);
}
else
{
// If the tool itself did not log any errors on its own, then we log one now simply saying
// that the tool exited with a non-zero exit code. This way, the customer nevers sees
// "Build failed" without at least one error being logged.
LogPrivate.LogErrorWithCodeFromResources("ToolTask.ToolCommandFailed", ToolExe, ExitCode);
}
// by default, always fail the task
return false;
}
/// <summary>
/// We expect the tasks to override this method, if they support host objects. The implementation should call into the
/// host object to perform the real work of the task. For example, for compiler tasks like Csc and Vbc, this method would
/// call Compile() on the host object.
/// </summary>
/// <returns>The return value indicates success (true) or failure (false) if the host object was actually called to do the work.</returns>
protected virtual bool CallHostObjectToExecute() => false;
/// <summary>
/// We expect tasks to override this method if they support host objects. The implementation should
/// make sure that the host object is ready to perform the real work of the task.
/// </summary>
/// <returns>The return value indicates what steps to take next. The default is to assume that there
/// is no host object provided, and therefore we should fallback to calling the command-line tool.</returns>
protected virtual HostObjectInitializationStatus InitializeHostObject() => HostObjectInitializationStatus.UseAlternateToolToExecute;
/// <summary>
/// Logs the actual command line about to be executed (or what the task wants the log to show)
/// </summary>
/// <param name="message">
/// Descriptive message about what is happening - usually the command line to be executed.
/// </param>
protected virtual void LogToolCommand(string message) => LogPrivate.LogCommandLine(MessageImportance.High, message); // Log a descriptive message about what's happening.
/// <summary>
/// Logs the tool name and the path from where it is being run.
/// </summary>
/// <param name="toolName">
/// The tool to Log. This is the actual tool being used, ie. if ToolExe has been specified it will be used, otherwise it will be ToolName
/// </param>
/// <param name="pathToTool">
/// The path from where the tool is being run.
/// </param>
protected virtual void LogPathToTool(string toolName, string pathToTool)
{
// We don't do anything here any more, as it was just duplicative and noise.
// The method only remains for backwards compatibility - to avoid breaking tasks that override it
}
#endregion
#region Methods
/// <summary>
/// Figures out the path to the tool (including the .exe), either by using the ToolPath
/// parameter, or by asking the derived class to tell us where it should be located.
/// </summary>
/// <returns>path to the tool, or null</returns>
private string ComputePathToTool()
{
string pathToTool = null;
if (UseCommandProcessor)
{
return ToolExe;
}
if (!string.IsNullOrEmpty(ToolPath))
{
// If the project author passed in a ToolPath, always use that.
pathToTool = Path.Combine(ToolPath, ToolExe);
}
if (string.IsNullOrWhiteSpace(pathToTool) || (ToolPath == null && !FileSystems.Default.FileExists(pathToTool)))
{
// Otherwise, try to find the tool ourselves.
pathToTool = GenerateFullPathToTool();
// We have no toolpath, but we have been given an override
// for the tool exe, fix up the path, assuming that the tool is in the same location
if (pathToTool != null && !string.IsNullOrEmpty(_toolExe))
{
string directory = Path.GetDirectoryName(pathToTool);
pathToTool = Path.Combine(directory, ToolExe);
}
}
// only look for the file if we have a path to it. If we have just the file name, we'll
// look for it in the path
if (pathToTool != null)
{
bool isOnlyFileName = Path.GetFileName(pathToTool).Length == pathToTool.Length;
if (!isOnlyFileName)
{
bool isExistingFile = FileSystems.Default.FileExists(pathToTool);
if (!isExistingFile)
{
LogPrivate.LogErrorWithCodeFromResources("ToolTask.ToolExecutableNotFound", pathToTool);
return null;
}
}
else
{
// if we just have the file name, search for the file on the system path
string actualPathToTool = FindOnPath(pathToTool);
// if we find the file
if (actualPathToTool != null)
{
// point to it
pathToTool = actualPathToTool;
}
else
{
// if we cannot find the file, we'll probably error out later on when
// we try to launch the tool; so do nothing for now
}
}
}
return pathToTool;
}
/// <summary>
/// Creates a temporary response file for the given command line arguments.
/// We put as many command line arguments as we can into a response file to
/// prevent the command line from getting too long. An overly long command
/// line can cause the process creation to fail.
/// </summary>
/// <remarks>
/// Command line arguments that cannot be put into response files, and which
/// must appear on the command line, should not be passed to this method.
/// </remarks>
/// <param name="responseFileCommands">The command line arguments that need
/// to go into the temporary response file.</param>
/// <param name="responseFileSwitch">[out] The command line switch for using
/// the temporary response file, or null if the response file is not needed.
/// </param>
/// <returns>The path to the temporary response file, or null if the response
/// file is not needed.</returns>
private string GetTemporaryResponseFile(string responseFileCommands, out string responseFileSwitch)
{
string responseFile = null;
responseFileSwitch = null;
// if this tool supports response files
if (!string.IsNullOrEmpty(responseFileCommands))
{
// put all the parameters into a temporary response file so we don't
// have to worry about how long the command-line is going to be
// May throw IO-related exceptions
responseFile = FileUtilities.GetTemporaryFileName(".rsp");
// Use the encoding specified by the overridable ResponseFileEncoding property
using (StreamWriter responseFileStream = FileUtilities.OpenWrite(responseFile, false, ResponseFileEncoding))
{
responseFileStream.Write(ResponseFileEscape(responseFileCommands));
}
responseFileSwitch = GetResponseFileSwitch(responseFile);
}
return responseFile;
}
/// <summary>
/// Initializes the information required to spawn the process executing the tool.
/// </summary>
/// <param name="pathToTool"></param>
/// <param name="commandLineCommands"></param>
/// <param name="responseFileSwitch"></param>
/// <returns>The information required to start the process.</returns>
protected virtual ProcessStartInfo GetProcessStartInfo(
string pathToTool,
string commandLineCommands,
string responseFileSwitch)
{
// Build up the command line that will be spawned.
string commandLine = commandLineCommands;
if (!UseCommandProcessor)
{
if (!string.IsNullOrEmpty(responseFileSwitch))
{
commandLine += " " + responseFileSwitch;
}
}
// If the command is too long, it will most likely fail. The command line
// arguments passed into any process cannot exceed 32768 characters, but
// depending on the structure of the command (e.g. if it contains embedded
// environment variables that will be expanded), longer commands might work,
// or shorter commands might fail -- to play it safe, we warn at 32000.
// NOTE: cmd.exe has a buffer limit of 8K, but we're not using cmd.exe here,
// so we can go past 8K easily.
if (commandLine.Length > 32000)
{
LogPrivate.LogWarningWithCodeFromResources("ToolTask.CommandTooLong", GetType().Name);
}
ProcessStartInfo startInfo = new ProcessStartInfo(pathToTool, commandLine);
startInfo.CreateNoWindow = true;
startInfo.UseShellExecute = false;
startInfo.RedirectStandardError = true;
startInfo.RedirectStandardOutput = true;
// ensure the redirected streams have the encoding we want
startInfo.StandardErrorEncoding = StandardErrorEncoding;
startInfo.StandardOutputEncoding = StandardOutputEncoding;
if (NativeMethodsShared.IsWindows)
{
// Some applications such as xcopy.exe fail without error if there's no stdin stream.
// We only do it under Windows, we get Pipe Broken IO exception on other systems if
// the program terminates very fast.
startInfo.RedirectStandardInput = true;
}
// Generally we won't set a working directory, and it will use the current directory
string workingDirectory = GetWorkingDirectory();
if (workingDirectory != null)
{
startInfo.WorkingDirectory = workingDirectory;
}
// Old style environment overrides
#pragma warning disable 0618 // obsolete
Dictionary<string, string> envOverrides = EnvironmentOverride;
if (envOverrides != null)
{
foreach (KeyValuePair<string, string> entry in envOverrides)
{
startInfo.Environment[entry.Key] = entry.Value;
}
#pragma warning restore 0618
}
// New style environment overrides
if (_environmentVariablePairs != null)
{
foreach (KeyValuePair<string, string> variable in _environmentVariablePairs)
{
startInfo.Environment[variable.Key] = variable.Value;
}
}
return startInfo;
}
/// <summary>
/// We expect tasks to override this method if they need information about the tool process or its process events during task execution.
/// Implementation should make sure that the task is started in this method.
/// Starts the process during task execution.
/// </summary>
/// <param name="proc">Fully populated <see cref="Process"/> instance representing the tool process to be started.</param>
/// <returns>A started process. This could be <paramref name="proc"/> or another <see cref="Process"/> instance.</returns>
protected virtual Process StartToolProcess(Process proc)
{
proc.Start();
return proc;
}
/// <summary>
/// Writes out a temporary response file and shell-executes the tool requested. Enables concurrent
/// logging of the output of the tool.
/// </summary>
/// <param name="pathToTool">The computed path to tool executable on disk</param>
/// <param name="responseFileCommands">Command line arguments that should go into a temporary response file</param>
/// <param name="commandLineCommands">Command line arguments that should be passed to the tool executable directly</param>
/// <returns>exit code from the tool - if errors were logged and the tool has an exit code of zero, then we sit it to -1</returns>
protected virtual int ExecuteTool(
string pathToTool,
string responseFileCommands,
string commandLineCommands)
{
if (!UseCommandProcessor)
{
LogPathToTool(ToolExe, pathToTool);
}
string responseFile = null;
Process proc = null;
_standardErrorData = new Queue();
_standardOutputData = new Queue();
_standardErrorDataAvailable = new ManualResetEvent(false);
_standardOutputDataAvailable = new ManualResetEvent(false);
_toolExited = new ManualResetEvent(false);
_terminatedTool = false;
_toolTimeoutExpired = new ManualResetEvent(false);
_eventsDisposed = false;
try
{
responseFile = GetTemporaryResponseFile(responseFileCommands, out string responseFileSwitch);
// create/initialize the process to run the tool
proc = new Process();
proc.StartInfo = GetProcessStartInfo(pathToTool, commandLineCommands, responseFileSwitch);
// turn on the Process.Exited event
proc.EnableRaisingEvents = true;
// sign up for the exit notification
proc.Exited += ReceiveExitNotification;
// turn on async stderr notifications
proc.ErrorDataReceived += ReceiveStandardErrorData;
// turn on async stdout notifications
proc.OutputDataReceived += ReceiveStandardOutputData;
// if we've got this far, we expect to get an exit code from the process. If we don't
// get one from the process, we want to use an exit code value of -1.
ExitCode = -1;
// Start the process
proc = StartToolProcess(proc);
// Close the input stream. This is done to prevent commands from
// blocking the build waiting for input from the user.
if (NativeMethodsShared.IsWindows)
{
proc.StandardInput.Dispose();
}
// Call user-provided hook for code that should execute immediately after the process starts
this.ProcessStarted();
// sign up for stderr callbacks
proc.BeginErrorReadLine();
// sign up for stdout callbacks
proc.BeginOutputReadLine();
// start the time-out timer
_toolTimer = new Timer(ReceiveTimeoutNotification, null, Timeout, System.Threading.Timeout.Infinite /* no periodic timeouts */);
// deal with the various notifications
HandleToolNotifications(proc);
}
finally
{
// Delete the temp file used for the response file.
if (responseFile != null)
{
DeleteTempFile(responseFile);
}
// get the exit code and release the process handle
if (proc != null)
{
try
{
ExitCode = proc.ExitCode;
}
catch (InvalidOperationException)
{
// The process was never launched successfully.
// Leave the exit code at -1.
}
proc.Dispose();
proc = null;
}
// If the tool exited cleanly, but logged errors then assign a failing exit code (-1)
if (ExitCode == 0 && HasLoggedErrors)
{
ExitCode = -1;
}
// release all the OS resources
// setting a bool to make sure tardy notification threads
// don't try to set the event after this point
lock (_eventCloseLock)
{
_eventsDisposed = true;
_standardErrorDataAvailable.Dispose();
_standardOutputDataAvailable.Dispose();
_toolExited.Dispose();
_toolTimeoutExpired.Dispose();
_toolTimer?.Dispose();
}
}
return ExitCode;
}
/// <summary>
/// Cancels the process executing the task by asking it to close nicely, then after a short period, forcing termination.
/// </summary>
public virtual void Cancel() => ToolCanceled.Set();
/// <summary>
/// Delete temporary file. If the delete fails for some reason (e.g. file locked by anti-virus) then
/// the call will not throw an exception. Instead a warning will be logged, but the build will not fail.
/// </summary>
/// <param name="fileName">File to delete</param>
protected void DeleteTempFile(string fileName)
{
if (s_preserveTempFiles)
{
Log.LogMessageFromText($"Preserving temporary file '{fileName}'", MessageImportance.Low);
return;
}
try
{
File.Delete(fileName);
}
catch (Exception e) when (ExceptionHandling.IsIoRelatedException(e))
{
// Warn only -- occasionally temp files fail to delete because of virus checkers; we
// don't want the build to fail in such cases
LogShared.LogWarningWithCodeFromResources("Shared.FailedDeletingTempFile", fileName, e.Message);
}
}
/// <summary>
/// Handles all the notifications sent while the tool is executing. The
/// notifications can be for tool output, tool time-out, or tool completion.
/// </summary>
/// <remarks>
/// The slightly convoluted use of the async stderr/stdout streams of the
/// Process class is necessary because we want to log all our messages from
/// the main thread, instead of from a worker or callback thread.
/// </remarks>
/// <param name="proc"></param>
private void HandleToolNotifications(Process proc)
{
// NOTE: the ordering of this array is deliberate -- if multiple
// notifications are sent simultaneously, we want to handle them
// in the order specified by the array, so that we can observe the
// following rules:
// 1) if a tool times-out we want to abort it immediately regardless
// of whether its stderr/stdout queues are empty
// 2) if a tool exits, we first want to flush its stderr/stdout queues
// 3) if a tool exits and times-out at the same time, we want to let
// it exit gracefully
WaitHandle[] notifications =
{
_toolTimeoutExpired,
ToolCanceled,
_standardErrorDataAvailable,
_standardOutputDataAvailable,
_toolExited
};
bool isToolRunning = true;
if (YieldDuringToolExecution)
{
BuildEngine3.Yield();
}
try
{
while (isToolRunning)
{
// wait for something to happen -- we block the main thread here
// because we don't want to uselessly consume CPU cycles; in theory
// we could poll the stdout and stderr queues, but polling is not
// good for performance, and so we use ManualResetEvents to wake up
// the main thread only when necessary
// NOTE: the return value from WaitAny() is the array index of the
// notification that was sent; if multiple notifications are sent
// simultaneously, the return value is the index of the notification
// with the smallest index value of all the sent notifications
int notificationIndex = WaitHandle.WaitAny(notifications);
switch (notificationIndex)
{
// tool timed-out
case 0:
// tool was canceled
case 1:
TerminateToolProcess(proc, notificationIndex == 1);
_terminatedTool = true;
isToolRunning = false;
break;
// tool wrote to stderr (and maybe stdout also)
case 2:
LogMessagesFromStandardError();
// if stderr and stdout notifications were sent simultaneously, we
// must alternate between the queues, and not starve the stdout queue
LogMessagesFromStandardOutput();
break;
// tool wrote to stdout
case 3:
LogMessagesFromStandardOutput();
break;
// tool exited
case 4:
// We need to do this to guarantee the stderr/stdout streams
// are empty -- there seems to be no other way of telling when the
// process is done sending its async stderr/stdout notifications; why
// is the Process class sending the exit notification prematurely?
WaitForProcessExit(proc);
// flush the stderr and stdout queues to clear out the data placed
// in them while we were waiting for the process to exit
LogMessagesFromStandardError();
LogMessagesFromStandardOutput();
isToolRunning = false;
break;
default:
ErrorUtilities.ThrowInternalError("Unknown tool notification.");
break;
}
}
}
finally
{
if (YieldDuringToolExecution)
{
BuildEngine3.Reacquire();
}
}
}
/// <summary>
/// Kills the given process that is executing the tool, because the tool's
/// time-out period expired.
/// </summary>
private void KillToolProcessOnTimeout(Process proc, bool isBeingCancelled)
{
// kill the process if it's not finished yet
if (!proc.HasExited)
{
string processName;
try
{
processName = proc.ProcessName;
}
catch (InvalidOperationException)
{
// Process exited in the small interval since we checked HasExited
return;
}
if (!isBeingCancelled)
{
ErrorUtilities.VerifyThrow(Timeout != System.Threading.Timeout.Infinite,
"A time-out value must have been specified or the task must be cancelled.");
LogShared.LogWarningWithCodeFromResources("Shared.KillingProcess", processName, Timeout);
}
else
{
LogShared.LogWarningWithCodeFromResources("Shared.KillingProcessByCancellation", processName);