-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
XMake.cs
4639 lines (4079 loc) · 221 KB
/
XMake.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.Generic;
using System.ComponentModel;
#if FEATURE_SYSTEM_CONFIGURATION
using System.Configuration;
#endif
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Security;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Text.RegularExpressions;
using System.Threading;
using Microsoft.Build.Collections;
using Microsoft.Build.Evaluation;
using Microsoft.Build.Eventing;
using Microsoft.Build.Exceptions;
using Microsoft.Build.Execution;
using Microsoft.Build.Experimental;
using Microsoft.Build.Experimental.BuildCheck;
using Microsoft.Build.Experimental.ProjectCache;
using Microsoft.Build.Framework;
using Microsoft.Build.Framework.Telemetry;
using Microsoft.Build.Graph;
using Microsoft.Build.Internal;
using Microsoft.Build.Logging;
using Microsoft.Build.Shared;
using Microsoft.Build.Shared.Debugging;
using Microsoft.Build.Shared.FileSystem;
using BinaryLogger = Microsoft.Build.Logging.BinaryLogger;
using ConsoleLogger = Microsoft.Build.Logging.ConsoleLogger;
using FileLogger = Microsoft.Build.Logging.FileLogger;
using ForwardingLoggerRecord = Microsoft.Build.Logging.ForwardingLoggerRecord;
using LoggerDescription = Microsoft.Build.Logging.LoggerDescription;
using SimpleErrorLogger = Microsoft.Build.Logging.SimpleErrorLogger.SimpleErrorLogger;
using TerminalLogger = Microsoft.Build.Logging.TerminalLogger.TerminalLogger;
#nullable disable
namespace Microsoft.Build.CommandLine
{
/// <summary>
/// This class implements the MSBuild.exe command-line application. It processes
/// command-line arguments and invokes the build engine.
/// </summary>
public static class MSBuildApp
{
/// <summary>
/// Enumeration of the various ways in which the MSBuild.exe application can exit.
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible", Justification = "shipped already")]
public enum ExitType
{
/// <summary>
/// The application executed successfully.
/// </summary>
Success,
/// <summary>
/// There was a syntax error in a command line argument.
/// </summary>
SwitchError,
/// <summary>
/// A command line argument was not valid.
/// </summary>
InitializationError,
/// <summary>
/// The build failed.
/// </summary>
BuildError,
/// <summary>
/// A logger aborted the build.
/// </summary>
LoggerAbort,
/// <summary>
/// A logger failed unexpectedly.
/// </summary>
LoggerFailure,
/// <summary>
/// The build stopped unexpectedly, for example,
/// because a child died or hung.
/// </summary>
Unexpected,
/// <summary>
/// A project cache failed unexpectedly.
/// </summary>
ProjectCacheFailure,
/// <summary>
/// The client for MSBuild server failed unexpectedly, for example,
/// because the server process died or hung.
/// </summary>
MSBuildClientFailure
}
/// <summary>
/// Whether the static constructor ran successfully.
/// </summary>
private static bool s_initialized;
/// <summary>
/// The object used to synchronize access to shared build state
/// </summary>
private static readonly object s_buildLock = new object();
/// <summary>
/// Whether a build has started.
/// </summary>
private static bool s_hasBuildStarted;
/// <summary>
/// Event signaled when the build is complete.
/// </summary>
private static readonly ManualResetEvent s_buildComplete = new ManualResetEvent(false);
/// <summary>
/// Event signaled when the cancel method is complete.
/// </summary>
private static readonly ManualResetEvent s_cancelComplete = new ManualResetEvent(true);
/// <summary>
/// Cancel when handling Ctrl-C
/// </summary>
private static readonly CancellationTokenSource s_buildCancellationSource = new CancellationTokenSource();
private static readonly char[] s_commaSemicolon = { ',', ';' };
/// <summary>
/// Static constructor
/// </summary>
#pragma warning disable CA1810 // Initialize reference type static fields inline
static MSBuildApp()
#pragma warning restore CA1810 // Initialize reference type static fields inline
{
try
{
////////////////////////////////////////////////////////////////////////////////
// Only initialize static fields here, not inline! //
// This forces the type to initialize in this static constructor and thus //
// any configuration file exceptions can be caught here. //
////////////////////////////////////////////////////////////////////////////////
s_exePath = Path.GetDirectoryName(FileUtilities.ExecutingAssemblyPath);
s_initialized = true;
}
catch (TypeInitializationException ex) when (ex.InnerException is not null
#if FEATURE_SYSTEM_CONFIGURATION
&& ex.InnerException is ConfigurationErrorsException
#endif
)
{
HandleConfigurationException(ex);
}
#if FEATURE_SYSTEM_CONFIGURATION
catch (ConfigurationException ex)
{
HandleConfigurationException(ex);
}
#endif
}
/// <summary>
/// Static no-op method to force static constructor to run and initialize resources.
/// This is useful for unit tests.
/// </summary>
internal static void Initialize()
{
}
/// <summary>
/// Dump any exceptions reading the configuration file, nicely
/// </summary>
private static void HandleConfigurationException(Exception ex)
{
// Error reading the configuration file - eg., unexpected element
// Since we expect users to edit it to add toolsets, this is not unreasonable to expect
StringBuilder builder = new StringBuilder();
Exception exception = ex;
do
{
string message = exception.Message.TrimEnd();
builder.Append(message);
// One of the exceptions is missing a period!
if (message[message.Length - 1] != '.')
{
builder.Append('.');
}
builder.Append(' ');
exception = exception.InnerException;
}
while (exception != null);
Console.WriteLine(ResourceUtilities.FormatResourceStringStripCodeAndKeyword("InvalidConfigurationFile", builder.ToString()));
s_initialized = false;
}
/// <summary>
/// This is the entry point for the application.
/// </summary>
/// <remarks>
/// MSBuild no longer runs any arbitrary code (tasks or loggers) on the main thread, so it never needs the
/// main thread to be in an STA. Accordingly, to avoid ambiguity, we explicitly use the [MTAThread] attribute.
/// This doesn't actually do any work unless COM interop occurs for some reason.
/// We use the MultiDomain loader policy because we may create secondary AppDomains and need NGEN images
/// for our as well as Framework assemblies to be loaded domain neutral so their native images can be used.
/// See <see cref="NuGetFrameworkWrapper"/>.
/// </remarks>
/// <returns>0 on success, 1 on failure</returns>
[MTAThread]
#if FEATURE_APPDOMAIN
[LoaderOptimization(LoaderOptimization.MultiDomain)]
#endif
#pragma warning disable SA1111, SA1009 // Closing parenthesis should be on line of last parameter
public static int Main(
#if !FEATURE_GET_COMMANDLINE
string[] args
#endif
)
#pragma warning restore SA1111, SA1009 // Closing parenthesis should be on line of last parameter
{
// Setup the console UI.
using AutomaticEncodingRestorer _ = new();
SetConsoleUI();
DebuggerLaunchCheck();
// Initialize new build telemetry and record start of this build.
KnownTelemetry.PartialBuildTelemetry = new BuildTelemetry { StartAt = DateTime.UtcNow };
using PerformanceLogEventListener eventListener = PerformanceLogEventListener.Create();
if (Environment.GetEnvironmentVariable("MSBUILDDUMPPROCESSCOUNTERS") == "1")
{
DumpCounters(true /* initialize only */);
}
int exitCode;
if (
Environment.GetEnvironmentVariable(Traits.UseMSBuildServerEnvVarName) == "1" &&
!Traits.Instance.EscapeHatches.EnsureStdOutForChildNodesIsPrimaryStdout &&
CanRunServerBasedOnCommandLineSwitches(
#if FEATURE_GET_COMMANDLINE
Environment.CommandLine))
#else
ConstructArrayArg(args)))
#endif
{
Console.CancelKeyPress += Console_CancelKeyPress;
// Use the client app to execute build in msbuild server. Opt-in feature.
exitCode = ((s_initialized && MSBuildClientApp.Execute(
#if FEATURE_GET_COMMANDLINE
Environment.CommandLine,
#else
ConstructArrayArg(args),
#endif
s_buildCancellationSource.Token) == ExitType.Success) ? 0 : 1);
}
else
{
// return 0 on success, non-zero on failure
exitCode = ((s_initialized && Execute(
#if FEATURE_GET_COMMANDLINE
Environment.CommandLine)
#else
ConstructArrayArg(args))
#endif
== ExitType.Success) ? 0 : 1);
}
if (Environment.GetEnvironmentVariable("MSBUILDDUMPPROCESSCOUNTERS") == "1")
{
DumpCounters(false /* log to console */);
}
return exitCode;
}
/// <summary>
/// Returns true if arguments allows or make sense to leverage msbuild server.
/// </summary>
/// <remarks>
/// Will not throw. If arguments processing fails, we will not run it on server - no reason as it will not run any build anyway.
/// </remarks>
private static bool CanRunServerBasedOnCommandLineSwitches(
#if FEATURE_GET_COMMANDLINE
string commandLine)
#else
string[] commandLine)
#endif
{
bool canRunServer = true;
try
{
GatherAllSwitches(commandLine, out var switchesFromAutoResponseFile, out var switchesNotFromAutoResponseFile, out string fullCommandLine);
CommandLineSwitches commandLineSwitches = CombineSwitchesRespectingPriority(switchesFromAutoResponseFile, switchesNotFromAutoResponseFile, fullCommandLine);
if (CheckAndGatherProjectAutoResponseFile(switchesFromAutoResponseFile, commandLineSwitches, false, fullCommandLine))
{
commandLineSwitches = CombineSwitchesRespectingPriority(switchesFromAutoResponseFile, switchesNotFromAutoResponseFile, fullCommandLine);
}
string projectFile = ProcessProjectSwitch(commandLineSwitches[CommandLineSwitches.ParameterizedSwitch.Project], commandLineSwitches[CommandLineSwitches.ParameterizedSwitch.IgnoreProjectExtensions], Directory.GetFiles);
if (commandLineSwitches[CommandLineSwitches.ParameterlessSwitch.Help] ||
commandLineSwitches.IsParameterizedSwitchSet(CommandLineSwitches.ParameterizedSwitch.NodeMode) ||
commandLineSwitches[CommandLineSwitches.ParameterlessSwitch.Version] ||
FileUtilities.IsBinaryLogFilename(projectFile) ||
!ProcessNodeReuseSwitch(commandLineSwitches[CommandLineSwitches.ParameterizedSwitch.NodeReuse]) ||
IsInteractiveBuild(commandLineSwitches))
{
canRunServer = false;
if (KnownTelemetry.PartialBuildTelemetry != null)
{
KnownTelemetry.PartialBuildTelemetry.ServerFallbackReason = "Arguments";
}
}
}
catch (Exception ex)
{
CommunicationsUtilities.Trace("Unexpected exception during command line parsing. Can not determine if it is allowed to use Server. Fall back to old behavior. Exception: {0}", ex);
if (KnownTelemetry.PartialBuildTelemetry != null)
{
KnownTelemetry.PartialBuildTelemetry.ServerFallbackReason = "ErrorParsingCommandLine";
}
canRunServer = false;
}
return canRunServer;
}
private static bool IsInteractiveBuild(CommandLineSwitches commandLineSwitches)
{
// In 16.0 we added the /interactive command-line argument so the line below keeps back-compat
if (commandLineSwitches.IsParameterizedSwitchSet(CommandLineSwitches.ParameterizedSwitch.Interactive) &&
ProcessBooleanSwitch(commandLineSwitches[CommandLineSwitches.ParameterizedSwitch.Interactive], true, "InvalidInteractiveValue"))
{
return true;
}
// In 15.9 we added support for the global property "NuGetInteractive" to allow SDK resolvers to be interactive.
foreach (string parameter in commandLineSwitches[CommandLineSwitches.ParameterizedSwitch.Property])
{
// split each <prop>=<value> string into 2 pieces, breaking on the first = that is found
string[] parameterSections = parameter.Split(s_propertyValueSeparator, 2);
if (parameterSections.Length == 2 &&
parameterSections[0].Length > 0 &&
string.Equals("NuGetInteractive", parameterSections[0], StringComparison.OrdinalIgnoreCase))
{
string nuGetInteractiveValue = parameterSections[1].Trim('"', ' ');
if (!string.Equals("false", nuGetInteractiveValue, StringComparison.OrdinalIgnoreCase))
{
return true;
}
}
}
return false;
}
#if !FEATURE_GET_COMMANDLINE
/// <summary>
/// Insert the command executable path as the first element of the args array.
/// </summary>
/// <param name="args"></param>
/// <returns></returns>
private static string[] ConstructArrayArg(string[] args)
{
string[] newArgArray = new string[args.Length + 1];
newArgArray[0] = BuildEnvironmentHelper.Instance.CurrentMSBuildExePath;
Array.Copy(args, 0, newArgArray, 1, args.Length);
return newArgArray;
}
#endif // !FEATURE_GET_COMMANDLINE
/// <summary>
/// Append output file with elapsedTime
/// </summary>
/// <comments>
/// This is a non-supported feature to facilitate timing multiple runs
/// </comments>
private static void AppendOutputFile(string path, long elapsedTime)
{
if (!FileSystems.Default.FileExists(path))
{
using StreamWriter sw = File.CreateText(path);
sw.WriteLine(elapsedTime);
}
else
{
using StreamWriter sw = File.AppendText(path);
sw.WriteLine(elapsedTime);
}
}
/// <summary>
/// Dump process counters in parseable format.
/// These can't be gotten after the process ends, so log them here.
/// These are for the current process only: remote nodes are not counted.
/// </summary>
/// <comments>
/// Because some of these counters give bogus results or are poorly defined,
/// we only dump counters if an undocumented environment variable is set.
/// Also, the strings are not localized.
/// Before execution, this is called with initialize only, causing counters to get called with NextValue() to
/// initialize them.
/// </comments>
private static void DumpCounters(bool initializeOnly)
{
Process currentProcess = Process.GetCurrentProcess();
if (!initializeOnly)
{
Console.WriteLine("\n{0}{1}{0}", new string('=', 41 - ("Process".Length / 2)), "Process");
Console.WriteLine("||{0,50}|{1,20:N0}|{2,8}|", "Peak Working Set", currentProcess.PeakWorkingSet64, "bytes");
Console.WriteLine("||{0,50}|{1,20:N0}|{2,8}|", "Peak Paged Memory", currentProcess.PeakPagedMemorySize64, "bytes"); // Not very useful one
Console.WriteLine("||{0,50}|{1,20:N0}|{2,8}|", "Peak Virtual Memory", currentProcess.PeakVirtualMemorySize64, "bytes"); // Not very useful one
Console.WriteLine("||{0,50}|{1,20:N0}|{2,8}|", "Peak Privileged Processor Time", currentProcess.PrivilegedProcessorTime.TotalMilliseconds, "ms");
Console.WriteLine("||{0,50}|{1,20:N0}|{2,8}|", "Peak User Processor Time", currentProcess.UserProcessorTime.TotalMilliseconds, "ms");
Console.WriteLine("||{0,50}|{1,20:N0}|{2,8}|", "Peak Total Processor Time", currentProcess.TotalProcessorTime.TotalMilliseconds, "ms");
Console.WriteLine("{0}{0}", new string('=', 41));
}
#if FEATURE_PERFORMANCE_COUNTERS
// Now some Windows performance counters
// First get the instance name of this process, in order to look them up.
// Generally, the instance names, such as "msbuild" and "msbuild#2" are non deterministic; we want this process.
// Don't use the "ID Process" counter out of the "Process" category, as it doesn't use the same naming scheme
// as the .NET counters. However, the "Process ID" counter out of the ".NET CLR Memory" category apparently uses
// the same scheme as the other .NET categories.
string currentInstance = null;
PerformanceCounterCategory processCategory = new PerformanceCounterCategory("Process");
foreach (string instance in processCategory.GetInstanceNames())
{
using PerformanceCounter counter = new PerformanceCounter(".NET CLR Memory", "Process ID", instance, true);
try
{
if ((int)counter.RawValue == currentProcess.Id)
{
currentInstance = instance;
break;
}
}
catch (InvalidOperationException) // Instance 'WmiApSrv' does not exist in the specified Category. (??)
{
}
}
foreach (PerformanceCounterCategory category in PerformanceCounterCategory.GetCategories())
{
DumpAllInCategory(currentInstance, category, initializeOnly);
}
#endif
}
#if FEATURE_PERFORMANCE_COUNTERS
/// <summary>
/// Dumps all counters in the category
/// </summary>
private static void DumpAllInCategory(string currentInstance, PerformanceCounterCategory category, bool initializeOnly)
{
if (category.CategoryName.IndexOf("remoting", StringComparison.OrdinalIgnoreCase) != -1) // not interesting
{
return;
}
PerformanceCounter[] counters;
try
{
counters = category.GetCounters(currentInstance);
}
catch (InvalidOperationException)
{
// This is a system-wide category, ignore those
return;
}
if (!initializeOnly)
{
Console.WriteLine("\n{0}{1}{0}", new string('=', 41 - (category.CategoryName.Length / 2)), category.CategoryName);
}
foreach (PerformanceCounter counter in counters)
{
DumpCounter(counter, initializeOnly);
}
if (!initializeOnly)
{
Console.WriteLine("{0}{0}", new string('=', 41));
}
}
/// <summary>
/// Dumps one counter
/// </summary>
private static void DumpCounter(PerformanceCounter counter, bool initializeOnly)
{
try
{
if (counter.CounterName.IndexOf("not displayed", StringComparison.OrdinalIgnoreCase) != -1)
{
return;
}
float value = counter.NextValue();
if (!initializeOnly)
{
string friendlyCounterType = GetFriendlyCounterType(counter.CounterType, counter.CounterName);
// At least some (such as % in GC; maybe all) "%" counters are already multiplied by 100. So we don't do that here.
// Show decimal places if meaningful
string valueFormat = value < 10 ? "{0,20:N2}" : "{0,20:N0}";
string valueString = string.Format(CultureInfo.CurrentCulture, valueFormat, value);
Console.WriteLine("||{0,50}|{1}|{2,8}|", counter.CounterName, valueString, friendlyCounterType);
}
}
catch (InvalidOperationException) // Instance 'WmiApSrv' does not exist in the specified Category. (??)
{
}
}
/// <summary>
/// Gets a friendly representation of the counter units
/// </summary>
private static string GetFriendlyCounterType(PerformanceCounterType type, string name)
{
if (name.IndexOf("bytes", StringComparison.OrdinalIgnoreCase) != -1)
{
return "bytes";
}
if (name.IndexOf("threads", StringComparison.OrdinalIgnoreCase) != -1)
{
return "threads";
}
switch (type)
{
case PerformanceCounterType.ElapsedTime:
case PerformanceCounterType.AverageTimer32:
return "s";
case PerformanceCounterType.Timer100Ns:
case PerformanceCounterType.Timer100NsInverse:
return "100ns";
case PerformanceCounterType.SampleCounter:
case PerformanceCounterType.AverageCount64:
case PerformanceCounterType.NumberOfItems32:
case PerformanceCounterType.NumberOfItems64:
case PerformanceCounterType.NumberOfItemsHEX32:
case PerformanceCounterType.NumberOfItemsHEX64:
case PerformanceCounterType.RateOfCountsPerSecond32:
case PerformanceCounterType.RateOfCountsPerSecond64:
case PerformanceCounterType.CountPerTimeInterval32:
case PerformanceCounterType.CountPerTimeInterval64:
case PerformanceCounterType.CounterTimer:
case PerformanceCounterType.CounterTimerInverse:
case PerformanceCounterType.CounterMultiTimer:
case PerformanceCounterType.CounterMultiTimerInverse:
case PerformanceCounterType.CounterDelta32:
case PerformanceCounterType.CounterDelta64:
return "#";
case PerformanceCounterType.CounterMultiTimer100Ns:
case PerformanceCounterType.CounterMultiTimer100NsInverse:
case PerformanceCounterType.RawFraction:
case PerformanceCounterType.SampleFraction:
return "%";
case PerformanceCounterType.AverageBase:
case PerformanceCounterType.RawBase:
case PerformanceCounterType.SampleBase:
case PerformanceCounterType.CounterMultiBase:
default:
return "?";
}
}
#endif
/// <summary>
/// Launch debugger if it's requested by environment variable "MSBUILDDEBUGONSTART".
/// </summary>
private static void DebuggerLaunchCheck()
{
if (Debugger.IsAttached)
{
return;
}
switch (Environment.GetEnvironmentVariable("MSBUILDDEBUGONSTART"))
{
#if FEATURE_DEBUG_LAUNCH
case "1":
Debugger.Launch();
break;
#endif
case "2":
// Sometimes easier to attach rather than deal with JIT prompt
Process currentProcess = Process.GetCurrentProcess();
Console.WriteLine($"Waiting for debugger to attach ({currentProcess.MainModule.FileName} PID {currentProcess.Id}). Press enter to continue...");
Console.ReadLine();
break;
}
}
/// <summary>
/// Orchestrates the execution of the application, and is also responsible
/// for top-level error handling.
/// </summary>
/// <param name="commandLine">The command line to process. The first argument
/// on the command line is assumed to be the name/path of the executable, and
/// is ignored.</param>
/// <returns>A value of type ExitType that indicates whether the build succeeded,
/// or the manner in which it failed.</returns>
public static ExitType Execute(
#if FEATURE_GET_COMMANDLINE
string commandLine)
#else
string[] commandLine)
#endif
{
DebuggerLaunchCheck();
// Initialize new build telemetry and record start of this build, if not initialized already
KnownTelemetry.PartialBuildTelemetry ??= new BuildTelemetry { StartAt = DateTime.UtcNow };
// Indicate to the engine that it can toss extraneous file content
// when it loads microsoft.*.targets. We can't do this in the general case,
// because tasks in the build can (and occasionally do) load MSBuild format files
// with our OM and modify and save them. They'll never do this for Microsoft.*.targets, though,
// and those form the great majority of our unnecessary memory use.
Environment.SetEnvironmentVariable("MSBuildLoadMicrosoftTargetsReadOnly", "true");
#if FEATURE_GET_COMMANDLINE
ErrorUtilities.VerifyThrowArgumentLength(commandLine, nameof(commandLine));
#endif
AppDomain.CurrentDomain.UnhandledException += ExceptionHandling.UnhandledExceptionHandler;
ExitType exitType = ExitType.Success;
ConsoleCancelEventHandler cancelHandler = Console_CancelKeyPress;
TextWriter preprocessWriter = null;
TextWriter targetsWriter = null;
try
{
#if FEATURE_GET_COMMANDLINE
MSBuildEventSource.Log.MSBuildExeStart(commandLine);
#else
if (MSBuildEventSource.Log.IsEnabled())
{
MSBuildEventSource.Log.MSBuildExeStart(string.Join(" ", commandLine));
}
#endif
Console.CancelKeyPress += cancelHandler;
// check the operating system the code is running on
VerifyThrowSupportedOS();
// reset the application state for this new build
ResetBuildState();
// process the detected command line switches -- gather build information, take action on non-build switches, and
// check for non-trivial errors
string projectFile = null;
string[] targets = Array.Empty<string>();
string toolsVersion = null;
Dictionary<string, string> globalProperties = null;
Dictionary<string, string> restoreProperties = null;
ILogger[] loggers = Array.Empty<ILogger>();
LoggerVerbosity verbosity = LoggerVerbosity.Normal;
LoggerVerbosity originalVerbosity = LoggerVerbosity.Normal;
List<DistributedLoggerRecord> distributedLoggerRecords = null;
#if FEATURE_XML_SCHEMA_VALIDATION
bool needToValidateProject = false;
string schemaFile = null;
#endif
int cpuCount = 1;
#if FEATURE_NODE_REUSE
bool enableNodeReuse = true;
#else
bool enableNodeReuse = false;
#endif
bool detailedSummary = false;
ISet<string> warningsAsErrors = null;
ISet<string> warningsNotAsErrors = null;
ISet<string> warningsAsMessages = null;
bool enableRestore = Traits.Instance.EnableRestoreFirst;
ProfilerLogger profilerLogger = null;
bool enableProfiler = false;
bool interactive = false;
ProjectIsolationMode isolateProjects = ProjectIsolationMode.False;
GraphBuildOptions graphBuildOptions = null;
bool lowPriority = false;
string[] inputResultsCaches = null;
string outputResultsCache = null;
bool question = false;
bool isBuildCheckEnabled = false;
string[] getProperty = Array.Empty<string>();
string[] getItem = Array.Empty<string>();
string[] getTargetResult = Array.Empty<string>();
string getResultOutputFile = string.Empty;
BuildResult result = null;
#if FEATURE_REPORTFILEACCESSES
bool reportFileAccesses = false;
#endif
GatherAllSwitches(commandLine, out var switchesFromAutoResponseFile, out var switchesNotFromAutoResponseFile, out _);
bool buildCanBeInvoked = ProcessCommandLineSwitches(
switchesFromAutoResponseFile,
switchesNotFromAutoResponseFile,
ref projectFile,
ref targets,
ref toolsVersion,
ref globalProperties,
ref loggers,
ref verbosity,
ref originalVerbosity,
ref distributedLoggerRecords,
#if FEATURE_XML_SCHEMA_VALIDATION
ref needToValidateProject,
ref schemaFile,
#endif
ref cpuCount,
ref enableNodeReuse,
ref preprocessWriter,
ref targetsWriter,
ref detailedSummary,
ref warningsAsErrors,
ref warningsNotAsErrors,
ref warningsAsMessages,
ref enableRestore,
ref interactive,
ref profilerLogger,
ref enableProfiler,
ref restoreProperties,
ref isolateProjects,
ref graphBuildOptions,
ref inputResultsCaches,
ref outputResultsCache,
#if FEATURE_REPORTFILEACCESSES
ref reportFileAccesses,
#endif
ref lowPriority,
ref question,
ref isBuildCheckEnabled,
ref getProperty,
ref getItem,
ref getTargetResult,
ref getResultOutputFile,
recursing: false,
#if FEATURE_GET_COMMANDLINE
commandLine);
#else
string.Join(' ', commandLine));
#endif
CommandLineSwitches.SwitchesFromResponseFiles = null;
if (buildCanBeInvoked)
{
// Unfortunately /m isn't the default, and we are not yet brave enough to make it the default.
// However we want to give a hint to anyone who is building single proc without realizing it that there
// is a better way.
// Only display the message if /m isn't provided
if (cpuCount == 1 && FileUtilities.IsSolutionFilename(projectFile) && verbosity > LoggerVerbosity.Minimal
&& switchesNotFromAutoResponseFile[CommandLineSwitches.ParameterizedSwitch.MaxCPUCount].Length == 0
&& switchesFromAutoResponseFile[CommandLineSwitches.ParameterizedSwitch.MaxCPUCount].Length == 0
&& preprocessWriter != null
&& targetsWriter != null)
{
Console.WriteLine(ResourceUtilities.GetResourceString("PossiblyOmittedMaxCPUSwitch"));
}
if (preprocessWriter != null && !BuildEnvironmentHelper.Instance.RunningTests)
{
// Indicate to the engine that it can NOT toss extraneous file content: we want to
// see that in preprocessing/debugging
Environment.SetEnvironmentVariable("MSBUILDLOADALLFILESASWRITEABLE", "1");
}
DateTime t1 = DateTime.Now;
bool outputPropertiesItemsOrTargetResults = getProperty.Length > 0 || getItem.Length > 0 || getTargetResult.Length > 0;
// If the primary file passed to MSBuild is a .binlog file, play it back into passed loggers
// as if a build is happening
if (FileUtilities.IsBinaryLogFilename(projectFile))
{
ReplayBinaryLog(projectFile, loggers, distributedLoggerRecords, cpuCount, isBuildCheckEnabled);
}
else if (outputPropertiesItemsOrTargetResults && FileUtilities.IsSolutionFilename(projectFile))
{
exitType = ExitType.BuildError;
CommandLineSwitchException.Throw("SolutionBuildInvalidForCommandLineEvaluation",
getProperty.Length > 0 ? "getProperty" :
getItem.Length > 0 ? "getItem" :
"getTargetResult");
}
else if ((getProperty.Length > 0 || getItem.Length > 0) && (targets is null || targets.Length == 0))
{
try
{
using (ProjectCollection collection = new(globalProperties, loggers, ToolsetDefinitionLocations.Default))
{
Project project = collection.LoadProject(projectFile, globalProperties, toolsVersion);
if (getResultOutputFile.Length == 0)
{
exitType = OutputPropertiesAfterEvaluation(getProperty, getItem, project, Console.Out);
}
else
{
using (var streamWriter = new StreamWriter(getResultOutputFile))
{
exitType = OutputPropertiesAfterEvaluation(getProperty, getItem, project, streamWriter);
}
}
collection.LogBuildFinishedEvent(exitType == ExitType.Success);
}
}
catch (InvalidProjectFileException)
{
exitType = ExitType.BuildError;
}
}
else // regular build
{
// if everything checks out, and sufficient information is available to start building
if (
!BuildProject(
projectFile,
targets,
toolsVersion,
globalProperties,
restoreProperties,
loggers,
verbosity,
distributedLoggerRecords.ToArray(),
#if FEATURE_XML_SCHEMA_VALIDATION
needToValidateProject, schemaFile,
#endif
cpuCount,
enableNodeReuse,
preprocessWriter,
targetsWriter,
detailedSummary,
warningsAsErrors,
warningsNotAsErrors,
warningsAsMessages,
enableRestore,
profilerLogger,
enableProfiler,
interactive,
isolateProjects,
graphBuildOptions,
lowPriority,
question,
isBuildCheckEnabled,
inputResultsCaches,
outputResultsCache,
saveProjectResult: outputPropertiesItemsOrTargetResults,
ref result,
#if FEATURE_REPORTFILEACCESSES
reportFileAccesses,
#endif
commandLine))
{
exitType = ExitType.BuildError;
}
} // end of build
DateTime t2 = DateTime.Now;
TimeSpan elapsedTime = t2.Subtract(t1);
string timerOutputFilename = Environment.GetEnvironmentVariable("MSBUILDTIMEROUTPUTS");
if (outputPropertiesItemsOrTargetResults && targets?.Length > 0 && result is not null)
{
if (getResultOutputFile.Length == 0)
{
exitType = OutputBuildInformationInJson(result, getProperty, getItem, getTargetResult, loggers, exitType, Console.Out);
}
else
{
using (var streamWriter = new StreamWriter(getResultOutputFile))
{
exitType = OutputBuildInformationInJson(result, getProperty, getItem, getTargetResult, loggers, exitType, streamWriter);
}
}
}
if (!string.IsNullOrEmpty(timerOutputFilename))
{
AppendOutputFile(timerOutputFilename, (long)elapsedTime.TotalMilliseconds);
}
}
else
{
// if there was no need to start the build e.g. because /help was triggered
// do nothing
}
}
/**********************************************************************************************************************
* WARNING: Do NOT add any more catch blocks below! Exceptions should be caught as close to their point of origin as
* possible, and converted into one of the known exceptions. The code that causes an exception best understands the
* reason for the exception, and only that code can provide the proper error message. We do NOT want to display
* messages from unknown exceptions, because those messages are most likely neither localized, nor composed in the
* canonical form with the correct prefix.
*********************************************************************************************************************/
// handle switch errors
catch (CommandLineSwitchException e)
{
Console.WriteLine(e.Message);
Console.WriteLine();
// prompt user to display help for proper switch usage
ShowHelpPrompt();
exitType = ExitType.SwitchError;
}
// handle configuration exceptions: problems reading toolset information from msbuild.exe.config or the registry
catch (InvalidToolsetDefinitionException e)
{
// Brief prefix to indicate that it's a configuration failure, and provide the "error" indication
Console.WriteLine(ResourceUtilities.FormatResourceStringStripCodeAndKeyword("ConfigurationFailurePrefixNoErrorCode", e.ErrorCode, e.Message));
exitType = ExitType.InitializationError;
}
// handle initialization failures
catch (InitializationException e)
{
Console.WriteLine(e.Message);
exitType = ExitType.InitializationError;
}
// handle polite logger failures: don't dump the stack or trigger watson for these
catch (LoggerException e)
{
// display the localized message from the outer exception in canonical format
if (e.ErrorCode != null)
{
// Brief prefix to indicate that it's a logger failure, and provide the "error" indication
Console.WriteLine(ResourceUtilities.FormatResourceStringStripCodeAndKeyword("LoggerFailurePrefixNoErrorCode", e.ErrorCode, e.Message));
}
else
{
// Brief prefix to indicate that it's a logger failure, adding a generic error code to make sure
// there's something for the user to look up in the documentation
Console.WriteLine(ResourceUtilities.FormatResourceStringStripCodeAndKeyword("LoggerFailurePrefixWithErrorCode", e.Message));
}
if (e.InnerException != null)
{
// write out exception details -- don't bother triggering Watson, because most of these exceptions will be coming
// from buggy loggers written by users
Console.WriteLine(e.InnerException.ToString());
}
exitType = ExitType.LoggerAbort;
}
// handle logger failures (logger bugs)
catch (InternalLoggerException e)
{
if (!e.InitializationException)
{
// display the localized message from the outer exception in canonical format
Console.WriteLine($"MSBUILD : error {e.ErrorCode}: {e.Message}");
#if DEBUG
Console.WriteLine("This is an unhandled exception from a logger -- PLEASE OPEN A BUG AGAINST THE LOGGER OWNER.");
#endif
// write out exception details -- don't bother triggering Watson, because most of these exceptions will be coming
// from buggy loggers written by users
Console.WriteLine(e.InnerException.ToString());
exitType = ExitType.LoggerFailure;
}
else
{