PageRenderTime 63ms CodeModel.GetById 29ms RepoModel.GetById 0ms app.codeStats 1ms

/SolutionFramework/VisualStudioProvider/MSBuild/Build/CommandLine/MSBuildApp.cs

#
C# | 1683 lines | 1662 code | 21 blank | 0 comment | 130 complexity | 6f20dca73f1c5ceb3e7db1cb93c087dc MD5 | raw file
Possible License(s): Apache-2.0, LGPL-3.0

Large files files are truncated, but you can click here to view the full file

  1. namespace Microsoft.Build.CommandLine
  2. {
  3. using Microsoft.Build.BuildEngine;
  4. using Microsoft.Build.Evaluation;
  5. using Microsoft.Build.Exceptions;
  6. using Microsoft.Build.Execution;
  7. using Microsoft.Build.Framework;
  8. using Microsoft.Build.Logging;
  9. using Microsoft.Build.Shared;
  10. using Microsoft.Internal.Performance;
  11. using System;
  12. using System.Collections;
  13. using System.Collections.Generic;
  14. using System.Configuration;
  15. using System.Diagnostics;
  16. using System.Globalization;
  17. using System.IO;
  18. using System.Reflection;
  19. using System.Runtime.CompilerServices;
  20. using System.Runtime.InteropServices;
  21. using System.Security;
  22. using System.Text;
  23. using System.Threading;
  24. public static class MSBuildApp
  25. {
  26. private static BuildSubmission activeBuild;
  27. private const string autoResponseFileName = "MSBuild.rsp";
  28. private static ManualResetEvent buildComplete = new ManualResetEvent(false);
  29. private static object buildLock = new object();
  30. private static ManualResetEvent cancelComplete = new ManualResetEvent(true);
  31. private static readonly string exePath;
  32. private static ArrayList includedResponseFiles;
  33. private static bool initialized;
  34. private const string msbuildLogFileName = "msbuild.log";
  35. private static readonly char[] propertyValueSeparator = new char[] { '=' };
  36. private static int receivedCancel;
  37. internal static bool usingSwitchesFromAutoResponseFile = false;
  38. private static readonly char[] wildcards = new char[] { '*', '?' };
  39. static MSBuildApp()
  40. {
  41. try
  42. {
  43. exePath = Path.GetDirectoryName(new Uri(Assembly.GetExecutingAssembly().EscapedCodeBase).LocalPath);
  44. initialized = true;
  45. }
  46. catch (TypeInitializationException exception)
  47. {
  48. if ((exception.InnerException == null) || (exception.InnerException.GetType() != typeof(ConfigurationErrorsException)))
  49. {
  50. throw;
  51. }
  52. HandleConfigurationException(exception);
  53. }
  54. catch (ConfigurationException exception2)
  55. {
  56. HandleConfigurationException(exception2);
  57. }
  58. }
  59. internal static string AggregateParameters(string anyPrefixingParameter, string[] parametersToAggregate)
  60. {
  61. for (int i = 0; i < parametersToAggregate.Length; i++)
  62. {
  63. parametersToAggregate[i] = parametersToAggregate[i].Trim(new char[] { ';' });
  64. }
  65. string str = anyPrefixingParameter ?? string.Empty;
  66. return (str + string.Join(";", parametersToAggregate));
  67. }
  68. internal static bool BuildProject(string projectFile, string[] targets, string toolsVersion, Dictionary<string, string> globalProperties, ILogger[] loggers, LoggerVerbosity verbosity, DistributedLoggerRecord[] distributedLoggerRecords, bool needToValidateProject, string schemaFile, int cpuCount, bool enableNodeReuse, TextWriter preprocessWriter, bool debugger, bool detailedSummary)
  69. {
  70. if (string.Equals(Path.GetExtension(projectFile), ".vcproj", StringComparison.OrdinalIgnoreCase) || string.Equals(Path.GetExtension(projectFile), ".dsp", StringComparison.OrdinalIgnoreCase))
  71. {
  72. InitializationException.Throw(Microsoft.Build.Shared.ResourceUtilities.FormatResourceString("ProjectUpgradeNeededToVcxProj", new object[] { projectFile }), null);
  73. }
  74. bool flag = false;
  75. ProjectCollection projectCollection = null;
  76. bool onlyLogCriticalEvents = false;
  77. try
  78. {
  79. List<ForwardingLoggerRecord> list = new List<ForwardingLoggerRecord>();
  80. foreach (DistributedLoggerRecord record in distributedLoggerRecords)
  81. {
  82. list.Add(new ForwardingLoggerRecord(record.CentralLogger, record.ForwardingLoggerDescription));
  83. }
  84. if ((((loggers.Length == 1) && (verbosity == LoggerVerbosity.Quiet)) && ((loggers[0].Parameters.IndexOf("ENABLEMPLOGGING", StringComparison.OrdinalIgnoreCase) != -1) && (loggers[0].Parameters.IndexOf("DISABLEMPLOGGING", StringComparison.OrdinalIgnoreCase) == -1))) && ((loggers[0].Parameters.IndexOf("V=", StringComparison.OrdinalIgnoreCase) == -1) && (loggers[0].Parameters.IndexOf("VERBOSITY=", StringComparison.OrdinalIgnoreCase) == -1)))
  85. {
  86. Type type = loggers[0].GetType();
  87. Type type2 = typeof(Microsoft.Build.Logging.ConsoleLogger);
  88. if (type == type2)
  89. {
  90. onlyLogCriticalEvents = true;
  91. }
  92. }
  93. projectCollection = new ProjectCollection(globalProperties, loggers, null, Microsoft.Build.Evaluation.ToolsetDefinitionLocations.Registry | Microsoft.Build.Evaluation.ToolsetDefinitionLocations.ConfigurationFile, cpuCount, onlyLogCriticalEvents);
  94. if (debugger)
  95. {
  96. Environment.SetEnvironmentVariable("MSBUILDDEBUGGING", "1");
  97. }
  98. if ((toolsVersion != null) && !projectCollection.ContainsToolset(toolsVersion))
  99. {
  100. ThrowInvalidToolsVersionInitializationException(projectCollection.Toolsets, toolsVersion);
  101. }
  102. if (needToValidateProject && !Microsoft.Build.Shared.FileUtilities.IsSolutionFilename(projectFile))
  103. {
  104. Microsoft.Build.Evaluation.Project project = projectCollection.LoadProject(projectFile, globalProperties, toolsVersion);
  105. Microsoft.Build.Evaluation.Toolset toolset = projectCollection.GetToolset((toolsVersion == null) ? project.ToolsVersion : toolsVersion);
  106. if (toolset == null)
  107. {
  108. ThrowInvalidToolsVersionInitializationException(projectCollection.Toolsets, project.ToolsVersion);
  109. }
  110. Microsoft.Build.CommandLine.ProjectSchemaValidationHandler.VerifyProjectSchema(projectFile, schemaFile, toolset.ToolsPath);
  111. projectCollection.UnloadProject(project);
  112. }
  113. if ((preprocessWriter != null) && !Microsoft.Build.Shared.FileUtilities.IsSolutionFilename(projectFile))
  114. {
  115. Microsoft.Build.Evaluation.Project project2 = projectCollection.LoadProject(projectFile, globalProperties, toolsVersion);
  116. project2.SaveLogicalProject(preprocessWriter);
  117. projectCollection.UnloadProject(project2);
  118. return flag;
  119. }
  120. BuildRequestData requestData = new BuildRequestData(projectFile, globalProperties, toolsVersion, targets, null);
  121. BuildParameters parameters = new BuildParameters(projectCollection);
  122. if (!string.Equals(Environment.GetEnvironmentVariable("MSBUILDLOGASYNC"), "1", StringComparison.Ordinal))
  123. {
  124. parameters.UseSynchronousLogging = true;
  125. }
  126. parameters.EnableNodeReuse = enableNodeReuse;
  127. parameters.NodeExeLocation = Assembly.GetExecutingAssembly().Location;
  128. parameters.MaxNodeCount = cpuCount;
  129. parameters.Loggers = projectCollection.Loggers;
  130. parameters.ForwardingLoggers = list;
  131. parameters.ToolsetDefinitionLocations = Microsoft.Build.Evaluation.ToolsetDefinitionLocations.Registry | Microsoft.Build.Evaluation.ToolsetDefinitionLocations.ConfigurationFile;
  132. parameters.DetailedSummary = detailedSummary;
  133. if (!string.IsNullOrEmpty(toolsVersion))
  134. {
  135. parameters.DefaultToolsVersion = toolsVersion;
  136. }
  137. string environmentVariable = Environment.GetEnvironmentVariable("MSBUILDMEMORYUSELIMIT");
  138. if (!string.IsNullOrEmpty(environmentVariable))
  139. {
  140. parameters.MemoryUseLimit = Convert.ToInt32(environmentVariable, CultureInfo.InvariantCulture);
  141. if (parameters.MemoryUseLimit < parameters.MaxNodeCount)
  142. {
  143. parameters.MemoryUseLimit = parameters.MaxNodeCount;
  144. }
  145. }
  146. BuildManager defaultBuildManager = BuildManager.DefaultBuildManager;
  147. Microsoft.Build.Execution.BuildResult result = null;
  148. defaultBuildManager.BeginBuild(parameters);
  149. Exception exception = null;
  150. try
  151. {
  152. try
  153. {
  154. lock (buildLock)
  155. {
  156. activeBuild = defaultBuildManager.PendBuildRequest(requestData);
  157. }
  158. result = activeBuild.Execute();
  159. }
  160. finally
  161. {
  162. defaultBuildManager.EndBuild();
  163. }
  164. }
  165. catch (Exception exception2)
  166. {
  167. exception = exception2;
  168. flag = false;
  169. }
  170. if ((result != null) && (exception == null))
  171. {
  172. flag = result.OverallResult == BuildResultCode.Success;
  173. exception = result.Exception;
  174. }
  175. if (exception != null)
  176. {
  177. flag = false;
  178. if (!(exception.GetType() != typeof(Microsoft.Build.Exceptions.InvalidProjectFileException)))
  179. {
  180. return flag;
  181. }
  182. if ((exception.GetType() == typeof(LoggerException)) || (exception.GetType() == typeof(Microsoft.Build.Exceptions.InternalLoggerException)))
  183. {
  184. throw exception;
  185. }
  186. if (!(exception.GetType() == typeof(BuildAbortedException)))
  187. {
  188. Console.WriteLine(Microsoft.Build.Shared.AssemblyResources.GetString("FatalError"));
  189. Console.WriteLine(exception.ToString());
  190. Console.WriteLine();
  191. throw exception;
  192. }
  193. }
  194. return flag;
  195. }
  196. catch (Microsoft.Build.Exceptions.InvalidProjectFileException exception3)
  197. {
  198. Microsoft.Build.Shared.ErrorUtilities.VerifyThrow(exception3.HasBeenLogged, "Should have been logged");
  199. flag = false;
  200. }
  201. finally
  202. {
  203. Microsoft.Build.Shared.FileUtilities.ClearCacheDirectory();
  204. if (projectCollection != null)
  205. {
  206. projectCollection.Dispose();
  207. }
  208. }
  209. return flag;
  210. }
  211. [MethodImpl(MethodImplOptions.NoInlining)]
  212. private static bool BuildProjectWithOldOM(string projectFile, string[] targets, string toolsVersion, BuildPropertyGroup propertyBag, ILogger[] loggers, LoggerVerbosity verbosity, DistributedLoggerRecord[] distributedLoggerRecords, bool needToValidateProject, string schemaFile, int cpuCount)
  213. {
  214. string directoryName = Path.GetDirectoryName(Assembly.GetAssembly(typeof(MSBuildApp)).Location);
  215. string localNodeProviderParameters = "msbuildlocation=" + directoryName + ";nodereuse=false";
  216. Engine engine = new Engine(propertyBag, Microsoft.Build.BuildEngine.ToolsetDefinitionLocations.Registry | Microsoft.Build.BuildEngine.ToolsetDefinitionLocations.ConfigurationFile, cpuCount, localNodeProviderParameters);
  217. bool flag = false;
  218. try
  219. {
  220. foreach (ILogger logger in loggers)
  221. {
  222. engine.RegisterLogger(logger);
  223. }
  224. if ((((loggers.Length == 1) && (verbosity == LoggerVerbosity.Quiet)) && ((loggers[0].Parameters.IndexOf("ENABLEMPLOGGING", StringComparison.OrdinalIgnoreCase) != -1) && (loggers[0].Parameters.IndexOf("DISABLEMPLOGGING", StringComparison.OrdinalIgnoreCase) == -1))) && ((loggers[0].Parameters.IndexOf("V=", StringComparison.OrdinalIgnoreCase) == -1) && (loggers[0].Parameters.IndexOf("VERBOSITY=", StringComparison.OrdinalIgnoreCase) == -1)))
  225. {
  226. Type type = loggers[0].GetType();
  227. Type type2 = typeof(Microsoft.Build.Logging.ConsoleLogger);
  228. if (type == type2)
  229. {
  230. engine.OnlyLogCriticalEvents = true;
  231. }
  232. }
  233. Microsoft.Build.BuildEngine.Project project = null;
  234. try
  235. {
  236. project = new Microsoft.Build.BuildEngine.Project(engine, toolsVersion);
  237. }
  238. catch (InvalidOperationException exception)
  239. {
  240. InitializationException.Throw("InvalidToolsVersionError", toolsVersion, exception, false);
  241. }
  242. project.IsValidated = needToValidateProject;
  243. project.SchemaFile = schemaFile;
  244. project.Load(projectFile);
  245. flag = engine.BuildProject(project, targets);
  246. }
  247. catch (Microsoft.Build.Exceptions.InvalidProjectFileException)
  248. {
  249. }
  250. finally
  251. {
  252. engine.Shutdown();
  253. }
  254. return flag;
  255. }
  256. private static void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e)
  257. {
  258. if (e.SpecialKey == ConsoleSpecialKey.ControlBreak)
  259. {
  260. e.Cancel = false;
  261. }
  262. else
  263. {
  264. e.Cancel = true;
  265. if (Interlocked.CompareExchange(ref receivedCancel, 1, 0) != 1)
  266. {
  267. Console.WriteLine(Microsoft.Build.Shared.ResourceUtilities.FormatResourceString("AbortingBuild", new object[0]));
  268. WaitCallback callBack = delegate {
  269. cancelComplete.Reset();
  270. if (buildComplete.WaitOne(0, false))
  271. {
  272. cancelComplete.Set();
  273. }
  274. else
  275. {
  276. BuildSubmission activeBuild = null;
  277. lock (buildLock)
  278. {
  279. activeBuild = MSBuildApp.activeBuild;
  280. }
  281. if (activeBuild != null)
  282. {
  283. BuildManager.DefaultBuildManager.CancelAllSubmissions();
  284. buildComplete.WaitOne();
  285. }
  286. cancelComplete.Set();
  287. }
  288. };
  289. ThreadPool.QueueUserWorkItem(callBack);
  290. }
  291. }
  292. }
  293. private static ILogger CreateAndConfigureLogger(Microsoft.Build.Logging.LoggerDescription loggerDescription, LoggerVerbosity verbosity, string unquotedParameter)
  294. {
  295. ILogger logger = null;
  296. try
  297. {
  298. logger = loggerDescription.CreateLogger();
  299. if (logger == null)
  300. {
  301. InitializationException.VerifyThrow(logger != null, "LoggerNotFoundError", unquotedParameter);
  302. }
  303. }
  304. catch (IOException exception)
  305. {
  306. InitializationException.Throw("LoggerCreationError", unquotedParameter, exception, false);
  307. }
  308. catch (BadImageFormatException exception2)
  309. {
  310. InitializationException.Throw("LoggerCreationError", unquotedParameter, exception2, false);
  311. }
  312. catch (SecurityException exception3)
  313. {
  314. InitializationException.Throw("LoggerCreationError", unquotedParameter, exception3, false);
  315. }
  316. catch (ReflectionTypeLoadException exception4)
  317. {
  318. InitializationException.Throw("LoggerCreationError", unquotedParameter, exception4, false);
  319. }
  320. catch (MemberAccessException exception5)
  321. {
  322. InitializationException.Throw("LoggerCreationError", unquotedParameter, exception5, false);
  323. }
  324. catch (TargetInvocationException exception6)
  325. {
  326. InitializationException.Throw("LoggerFatalError", unquotedParameter, exception6.InnerException, true);
  327. }
  328. try
  329. {
  330. logger.Verbosity = verbosity;
  331. if (loggerDescription.LoggerSwitchParameters != null)
  332. {
  333. logger.Parameters = loggerDescription.LoggerSwitchParameters;
  334. }
  335. }
  336. catch (LoggerException)
  337. {
  338. throw;
  339. }
  340. catch (Exception exception7)
  341. {
  342. InitializationException.Throw("LoggerFatalError", unquotedParameter, exception7, true);
  343. }
  344. return logger;
  345. }
  346. private static DistributedLoggerRecord CreateForwardingLoggerRecord(ILogger logger, string loggerParameters, LoggerVerbosity defaultVerbosity)
  347. {
  348. string str2 = ExtractAnyParameterValue(ExtractAnyLoggerParameter(loggerParameters, new string[] { "verbosity", "v" }));
  349. LoggerVerbosity verbosity = defaultVerbosity;
  350. if (!string.IsNullOrEmpty(str2))
  351. {
  352. verbosity = ProcessVerbositySwitch(str2);
  353. }
  354. Assembly assembly = Assembly.GetAssembly(typeof(ProjectCollection));
  355. string loggerClassName = "Microsoft.Build.Logging.ConfigurableForwardingLogger";
  356. string fullName = assembly.GetName().FullName;
  357. return new DistributedLoggerRecord(logger, new Microsoft.Build.Logging.LoggerDescription(loggerClassName, fullName, null, loggerParameters, verbosity));
  358. }
  359. private static void DisplayCopyrightMessage()
  360. {
  361. Console.WriteLine(Microsoft.Build.Shared.ResourceUtilities.FormatResourceString("CopyrightMessage", new object[] { ProjectCollection.Version.ToString(), Environment.Version.ToString() }));
  362. }
  363. private static void DumpAllInCategory(string currentInstance, PerformanceCounterCategory category, bool initializeOnly)
  364. {
  365. if (category.CategoryName.IndexOf("remoting", StringComparison.OrdinalIgnoreCase) == -1)
  366. {
  367. System.Diagnostics.PerformanceCounter[] counters;
  368. try
  369. {
  370. counters = category.GetCounters(currentInstance);
  371. }
  372. catch (InvalidOperationException)
  373. {
  374. return;
  375. }
  376. if (!initializeOnly)
  377. {
  378. Console.WriteLine("\n{0}{1}{0}", new string('=', 0x29 - (category.CategoryName.Length / 2)), category.CategoryName);
  379. }
  380. foreach (System.Diagnostics.PerformanceCounter counter in counters)
  381. {
  382. DumpCounter(counter, initializeOnly);
  383. }
  384. if (!initializeOnly)
  385. {
  386. Console.WriteLine("{0}{0}", new string('=', 0x29));
  387. }
  388. }
  389. }
  390. private static void DumpCounter(System.Diagnostics.PerformanceCounter counter, bool initializeOnly)
  391. {
  392. if (counter.CounterName.IndexOf("not displayed", StringComparison.OrdinalIgnoreCase) == -1)
  393. {
  394. float num = counter.NextValue();
  395. if (!initializeOnly)
  396. {
  397. string friendlyCounterType = GetFriendlyCounterType(counter.CounterType, counter.CounterName);
  398. string format = (num < 10f) ? "{0,20:N2}" : "{0,20:N0}";
  399. string str3 = string.Format(CultureInfo.CurrentCulture, format, new object[] { num });
  400. Console.WriteLine("||{0,50}|{1}|{2,8}|", counter.CounterName, str3, friendlyCounterType);
  401. }
  402. }
  403. }
  404. private static void DumpCounters(bool initializeOnly)
  405. {
  406. Process currentProcess = Process.GetCurrentProcess();
  407. if (!initializeOnly)
  408. {
  409. Console.WriteLine("\n{0}{1}{0}", new string('=', 0x29 - ("Process".Length / 2)), "Process");
  410. Console.WriteLine("||{0,50}|{1,20:N0}|{2,8}|", "Peak Working Set", currentProcess.PeakWorkingSet64, "bytes");
  411. Console.WriteLine("||{0,50}|{1,20:N0}|{2,8}|", "Peak Paged Memory", currentProcess.PeakPagedMemorySize64, "bytes");
  412. Console.WriteLine("||{0,50}|{1,20:N0}|{2,8}|", "Peak Virtual Memory", currentProcess.PeakVirtualMemorySize64, "bytes");
  413. Console.WriteLine("||{0,50}|{1,20:N0}|{2,8}|", "Peak Privileged Processor Time", currentProcess.PrivilegedProcessorTime.TotalMilliseconds, "ms");
  414. Console.WriteLine("||{0,50}|{1,20:N0}|{2,8}|", "Peak User Processor Time", currentProcess.UserProcessorTime.TotalMilliseconds, "ms");
  415. Console.WriteLine("||{0,50}|{1,20:N0}|{2,8}|", "Peak Total Processor Time", currentProcess.TotalProcessorTime.TotalMilliseconds, "ms");
  416. Console.WriteLine("{0}{0}", new string('=', 0x29));
  417. }
  418. string currentInstance = null;
  419. PerformanceCounterCategory category = new PerformanceCounterCategory("Process");
  420. foreach (string str2 in category.GetInstanceNames())
  421. {
  422. System.Diagnostics.PerformanceCounter counter = new System.Diagnostics.PerformanceCounter(".NET CLR Memory", "Process ID", str2, true);
  423. try
  424. {
  425. if (((int) counter.RawValue) == currentProcess.Id)
  426. {
  427. currentInstance = str2;
  428. break;
  429. }
  430. }
  431. catch (InvalidOperationException)
  432. {
  433. }
  434. finally
  435. {
  436. if (counter != null)
  437. {
  438. counter.Dispose();
  439. }
  440. }
  441. }
  442. foreach (PerformanceCounterCategory category2 in PerformanceCounterCategory.GetCategories())
  443. {
  444. DumpAllInCategory(currentInstance, category2, initializeOnly);
  445. }
  446. }
  447. public static ExitType Execute(string projectFile = null, string[] targets = null, string toolsVersion = null, Dictionary<string, string> globalProperties = null, ILogger[] loggers = null, LoggerVerbosity normal = LoggerVerbosity.Normal)
  448. {
  449. ExitType success = ExitType.Success;
  450. ConsoleCancelEventHandler handler = new ConsoleCancelEventHandler(MSBuildApp.Console_CancelKeyPress);
  451. try
  452. {
  453. Microsoft.Internal.Performance.CodeMarkers.Instance.InitPerformanceDll(CodeMarkerApp.MSBUILDPERF, @"Software\Microsoft\MSBuild\4.0");
  454. Console.CancelKeyPress += handler;
  455. VerifyThrowSupportedOS();
  456. SetConsoleUI();
  457. ResetBuildState();
  458. if (Environment.GetEnvironmentVariable("MSBUILDDEBUGONSTART") == "1")
  459. {
  460. Debugger.Launch();
  461. }
  462. if (targets == null)
  463. {
  464. targets = new string[0];
  465. }
  466. if (loggers == null)
  467. {
  468. loggers = new ILogger[0];
  469. }
  470. List<DistributedLoggerRecord> distributedLoggerRecords = new List<DistributedLoggerRecord>();
  471. bool needToValidateProject = false;
  472. string schemaFile = null;
  473. int cpuCount = 1;
  474. bool enableNodeReuse = true;
  475. TextWriter preprocessWriter = null;
  476. bool debugger = false;
  477. bool detailedSummary = false;
  478. if (Environment.GetEnvironmentVariable("MSBUILDOLDOM") != "1")
  479. {
  480. if (!BuildProject(projectFile, targets, toolsVersion, globalProperties, loggers, normal, distributedLoggerRecords.ToArray(), needToValidateProject, schemaFile, cpuCount, enableNodeReuse, preprocessWriter, debugger, detailedSummary))
  481. {
  482. success = ExitType.BuildError;
  483. }
  484. return success;
  485. }
  486. return OldOMBuildProject(success, projectFile, targets, toolsVersion, globalProperties, loggers, normal, needToValidateProject, schemaFile, cpuCount);
  487. }
  488. catch (CommandLineSwitchException exception)
  489. {
  490. Console.WriteLine(exception.Message);
  491. Console.WriteLine();
  492. ShowHelpPrompt();
  493. success = ExitType.SwitchError;
  494. }
  495. catch (Microsoft.Build.Exceptions.InvalidToolsetDefinitionException exception2)
  496. {
  497. Console.WriteLine(Microsoft.Build.Shared.ResourceUtilities.FormatResourceString("ConfigurationFailurePrefixNoErrorCode", new object[] { exception2.ErrorCode, exception2.Message }));
  498. success = ExitType.InitializationError;
  499. }
  500. catch (InitializationException exception3)
  501. {
  502. Console.WriteLine(exception3.Message);
  503. success = ExitType.InitializationError;
  504. }
  505. catch (LoggerException exception4)
  506. {
  507. if (exception4.ErrorCode != null)
  508. {
  509. Console.WriteLine(Microsoft.Build.Shared.ResourceUtilities.FormatResourceString("LoggerFailurePrefixNoErrorCode", new object[] { exception4.ErrorCode, exception4.Message }));
  510. }
  511. else
  512. {
  513. Console.WriteLine(Microsoft.Build.Shared.ResourceUtilities.FormatResourceString("LoggerFailurePrefixWithErrorCode", new object[] { exception4.Message }));
  514. }
  515. if (exception4.InnerException != null)
  516. {
  517. Console.WriteLine(exception4.InnerException.ToString());
  518. }
  519. success = ExitType.LoggerAbort;
  520. }
  521. catch (Microsoft.Build.Exceptions.InternalLoggerException exception5)
  522. {
  523. if (!exception5.InitializationException)
  524. {
  525. Console.WriteLine("MSBUILD : error " + exception5.ErrorCode + ": " + exception5.Message);
  526. Console.WriteLine(exception5.InnerException.ToString());
  527. return ExitType.LoggerFailure;
  528. }
  529. Console.WriteLine("MSBUILD : error " + exception5.ErrorCode + ": " + exception5.Message + ((exception5.InnerException != null) ? (" " + exception5.InnerException.Message) : ""));
  530. return ExitType.InitializationError;
  531. }
  532. catch (BuildAbortedException exception6)
  533. {
  534. Console.WriteLine("MSBUILD : error " + exception6.ErrorCode + ": " + exception6.Message + ((exception6.InnerException != null) ? (" " + exception6.InnerException.Message) : string.Empty));
  535. success = ExitType.Unexpected;
  536. }
  537. catch (Exception exception7)
  538. {
  539. Console.WriteLine("{0}\r\n{1}", Microsoft.Build.Shared.AssemblyResources.GetString("FatalError"), exception7.ToString());
  540. throw;
  541. }
  542. finally
  543. {
  544. buildComplete.Set();
  545. Console.CancelKeyPress -= handler;
  546. cancelComplete.WaitOne();
  547. Microsoft.Internal.Performance.CodeMarkers.Instance.UninitializePerformanceDLL(CodeMarkerApp.MSBUILDPERF);
  548. }
  549. return success;
  550. }
  551. public static ExitType Execute(string commandLine)
  552. {
  553. Microsoft.Build.Shared.ErrorUtilities.VerifyThrowArgumentLength(commandLine, "commandLine");
  554. ExitType success = ExitType.Success;
  555. ConsoleCancelEventHandler handler = new ConsoleCancelEventHandler(MSBuildApp.Console_CancelKeyPress);
  556. try
  557. {
  558. Microsoft.Internal.Performance.CodeMarkers.Instance.InitPerformanceDll(CodeMarkerApp.MSBUILDPERF, @"Software\Microsoft\MSBuild\4.0");
  559. Console.CancelKeyPress += handler;
  560. VerifyThrowSupportedOS();
  561. SetConsoleUI();
  562. ResetBuildState();
  563. if (Environment.GetEnvironmentVariable("MSBUILDDEBUGONSTART") == "1")
  564. {
  565. Debugger.Launch();
  566. }
  567. string projectFile = null;
  568. string[] targets = new string[0];
  569. string toolsVersion = null;
  570. Dictionary<string, string> globalProperties = null;
  571. ILogger[] loggers = new ILogger[0];
  572. LoggerVerbosity normal = LoggerVerbosity.Normal;
  573. List<DistributedLoggerRecord> distributedLoggerRecords = null;
  574. bool needToValidateProject = false;
  575. string schemaFile = null;
  576. int cpuCount = 1;
  577. bool enableNodeReuse = true;
  578. TextWriter preprocessWriter = null;
  579. bool debugger = false;
  580. bool detailedSummary = false;
  581. if (!ProcessCommandLineSwitches(GatherAllSwitches(commandLine), ref projectFile, ref targets, ref toolsVersion, ref globalProperties, ref loggers, ref normal, ref distributedLoggerRecords, ref needToValidateProject, ref schemaFile, ref cpuCount, ref enableNodeReuse, ref preprocessWriter, ref debugger, ref detailedSummary))
  582. {
  583. return success;
  584. }
  585. if (Environment.GetEnvironmentVariable("MSBUILDOLDOM") != "1")
  586. {
  587. if (!BuildProject(projectFile, targets, toolsVersion, globalProperties, loggers, normal, distributedLoggerRecords.ToArray(), needToValidateProject, schemaFile, cpuCount, enableNodeReuse, preprocessWriter, debugger, detailedSummary))
  588. {
  589. success = ExitType.BuildError;
  590. }
  591. return success;
  592. }
  593. return OldOMBuildProject(success, projectFile, targets, toolsVersion, globalProperties, loggers, normal, needToValidateProject, schemaFile, cpuCount);
  594. }
  595. catch (CommandLineSwitchException exception)
  596. {
  597. Console.WriteLine(exception.Message);
  598. Console.WriteLine();
  599. ShowHelpPrompt();
  600. success = ExitType.SwitchError;
  601. }
  602. catch (Microsoft.Build.Exceptions.InvalidToolsetDefinitionException exception2)
  603. {
  604. Console.WriteLine(Microsoft.Build.Shared.ResourceUtilities.FormatResourceString("ConfigurationFailurePrefixNoErrorCode", new object[] { exception2.ErrorCode, exception2.Message }));
  605. success = ExitType.InitializationError;
  606. }
  607. catch (InitializationException exception3)
  608. {
  609. Console.WriteLine(exception3.Message);
  610. success = ExitType.InitializationError;
  611. }
  612. catch (LoggerException exception4)
  613. {
  614. if (exception4.ErrorCode != null)
  615. {
  616. Console.WriteLine(Microsoft.Build.Shared.ResourceUtilities.FormatResourceString("LoggerFailurePrefixNoErrorCode", new object[] { exception4.ErrorCode, exception4.Message }));
  617. }
  618. else
  619. {
  620. Console.WriteLine(Microsoft.Build.Shared.ResourceUtilities.FormatResourceString("LoggerFailurePrefixWithErrorCode", new object[] { exception4.Message }));
  621. }
  622. if (exception4.InnerException != null)
  623. {
  624. Console.WriteLine(exception4.InnerException.ToString());
  625. }
  626. success = ExitType.LoggerAbort;
  627. }
  628. catch (Microsoft.Build.Exceptions.InternalLoggerException exception5)
  629. {
  630. if (!exception5.InitializationException)
  631. {
  632. Console.WriteLine("MSBUILD : error " + exception5.ErrorCode + ": " + exception5.Message);
  633. Console.WriteLine(exception5.InnerException.ToString());
  634. return ExitType.LoggerFailure;
  635. }
  636. Console.WriteLine("MSBUILD : error " + exception5.ErrorCode + ": " + exception5.Message + ((exception5.InnerException != null) ? (" " + exception5.InnerException.Message) : ""));
  637. return ExitType.InitializationError;
  638. }
  639. catch (BuildAbortedException exception6)
  640. {
  641. Console.WriteLine("MSBUILD : error " + exception6.ErrorCode + ": " + exception6.Message + ((exception6.InnerException != null) ? (" " + exception6.InnerException.Message) : string.Empty));
  642. success = ExitType.Unexpected;
  643. }
  644. catch (Exception exception7)
  645. {
  646. Console.WriteLine("{0}\r\n{1}", Microsoft.Build.Shared.AssemblyResources.GetString("FatalError"), exception7.ToString());
  647. throw;
  648. }
  649. finally
  650. {
  651. buildComplete.Set();
  652. Console.CancelKeyPress -= handler;
  653. cancelComplete.WaitOne();
  654. Microsoft.Internal.Performance.CodeMarkers.Instance.UninitializePerformanceDLL(CodeMarkerApp.MSBUILDPERF);
  655. }
  656. return success;
  657. }
  658. internal static string ExtractAnyLoggerParameter(string parameters, params string[] parameterNames)
  659. {
  660. string[] strArray = parameters.Split(new char[] { ';' });
  661. string str = null;
  662. foreach (string str2 in strArray)
  663. {
  664. foreach (string str3 in parameterNames)
  665. {
  666. if (str2.StartsWith(str3 + "=", StringComparison.OrdinalIgnoreCase) || string.Equals(str3, str2, StringComparison.OrdinalIgnoreCase))
  667. {
  668. str = str2;
  669. }
  670. }
  671. }
  672. return str;
  673. }
  674. private static string ExtractAnyParameterValue(string parameter)
  675. {
  676. string str = null;
  677. if (!string.IsNullOrEmpty(parameter))
  678. {
  679. string[] strArray = parameter.Split(new char[] { '=' });
  680. str = (strArray.Length > 1) ? strArray[1] : null;
  681. }
  682. return str;
  683. }
  684. internal static string ExtractSwitchParameters(string commandLineArg, string unquotedCommandLineArg, int doubleQuotesRemovedFromArg, string switchName, int switchParameterIndicator)
  685. {
  686. string str = null;
  687. int num2;
  688. int index = commandLineArg.IndexOf(':');
  689. string str2 = QuotingUtilities.Unquote(commandLineArg.Substring(0, index), out num2);
  690. Microsoft.Build.Shared.ErrorUtilities.VerifyThrow(switchName == str2.Substring(1), "The switch name extracted from either the partially or completely unquoted arg should be the same.");
  691. Microsoft.Build.Shared.ErrorUtilities.VerifyThrow(doubleQuotesRemovedFromArg >= num2, "The name portion of the switch cannot contain more quoting than the arg itself.");
  692. if ((num2 % 2) == 0)
  693. {
  694. str = commandLineArg.Substring(index);
  695. }
  696. else
  697. {
  698. int num3 = commandLineArg.IndexOf('"', index + 1);
  699. if (((doubleQuotesRemovedFromArg - num2) <= 1) && ((num3 == -1) || (num3 == (commandLineArg.Length - 1))))
  700. {
  701. str = unquotedCommandLineArg.Substring(switchParameterIndicator);
  702. }
  703. else
  704. {
  705. str = ":\"" + commandLineArg.Substring(index + 1);
  706. }
  707. }
  708. Microsoft.Build.Shared.ErrorUtilities.VerifyThrow(str != null, "We must be able to extract the switch parameters.");
  709. return str;
  710. }
  711. private static CommandLineSwitches GatherAllSwitches(string commandLine)
  712. {
  713. ArrayList commandLineArgs = QuotingUtilities.SplitUnquoted(commandLine, new char[0]);
  714. CommandLineSwitches commandLineSwitches = new CommandLineSwitches();
  715. GatherCommandLineSwitches(commandLineArgs, commandLineSwitches);
  716. return GatherAutoResponseFileSwitches(commandLineSwitches);
  717. }
  718. private static CommandLineSwitches GatherAutoResponseFileSwitches(CommandLineSwitches commandLineSwitches)
  719. {
  720. CommandLineSwitches switches = commandLineSwitches;
  721. if (!commandLineSwitches[CommandLineSwitches.ParameterlessSwitch.NoAutoResponse])
  722. {
  723. string path = Path.Combine(exePath, "MSBuild.rsp");
  724. if (!File.Exists(path))
  725. {
  726. return switches;
  727. }
  728. switches = new CommandLineSwitches();
  729. GatherResponseFileSwitch("@" + path, switches);
  730. if (switches[CommandLineSwitches.ParameterlessSwitch.NoAutoResponse])
  731. {
  732. switches.SetSwitchError("CannotAutoDisableAutoResponseFile", switches.GetParameterlessSwitchCommandLineArg(CommandLineSwitches.ParameterlessSwitch.NoAutoResponse));
  733. }
  734. if (switches.HaveAnySwitchesBeenSet())
  735. {
  736. usingSwitchesFromAutoResponseFile = true;
  737. }
  738. switches.Append(commandLineSwitches);
  739. }
  740. return switches;
  741. }
  742. internal static void GatherCommandLineSwitches(ArrayList commandLineArgs, CommandLineSwitches commandLineSwitches)
  743. {
  744. foreach (string str in commandLineArgs)
  745. {
  746. int num;
  747. string unquotedCommandLineArg = QuotingUtilities.Unquote(str, out num);
  748. if (unquotedCommandLineArg.Length > 0)
  749. {
  750. string str3;
  751. string str4;
  752. CommandLineSwitches.ParameterlessSwitch switch2;
  753. string str5;
  754. if (unquotedCommandLineArg.StartsWith("@", StringComparison.Ordinal))
  755. {
  756. GatherResponseFileSwitch(unquotedCommandLineArg, commandLineSwitches);
  757. continue;
  758. }
  759. if (!unquotedCommandLineArg.StartsWith("-", StringComparison.Ordinal) && !unquotedCommandLineArg.StartsWith("/", StringComparison.Ordinal))
  760. {
  761. str3 = null;
  762. str4 = ":" + str;
  763. }
  764. else
  765. {
  766. int index = unquotedCommandLineArg.IndexOf(':');
  767. if (index == -1)
  768. {
  769. str3 = unquotedCommandLineArg.Substring(1);
  770. str4 = string.Empty;
  771. }
  772. else
  773. {
  774. str3 = unquotedCommandLineArg.Substring(1, index - 1);
  775. str4 = ExtractSwitchParameters(str, unquotedCommandLineArg, num, str3, index);
  776. }
  777. }
  778. if (string.IsNullOrEmpty(str4) && (string.Equals(str3, "m", StringComparison.OrdinalIgnoreCase) || string.Equals(str3, "maxcpucount", StringComparison.OrdinalIgnoreCase)))
  779. {
  780. int processorCount = Environment.ProcessorCount;
  781. str4 = ":" + processorCount;
  782. }
  783. if (CommandLineSwitches.IsParameterlessSwitch(str3, out switch2, out str5))
  784. {
  785. GatherParameterlessCommandLineSwitch(commandLineSwitches, switch2, str4, str5, unquotedCommandLineArg);
  786. }
  787. else
  788. {
  789. CommandLineSwitches.ParameterizedSwitch switch3;
  790. bool flag;
  791. string str6;
  792. bool flag2;
  793. if (CommandLineSwitches.IsParameterizedSwitch(str3, out switch3, out str5, out flag, out str6, out flag2))
  794. {
  795. GatherParameterizedCommandLineSwitch(commandLineSwitches, switch3, str4, str5, flag, str6, flag2, unquotedCommandLineArg);
  796. continue;
  797. }
  798. commandLineSwitches.SetUnknownSwitchError(unquotedCommandLineArg);
  799. }
  800. }
  801. }
  802. }
  803. private static void GatherParameterizedCommandLineSwitch(CommandLineSwitches commandLineSwitches, CommandLineSwitches.ParameterizedSwitch parameterizedSwitch, string switchParameters, string duplicateSwitchErrorMessage, bool multipleParametersAllowed, string missingParametersErrorMessage, bool unquoteParameters, string unquotedCommandLineArg)
  804. {
  805. if ((switchParameters.Length > 1) || (missingParametersErrorMessage == null))
  806. {
  807. if (commandLineSwitches.IsParameterizedSwitchSet(parameterizedSwitch) && (duplicateSwitchErrorMessage != null))
  808. {
  809. commandLineSwitches.SetSwitchError(duplicateSwitchErrorMessage, unquotedCommandLineArg);
  810. }
  811. else
  812. {
  813. if (switchParameters.Length > 0)
  814. {
  815. switchParameters = switchParameters.Substring(1);
  816. }
  817. if (!commandLineSwitches.SetParameterizedSwitch(parameterizedSwitch, unquotedCommandLineArg, switchParameters, multipleParametersAllowed, unquoteParameters) && (missingParametersErrorMessage != null))
  818. {
  819. commandLineSwitches.SetSwitchError(missingParametersErrorMessage, unquotedCommandLineArg);
  820. }
  821. }
  822. }
  823. else
  824. {
  825. commandLineSwitches.SetSwitchError(missingParametersErrorMessage, unquotedCommandLineArg);
  826. }
  827. }
  828. private static void GatherParameterlessCommandLineSwitch(CommandLineSwitches commandLineSwitches, CommandLineSwitches.ParameterlessSwitch parameterlessSwitch, string switchParameters, string duplicateSwitchErrorMessage, string unquotedCommandLineArg)
  829. {
  830. if (switchParameters.Length == 0)
  831. {
  832. if (!commandLineSwitches.IsParameterlessSwitchSet(parameterlessSwitch) || (duplicateSwitchErrorMessage == null))
  833. {
  834. commandLineSwitches.SetParameterlessSwitch(parameterlessSwitch, unquotedCommandLineArg);
  835. }
  836. else
  837. {
  838. commandLineSwitches.SetSwitchError(duplicateSwitchErrorMessage, unquotedCommandLineArg);
  839. }
  840. }
  841. else
  842. {
  843. commandLineSwitches.SetUnexpectedParametersError(unquotedCommandLineArg);
  844. }
  845. }
  846. private static void GatherResponseFileSwitch(string unquotedCommandLineArg, CommandLineSwitches commandLineSwitches)
  847. {
  848. try
  849. {
  850. string path = unquotedCommandLineArg.Substring(1);
  851. if (path.Length == 0)
  852. {
  853. commandLineSwitches.SetSwitchError("MissingResponseFileError", unquotedCommandLineArg);
  854. }
  855. else if (!File.Exists(path))
  856. {
  857. commandLineSwitches.SetParameterError("ResponseFileNotFoundError", unquotedCommandLineArg);
  858. }
  859. else
  860. {
  861. path = Path.GetFullPath(path);
  862. bool flag = false;
  863. foreach (string str2 in includedResponseFiles)
  864. {
  865. if (string.Compare(path, str2, StringComparison.OrdinalIgnoreCase) == 0)
  866. {
  867. commandLineSwitches.SetParameterError("RepeatedResponseFileError", unquotedCommandLineArg);
  868. flag = true;
  869. break;
  870. }
  871. }
  872. if (!flag)
  873. {
  874. ArrayList list;
  875. includedResponseFiles.Add(path);
  876. using (StreamReader reader = new StreamReader(path, Encoding.Default))
  877. {
  878. list = new ArrayList();
  879. while (reader.Peek() != -1)
  880. {
  881. string name = reader.ReadLine().TrimStart(new char[0]);
  882. if (!name.StartsWith("#", StringComparison.Ordinal))
  883. {
  884. list.AddRange(QuotingUtilities.SplitUnquoted(Environment.ExpandEnvironmentVariables(name), new char[0]));
  885. }
  886. }
  887. }
  888. GatherCommandLineSwitches(list, commandLineSwitches);
  889. }
  890. }
  891. }
  892. catch (NotSupportedException exception)
  893. {
  894. commandLineSwitches.SetParameterError("ReadResponseFileError", unquotedCommandLineArg, exception);
  895. }
  896. catch (SecurityException exception2)
  897. {
  898. commandLineSwitches.SetParameterError("ReadResponseFileError", unquotedCommandLineArg, exception2);
  899. }
  900. catch (UnauthorizedAccessException exception3)
  901. {
  902. commandLineSwitches.SetParameterError("ReadResponseFileError", unquotedCommandLineArg, exception3);
  903. }
  904. catch (IOException exception4)
  905. {
  906. commandLineSwitches.SetParameterError("ReadResponseFileError", unquotedCommandLineArg, exception4);
  907. }
  908. }
  909. private static string GetFriendlyCounterType(PerformanceCounterType type, string name)
  910. {
  911. if (name.IndexOf("bytes", StringComparison.OrdinalIgnoreCase) != -1)
  912. {
  913. return "bytes";
  914. }
  915. if (name.IndexOf("threads", StringComparison.OrdinalIgnoreCase) != -1)
  916. {
  917. return "threads";
  918. }
  919. switch (type)
  920. {
  921. case PerformanceCounterType.NumberOfItems64:
  922. case PerformanceCounterType.CounterDelta32:
  923. case PerformanceCounterType.CounterDelta64:
  924. case PerformanceCounterType.NumberOfItemsHEX32:
  925. case PerformanceCounterType.NumberOfItemsHEX64:
  926. case PerformanceCounterType.NumberOfItems32:
  927. case PerformanceCounterType.SampleCounter:
  928. case PerformanceCounterType.CountPerTimeInterval32:
  929. case PerformanceCounterType.CountPerTimeInterval64:
  930. case PerformanceCounterType.CounterTimer:
  931. case PerformanceCounterType.RateOfCountsPerSecond32:
  932. case PerformanceCounterType.RateOfCountsPerSecond64:
  933. case PerformanceCounterType.CounterMultiTimer:
  934. case PerformanceCounterType.CounterTimerInverse:
  935. case PerformanceCounterType.CounterMultiTimerInverse:
  936. case PerformanceCounterType.AverageCount64:
  937. return "#";
  938. case PerformanceCounterType.RawFraction:
  939. case PerformanceCounterType.CounterMultiTimer100Ns:
  940. case PerformanceCounterType.SampleFraction:
  941. case PerformanceCounterType.CounterMultiTimer100NsInverse:
  942. return "%";
  943. case PerformanceCounterType.Timer100NsInverse:
  944. case PerformanceCounterType.Timer100Ns:
  945. return "100ns";

Large files files are truncated, but you can click here to view the full file