-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
XMake.cs
3536 lines (3113 loc) · 166 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
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections;
using System.Collections.Generic;
#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.Threading;
using Microsoft.Build.Evaluation;
using Microsoft.Build.Exceptions;
using Microsoft.Build.Execution;
using Microsoft.Build.Framework;
using Microsoft.Build.Logging;
using Microsoft.Build.Shared;
using Microsoft.Build.Utilities;
#if (!STANDALONEBUILD)
using Microsoft.Internal.Performance;
#endif
#if MSBUILDENABLEVSPROFILING
using Microsoft.VisualStudio.Profiler;
#endif
using FileLogger = Microsoft.Build.Logging.FileLogger;
using ConsoleLogger = Microsoft.Build.Logging.ConsoleLogger;
using LoggerDescription = Microsoft.Build.Logging.LoggerDescription;
using ForwardingLoggerRecord = Microsoft.Build.Logging.ForwardingLoggerRecord;
using BinaryLogger = Microsoft.Build.Logging.BinaryLogger;
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>
static public 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>
/// 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 Object s_buildLock = new Object();
/// <summary>
/// The currently active build, if any.
/// </summary>
private static BuildSubmission s_activeBuild;
/// <summary>
/// Event signalled when the build is complete.
/// </summary>
private static ManualResetEvent s_buildComplete = new ManualResetEvent(false);
/// <summary>
/// Event signalled when the cancel method is complete.
/// </summary>
private static ManualResetEvent s_cancelComplete = new ManualResetEvent(true);
/// <summary>
/// Set to 1 when the cancel method has been invoked.
/// Never reset to false: subsequent hits of Ctrl-C should do nothing
/// </summary>
private static int s_receivedCancel;
/// <summary>
/// Static constructor
/// </summary>
static MSBuildApp()
{
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)
{
if (ex.InnerException == null
#if !FEATURE_SYSTEM_CONFIGURATION
)
#else
|| ex.InnerException.GetType() != typeof(ConfigurationErrorsException))
#endif
{
throw;
}
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.FormatResourceString("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.
/// </remarks>
/// <returns>0 on success, 1 on failure</returns>
[MTAThread]
public static int Main(
#if !FEATURE_GET_COMMANDLINE
string [] args
#endif
)
{
if (Environment.GetEnvironmentVariable("MSBUILDDUMPPROCESSCOUNTERS") == "1")
{
DumpCounters(true /* initialize only */);
}
// return 0 on success, non-zero on failure
int 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>
/// 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;
}
/// <summary>
/// Append output file with elapsedTime
/// </summary>
/// <comments>
/// This is a non-supported feature to facilitate timing multiple runs
/// </comments>
static private void AppendOutputFile(string path, Int64 elapsedTime)
{
if (!File.Exists(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);
string valueFormat;
// 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
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>
/// 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
)
{
// 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");
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;
}
#if FEATURE_GET_COMMANDLINE
ErrorUtilities.VerifyThrowArgumentLength(commandLine, "commandLine");
#endif
ExitType exitType = ExitType.Success;
ConsoleCancelEventHandler cancelHandler = Console_CancelKeyPress;
try
{
#if (!STANDALONEBUILD)
// Enable CodeMarkers for MSBuild.exe
CodeMarkers.Instance.InitPerformanceDll(CodeMarkerApp.MSBUILDPERF, String.Format(CultureInfo.InvariantCulture, @"Software\Microsoft\MSBuild\{0}", MSBuildConstants.CurrentProductVersion));
#endif
#if MSBUILDENABLEVSPROFILING
string startMSBuildExe = String.Format(CultureInfo.CurrentCulture, "Running MSBuild.exe with command line {0}", commandLine);
DataCollection.CommentMarkProfile(8800, startMSBuildExe);
#endif
Console.CancelKeyPress += cancelHandler;
// check the operating system the code is running on
VerifyThrowSupportedOS();
// Setup the console UI.
SetConsoleUI();
// 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 = { };
string toolsVersion = null;
Dictionary<string, string> globalProperties = null;
Dictionary<string, string> restoreProperties = null;
ILogger[] loggers = { };
LoggerVerbosity verbosity = 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
TextWriter preprocessWriter = null;
bool detailedSummary = false;
ISet<string> warningsAsErrors = null;
ISet<string> warningsAsMessages = null;
bool enableRestore = Traits.Instance.EnableRestoreFirst;
ProfilerLogger profilerLogger = null;
bool enableProfiler = false;
CommandLineSwitches switchesFromAutoResponseFile;
CommandLineSwitches switchesNotFromAutoResponseFile;
GatherAllSwitches(commandLine, out switchesFromAutoResponseFile, out switchesNotFromAutoResponseFile);
if (ProcessCommandLineSwitches(
switchesFromAutoResponseFile,
switchesNotFromAutoResponseFile,
ref projectFile,
ref targets,
ref toolsVersion,
ref globalProperties,
ref loggers,
ref verbosity,
ref distributedLoggerRecords,
#if FEATURE_XML_SCHEMA_VALIDATION
ref needToValidateProject,
ref schemaFile,
#endif
ref cpuCount,
ref enableNodeReuse,
ref preprocessWriter,
ref detailedSummary,
ref warningsAsErrors,
ref warningsAsMessages,
ref enableRestore,
ref profilerLogger,
ref enableProfiler,
ref restoreProperties,
recursing: false
))
{
// 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.
if (cpuCount == 1 && FileUtilities.IsSolutionFilename(projectFile) && verbosity > LoggerVerbosity.Minimal)
{
Console.WriteLine(ResourceUtilities.GetResourceString("PossiblyOmittedMaxCPUSwitch"));
}
if (preprocessWriter != null)
{
// 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;
// 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);
}
else // regular build
{
#if !STANDALONEBUILD
if (Environment.GetEnvironmentVariable("MSBUILDOLDOM") != "1")
#endif
{
// 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, detailedSummary, warningsAsErrors, warningsAsMessages, enableRestore, profilerLogger, enableProfiler))
{
exitType = ExitType.BuildError;
}
}
#if !STANDALONEBUILD
else
{
exitType = OldOMBuildProject(exitType, projectFile, targets, toolsVersion, globalProperties, loggers, verbosity, needToValidateProject, schemaFile, cpuCount);
}
#endif
} // end of build
DateTime t2 = DateTime.Now;
TimeSpan elapsedTime = t2.Subtract(t1);
string timerOutputFilename = Environment.GetEnvironmentVariable("MSBUILDTIMEROUTPUTS");
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.FormatResourceString("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 (null != e.ErrorCode)
{
// Brief prefix to indicate that it's a logger failure, and provide the "error" indication
Console.WriteLine(ResourceUtilities.FormatResourceString("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.FormatResourceString("LoggerFailurePrefixWithErrorCode", e.Message));
}
if (null != e.InnerException)
{
// 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
{
Console.WriteLine("MSBUILD : error " + e.ErrorCode + ": " + e.Message +
(e.InnerException != null ? " " + e.InnerException.Message : ""));
exitType = ExitType.InitializationError;
}
}
catch (BuildAbortedException e)
{
Console.WriteLine("MSBUILD : error " + e.ErrorCode + ": " + e.Message +
(e.InnerException != null ? " " + e.InnerException.Message : String.Empty));
exitType = ExitType.Unexpected;
}
// handle fatal errors
catch (Exception e)
{
// display a generic localized message for the user
Console.WriteLine("{0}\r\n{1}", AssemblyResources.GetString("FatalError"), e.ToString());
#if DEBUG
Console.WriteLine("This is an unhandled exception in MSBuild Engine -- PLEASE OPEN A BUG AGAINST THE MSBUILD TEAM.\r\n{0}", e.ToString());
#endif
// rethrow, in case Watson is enabled on the machine -- if not, the CLR will write out exception details
// allow the build lab to set an env var to avoid jamming the build
if (Environment.GetEnvironmentVariable("MSBUILDDONOTLAUNCHDEBUGGER") != "1")
{
throw;
}
}
finally
{
s_buildComplete.Set();
Console.CancelKeyPress -= cancelHandler;
// Wait for any pending cancel, so that we get any remaining messages
s_cancelComplete.WaitOne();
#if (!STANDALONEBUILD)
// Turn off codemarkers
CodeMarkers.Instance.UninitializePerformanceDLL(CodeMarkerApp.MSBUILDPERF);
#endif
}
/**********************************************************************************************************************
* WARNING: Do NOT add any more catch blocks above!
*********************************************************************************************************************/
return exitType;
}
#if (!STANDALONEBUILD)
/// <summary>
/// Use the Orcas Engine to build the project
/// #############################################################################################
/// #### Segregated into another method to avoid loading the old Engine in the regular case. ####
/// #### Do not move back in to the main code path! #############################################
/// #############################################################################################
/// We have marked this method as NoInlining because we do not want Microsoft.Build.Engine.dll to be loaded unless we really execute this code path
/// </summary>
[MethodImpl(MethodImplOptions.NoInlining)]
private static ExitType OldOMBuildProject(ExitType exitType, string projectFile, string[] targets, string toolsVersion, Dictionary<string, string> globalProperties, ILogger[] loggers, LoggerVerbosity verbosity, bool needToValidateProject, string schemaFile, int cpuCount)
{
// Log something to avoid confusion caused by errant environment variable sending us down here
Console.WriteLine(AssemblyResources.GetString("Using35Engine"));
Microsoft.Build.BuildEngine.BuildPropertyGroup oldGlobalProps = new Microsoft.Build.BuildEngine.BuildPropertyGroup();
// Copy over the global properties to the old OM
foreach (KeyValuePair<string, string> globalProp in globalProperties)
{
oldGlobalProps.SetProperty(globalProp.Key, globalProp.Value);
}
if (!BuildProjectWithOldOM(projectFile, targets, toolsVersion, oldGlobalProps, loggers, verbosity, null, needToValidateProject, schemaFile, cpuCount))
{
exitType = ExitType.BuildError;
}
return exitType;
}
#endif
/// <summary>
/// Handler for when CTRL-C or CTRL-BREAK is called.
/// CTRL-BREAK means "die immediately"
/// CTRL-C means "try to stop work and exit cleanly"
/// </summary>
private static void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e)
{
if (e.SpecialKey == ConsoleSpecialKey.ControlBreak)
{
e.Cancel = false; // required; the process will now be terminated rudely
return;
}
e.Cancel = true; // do not terminate rudely
bool alreadyCalled = (Interlocked.CompareExchange(ref s_receivedCancel, 1, 0) == 1);
if (alreadyCalled)
{
return;
}
Console.WriteLine(ResourceUtilities.GetResourceString("AbortingBuild"));
// The OS takes a lock in
// kernel32.dll!_SetConsoleCtrlHandler, so if a task
// waits for that lock somehow before quitting, it would hang
// because we're in it here. One way a task can end up here is
// by calling Microsoft.Win32.SystemEvents.Initialize.
// So do our work asynchronously so we can return immediately.
// We're already on a threadpool thread anyway.
WaitCallback callback = new WaitCallback(
delegate (Object state)
{
s_cancelComplete.Reset();
// If the build is already complete, just exit.
if (s_buildComplete.WaitOne(0))
{
s_cancelComplete.Set();
return;
}
// If the build has already started (or already finished), we will cancel it
// If the build has not yet started, it will cancel itself, because
// we set alreadyCalled=1
BuildSubmission result = null;
lock (s_buildLock)
{
result = s_activeBuild;
}
if (result != null)
{
BuildManager.DefaultBuildManager.CancelAllSubmissions();
s_buildComplete.WaitOne();
}
s_cancelComplete.Set(); // This will release our main Execute method so we can finally exit.
});
ThreadPoolExtensions.QueueThreadPoolWorkItemWithCulture(callback, CultureInfo.CurrentCulture, CultureInfo.CurrentUICulture);
}
/// <summary>
/// Clears out any state accumulated from previous builds, and resets
/// member data in preparation for a new build.
/// </summary>
private static void ResetBuildState()
{
s_includedResponseFiles = new ArrayList();
usingSwitchesFromAutoResponseFile = false;
}
/// <summary>
/// The location of the application executable.
/// </summary>
/// <remarks>
/// Initialized in the static constructor. See comment there.
/// </remarks>
private static readonly string s_exePath; // Do not initialize
/// <summary>
/// Name of the exe (presumably msbuild.exe)
/// </summary>
private static string s_exeName;
/// <summary>
/// Default name for the msbuild log file
/// </summary>
private const string msbuildLogFileName = "msbuild.log";
/// <summary>
/// Initializes the build engine, and starts the project building.
/// </summary>
/// <returns>true, if build succeeds</returns>
[SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling", Justification = "Not going to refactor it right now")]
internal static bool BuildProject
(
string projectFile,
string[] targets,
string toolsVersion,
Dictionary<string, string> globalProperties,
Dictionary<string, string> restoreProperties,
ILogger[] loggers,
LoggerVerbosity verbosity,
DistributedLoggerRecord[] distributedLoggerRecords,
#if FEATURE_XML_SCHEMA_VALIDATION
bool needToValidateProject,
string schemaFile,
#endif
int cpuCount,
bool enableNodeReuse,
TextWriter preprocessWriter,
bool detailedSummary,
ISet<string> warningsAsErrors,
ISet<string> warningsAsMessages,
bool enableRestore,
ProfilerLogger profilerLogger,
bool enableProfiler
)
{
if (String.Equals(Path.GetExtension(projectFile), ".vcproj", StringComparison.OrdinalIgnoreCase) ||
String.Equals(Path.GetExtension(projectFile), ".dsp", StringComparison.OrdinalIgnoreCase))
{
InitializationException.Throw(ResourceUtilities.FormatResourceString("ProjectUpgradeNeededToVcxProj", projectFile), null);
}
bool success = false;
ProjectCollection projectCollection = null;
bool onlyLogCriticalEvents = false;
try
{
List<ForwardingLoggerRecord> remoteLoggerRecords = new List<ForwardingLoggerRecord>();
foreach (DistributedLoggerRecord distRecord in distributedLoggerRecords)
{
remoteLoggerRecords.Add(new ForwardingLoggerRecord(distRecord.CentralLogger, distRecord.ForwardingLoggerDescription));
}
// Targeted perf optimization for the case where we only have our own parallel console logger, and verbosity is quiet. In such a case
// we know we won't emit any messages except for errors and warnings, so the engine should not bother even logging them.
// If we're using the original serial console logger we can't do this, as it shows project started/finished context
// around errors and warnings.
// Telling the engine to not bother logging non-critical messages means that typically it can avoid loading any resources in the successful
// build case.
if (loggers.Length == 1 &&
remoteLoggerRecords.Count == 0 &&
verbosity == LoggerVerbosity.Quiet &&
loggers[0].Parameters != null &&
loggers[0].Parameters.IndexOf("ENABLEMPLOGGING", StringComparison.OrdinalIgnoreCase) != -1 &&
loggers[0].Parameters.IndexOf("DISABLEMPLOGGING", StringComparison.OrdinalIgnoreCase) == -1 &&
loggers[0].Parameters.IndexOf("V=", StringComparison.OrdinalIgnoreCase) == -1 && // Console logger could have had a verbosity
loggers[0].Parameters.IndexOf("VERBOSITY=", StringComparison.OrdinalIgnoreCase) == -1) // override with the /clp switch
{
// Must be exactly the console logger, not a derived type like the file logger.
Type t1 = loggers[0].GetType();
Type t2 = typeof(ConsoleLogger);
if (t1 == t2)
{
onlyLogCriticalEvents = true;
}
}
// HACK HACK: this enables task parameter logging.
// This is a hack for now to make sure the perf hit only happens
// on diagnostic. This should be changed to pipe it through properly,
// perhaps as part of a fuller tracing feature.
bool logTaskInputs = verbosity == LoggerVerbosity.Diagnostic;
if (!logTaskInputs)
{
foreach (var logger in loggers)
{
if (logger.Parameters != null &&
(logger.Parameters.IndexOf("V=DIAG", StringComparison.OrdinalIgnoreCase) != -1 ||
logger.Parameters.IndexOf("VERBOSITY=DIAG", StringComparison.OrdinalIgnoreCase) != -1)
)
{
logTaskInputs = true;
break;
}
}
}
if (!logTaskInputs)
{
foreach (var logger in distributedLoggerRecords)
{
if (logger.CentralLogger != null)
{
if (logger.CentralLogger.Parameters != null &&
(logger.CentralLogger.Parameters.IndexOf("V=DIAG", StringComparison.OrdinalIgnoreCase) != -1 ||
logger.CentralLogger.Parameters.IndexOf("VERBOSITY=DIAG", StringComparison.OrdinalIgnoreCase) != -1)
)
{