PageRenderTime 59ms CodeModel.GetById 20ms RepoModel.GetById 1ms app.codeStats 0ms

/MSBuild/Microsoft/Build/CommandLine/MSBuildApp.cs

#
C# | 1572 lines | 1556 code | 16 blank | 0 comment | 114 complexity | 6afbea180ca6202e4e0a75006a7993f9 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 commandLine)
  448. {
  449. Microsoft.Build.Shared.ErrorUtilities.VerifyThrowArgumentLength(commandLine, "commandLine");
  450. ExitType success = ExitType.Success;
  451. ConsoleCancelEventHandler handler = new ConsoleCancelEventHandler(MSBuildApp.Console_CancelKeyPress);
  452. try
  453. {
  454. Microsoft.Internal.Performance.CodeMarkers.Instance.InitPerformanceDll(CodeMarkerApp.MSBUILDPERF, @"Software\Microsoft\MSBuild\4.0");
  455. Console.CancelKeyPress += handler;
  456. VerifyThrowSupportedOS();
  457. SetConsoleUI();
  458. ResetBuildState();
  459. if (Environment.GetEnvironmentVariable("MSBUILDDEBUGONSTART") == "1")
  460. {
  461. Debugger.Launch();
  462. }
  463. string projectFile = null;
  464. string[] targets = new string[0];
  465. string toolsVersion = null;
  466. Dictionary<string, string> globalProperties = null;
  467. ILogger[] loggers = new ILogger[0];
  468. LoggerVerbosity normal = LoggerVerbosity.Normal;
  469. List<DistributedLoggerRecord> distributedLoggerRecords = null;
  470. bool needToValidateProject = false;
  471. string schemaFile = null;
  472. int cpuCount = 1;
  473. bool enableNodeReuse = true;
  474. TextWriter preprocessWriter = null;
  475. bool debugger = false;
  476. bool detailedSummary = false;
  477. 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))
  478. {
  479. return success;
  480. }
  481. if (Environment.GetEnvironmentVariable("MSBUILDOLDOM") != "1")
  482. {
  483. if (!BuildProject(projectFile, targets, toolsVersion, globalProperties, loggers, normal, distributedLoggerRecords.ToArray(), needToValidateProject, schemaFile, cpuCount, enableNodeReuse, preprocessWriter, debugger, detailedSummary))
  484. {
  485. success = ExitType.BuildError;
  486. }
  487. return success;
  488. }
  489. return OldOMBuildProject(success, projectFile, targets, toolsVersion, globalProperties, loggers, normal, needToValidateProject, schemaFile, cpuCount);
  490. }
  491. catch (CommandLineSwitchException exception)
  492. {
  493. Console.WriteLine(exception.Message);
  494. Console.WriteLine();
  495. ShowHelpPrompt();
  496. success = ExitType.SwitchError;
  497. }
  498. catch (Microsoft.Build.Exceptions.InvalidToolsetDefinitionException exception2)
  499. {
  500. Console.WriteLine(Microsoft.Build.Shared.ResourceUtilities.FormatResourceString("ConfigurationFailurePrefixNoErrorCode", new object[] { exception2.ErrorCode, exception2.Message }));
  501. success = ExitType.InitializationError;
  502. }
  503. catch (InitializationException exception3)
  504. {
  505. Console.WriteLine(exception3.Message);
  506. success = ExitType.InitializationError;
  507. }
  508. catch (LoggerException exception4)
  509. {
  510. if (exception4.ErrorCode != null)
  511. {
  512. Console.WriteLine(Microsoft.Build.Shared.ResourceUtilities.FormatResourceString("LoggerFailurePrefixNoErrorCode", new object[] { exception4.ErrorCode, exception4.Message }));
  513. }
  514. else
  515. {
  516. Console.WriteLine(Microsoft.Build.Shared.ResourceUtilities.FormatResourceString("LoggerFailurePrefixWithErrorCode", new object[] { exception4.Message }));
  517. }
  518. if (exception4.InnerException != null)
  519. {
  520. Console.WriteLine(exception4.InnerException.ToString());
  521. }
  522. success = ExitType.LoggerAbort;
  523. }
  524. catch (Microsoft.Build.Exceptions.InternalLoggerException exception5)
  525. {
  526. if (!exception5.InitializationException)
  527. {
  528. Console.WriteLine("MSBUILD : error " + exception5.ErrorCode + ": " + exception5.Message);
  529. Console.WriteLine(exception5.InnerException.ToString());
  530. return ExitType.LoggerFailure;
  531. }
  532. Console.WriteLine("MSBUILD : error " + exception5.ErrorCode + ": " + exception5.Message + ((exception5.InnerException != null) ? (" " + exception5.InnerException.Message) : ""));
  533. return ExitType.InitializationError;
  534. }
  535. catch (BuildAbortedException exception6)
  536. {
  537. Console.WriteLine("MSBUILD : error " + exception6.ErrorCode + ": " + exception6.Message + ((exception6.InnerException != null) ? (" " + exception6.InnerException.Message) : string.Empty));
  538. success = ExitType.Unexpected;
  539. }
  540. catch (Exception exception7)
  541. {
  542. Console.WriteLine("{0}\r\n{1}", Microsoft.Build.Shared.AssemblyResources.GetString("FatalError"), exception7.ToString());
  543. throw;
  544. }
  545. finally
  546. {
  547. buildComplete.Set();
  548. Console.CancelKeyPress -= handler;
  549. cancelComplete.WaitOne();
  550. Microsoft.Internal.Performance.CodeMarkers.Instance.UninitializePerformanceDLL(CodeMarkerApp.MSBUILDPERF);
  551. }
  552. return success;
  553. }
  554. internal static string ExtractAnyLoggerParameter(string parameters, params string[] parameterNames)
  555. {
  556. string[] strArray = parameters.Split(new char[] { ';' });
  557. string str = null;
  558. foreach (string str2 in strArray)
  559. {
  560. foreach (string str3 in parameterNames)
  561. {
  562. if (str2.StartsWith(str3 + "=", StringComparison.OrdinalIgnoreCase) || string.Equals(str3, str2, StringComparison.OrdinalIgnoreCase))
  563. {
  564. str = str2;
  565. }
  566. }
  567. }
  568. return str;
  569. }
  570. private static string ExtractAnyParameterValue(string parameter)
  571. {
  572. string str = null;
  573. if (!string.IsNullOrEmpty(parameter))
  574. {
  575. string[] strArray = parameter.Split(new char[] { '=' });
  576. str = (strArray.Length > 1) ? strArray[1] : null;
  577. }
  578. return str;
  579. }
  580. internal static string ExtractSwitchParameters(string commandLineArg, string unquotedCommandLineArg, int doubleQuotesRemovedFromArg, string switchName, int switchParameterIndicator)
  581. {
  582. string str = null;
  583. int num2;
  584. int index = commandLineArg.IndexOf(':');
  585. string str2 = QuotingUtilities.Unquote(commandLineArg.Substring(0, index), out num2);
  586. 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.");
  587. Microsoft.Build.Shared.ErrorUtilities.VerifyThrow(doubleQuotesRemovedFromArg >= num2, "The name portion of the switch cannot contain more quoting than the arg itself.");
  588. if ((num2 % 2) == 0)
  589. {
  590. str = commandLineArg.Substring(index);
  591. }
  592. else
  593. {
  594. int num3 = commandLineArg.IndexOf('"', index + 1);
  595. if (((doubleQuotesRemovedFromArg - num2) <= 1) && ((num3 == -1) || (num3 == (commandLineArg.Length - 1))))
  596. {
  597. str = unquotedCommandLineArg.Substring(switchParameterIndicator);
  598. }
  599. else
  600. {
  601. str = ":\"" + commandLineArg.Substring(index + 1);
  602. }
  603. }
  604. Microsoft.Build.Shared.ErrorUtilities.VerifyThrow(str != null, "We must be able to extract the switch parameters.");
  605. return str;
  606. }
  607. private static CommandLineSwitches GatherAllSwitches(string commandLine)
  608. {
  609. ArrayList commandLineArgs = QuotingUtilities.SplitUnquoted(commandLine, new char[0]);
  610. commandLineArgs.RemoveAt(0);
  611. CommandLineSwitches commandLineSwitches = new CommandLineSwitches();
  612. GatherCommandLineSwitches(commandLineArgs, commandLineSwitches);
  613. return GatherAutoResponseFileSwitches(commandLineSwitches);
  614. }
  615. private static CommandLineSwitches GatherAutoResponseFileSwitches(CommandLineSwitches commandLineSwitches)
  616. {
  617. CommandLineSwitches switches = commandLineSwitches;
  618. if (!commandLineSwitches[CommandLineSwitches.ParameterlessSwitch.NoAutoResponse])
  619. {
  620. string path = Path.Combine(exePath, "MSBuild.rsp");
  621. if (!File.Exists(path))
  622. {
  623. return switches;
  624. }
  625. switches = new CommandLineSwitches();
  626. GatherResponseFileSwitch("@" + path, switches);
  627. if (switches[CommandLineSwitches.ParameterlessSwitch.NoAutoResponse])
  628. {
  629. switches.SetSwitchError("CannotAutoDisableAutoResponseFile", switches.GetParameterlessSwitchCommandLineArg(CommandLineSwitches.ParameterlessSwitch.NoAutoResponse));
  630. }
  631. if (switches.HaveAnySwitchesBeenSet())
  632. {
  633. usingSwitchesFromAutoResponseFile = true;
  634. }
  635. switches.Append(commandLineSwitches);
  636. }
  637. return switches;
  638. }
  639. internal static void GatherCommandLineSwitches(ArrayList commandLineArgs, CommandLineSwitches commandLineSwitches)
  640. {
  641. foreach (string str in commandLineArgs)
  642. {
  643. int num;
  644. string unquotedCommandLineArg = QuotingUtilities.Unquote(str, out num);
  645. if (unquotedCommandLineArg.Length > 0)
  646. {
  647. string str3;
  648. string str4;
  649. CommandLineSwitches.ParameterlessSwitch switch2;
  650. string str5;
  651. if (unquotedCommandLineArg.StartsWith("@", StringComparison.Ordinal))
  652. {
  653. GatherResponseFileSwitch(unquotedCommandLineArg, commandLineSwitches);
  654. continue;
  655. }
  656. if (!unquotedCommandLineArg.StartsWith("-", StringComparison.Ordinal) && !unquotedCommandLineArg.StartsWith("/", StringComparison.Ordinal))
  657. {
  658. str3 = null;
  659. str4 = ":" + str;
  660. }
  661. else
  662. {
  663. int index = unquotedCommandLineArg.IndexOf(':');
  664. if (index == -1)
  665. {
  666. str3 = unquotedCommandLineArg.Substring(1);
  667. str4 = string.Empty;
  668. }
  669. else
  670. {
  671. str3 = unquotedCommandLineArg.Substring(1, index - 1);
  672. str4 = ExtractSwitchParameters(str, unquotedCommandLineArg, num, str3, index);
  673. }
  674. }
  675. if (string.IsNullOrEmpty(str4) && (string.Equals(str3, "m", StringComparison.OrdinalIgnoreCase) || string.Equals(str3, "maxcpucount", StringComparison.OrdinalIgnoreCase)))
  676. {
  677. int processorCount = Environment.ProcessorCount;
  678. str4 = ":" + processorCount;
  679. }
  680. if (CommandLineSwitches.IsParameterlessSwitch(str3, out switch2, out str5))
  681. {
  682. GatherParameterlessCommandLineSwitch(commandLineSwitches, switch2, str4, str5, unquotedCommandLineArg);
  683. }
  684. else
  685. {
  686. CommandLineSwitches.ParameterizedSwitch switch3;
  687. bool flag;
  688. string str6;
  689. bool flag2;
  690. if (CommandLineSwitches.IsParameterizedSwitch(str3, out switch3, out str5, out flag, out str6, out flag2))
  691. {
  692. GatherParameterizedCommandLineSwitch(commandLineSwitches, switch3, str4, str5, flag, str6, flag2, unquotedCommandLineArg);
  693. continue;
  694. }
  695. commandLineSwitches.SetUnknownSwitchError(unquotedCommandLineArg);
  696. }
  697. }
  698. }
  699. }
  700. private static void GatherParameterizedCommandLineSwitch(CommandLineSwitches commandLineSwitches, CommandLineSwitches.ParameterizedSwitch parameterizedSwitch, string switchParameters, string duplicateSwitchErrorMessage, bool multipleParametersAllowed, string missingParametersErrorMessage, bool unquoteParameters, string unquotedCommandLineArg)
  701. {
  702. if ((switchParameters.Length > 1) || (missingParametersErrorMessage == null))
  703. {
  704. if (commandLineSwitches.IsParameterizedSwitchSet(parameterizedSwitch) && (duplicateSwitchErrorMessage != null))
  705. {
  706. commandLineSwitches.SetSwitchError(duplicateSwitchErrorMessage, unquotedCommandLineArg);
  707. }
  708. else
  709. {
  710. if (switchParameters.Length > 0)
  711. {
  712. switchParameters = switchParameters.Substring(1);
  713. }
  714. if (!commandLineSwitches.SetParameterizedSwitch(parameterizedSwitch, unquotedCommandLineArg, switchParameters, multipleParametersAllowed, unquoteParameters) && (missingParametersErrorMessage != null))
  715. {
  716. commandLineSwitches.SetSwitchError(missingParametersErrorMessage, unquotedCommandLineArg);
  717. }
  718. }
  719. }
  720. else
  721. {
  722. commandLineSwitches.SetSwitchError(missingParametersErrorMessage, unquotedCommandLineArg);
  723. }
  724. }
  725. private static void GatherParameterlessCommandLineSwitch(CommandLineSwitches commandLineSwitches, CommandLineSwitches.ParameterlessSwitch parameterlessSwitch, string switchParameters, string duplicateSwitchErrorMessage, string unquotedCommandLineArg)
  726. {
  727. if (switchParameters.Length == 0)
  728. {
  729. if (!commandLineSwitches.IsParameterlessSwitchSet(parameterlessSwitch) || (duplicateSwitchErrorMessage == null))
  730. {
  731. commandLineSwitches.SetParameterlessSwitch(parameterlessSwitch, unquotedCommandLineArg);
  732. }
  733. else
  734. {
  735. commandLineSwitches.SetSwitchError(duplicateSwitchErrorMessage, unquotedCommandLineArg);
  736. }
  737. }
  738. else
  739. {
  740. commandLineSwitches.SetUnexpectedParametersError(unquotedCommandLineArg);
  741. }
  742. }
  743. private static void GatherResponseFileSwitch(string unquotedCommandLineArg, CommandLineSwitches commandLineSwitches)
  744. {
  745. try
  746. {
  747. string path = unquotedCommandLineArg.Substring(1);
  748. if (path.Length == 0)
  749. {
  750. commandLineSwitches.SetSwitchError("MissingResponseFileError", unquotedCommandLineArg);
  751. }
  752. else if (!File.Exists(path))
  753. {
  754. commandLineSwitches.SetParameterError("ResponseFileNotFoundError", unquotedCommandLineArg);
  755. }
  756. else
  757. {
  758. path = Path.GetFullPath(path);
  759. bool flag = false;
  760. foreach (string str2 in includedResponseFiles)
  761. {
  762. if (string.Compare(path, str2, StringComparison.OrdinalIgnoreCase) == 0)
  763. {
  764. commandLineSwitches.SetParameterError("RepeatedResponseFileError", unquotedCommandLineArg);
  765. flag = true;
  766. break;
  767. }
  768. }
  769. if (!flag)
  770. {
  771. ArrayList list;
  772. includedResponseFiles.Add(path);
  773. using (StreamReader reader = new StreamReader(path, Encoding.Default))
  774. {
  775. list = new ArrayList();
  776. while (reader.Peek() != -1)
  777. {
  778. string name = reader.ReadLine().TrimStart(new char[0]);
  779. if (!name.StartsWith("#", StringComparison.Ordinal))
  780. {
  781. list.AddRange(QuotingUtilities.SplitUnquoted(Environment.ExpandEnvironmentVariables(name), new char[0]));
  782. }
  783. }
  784. }
  785. GatherCommandLineSwitches(list, commandLineSwitches);
  786. }
  787. }
  788. }
  789. catch (NotSupportedException exception)
  790. {
  791. commandLineSwitches.SetParameterError("ReadResponseFileError", unquotedCommandLineArg, exception);
  792. }
  793. catch (SecurityException exception2)
  794. {
  795. commandLineSwitches.SetParameterError("ReadResponseFileError", unquotedCommandLineArg, exception2);
  796. }
  797. catch (UnauthorizedAccessException exception3)
  798. {
  799. commandLineSwitches.SetParameterError("ReadResponseFileError", unquotedCommandLineArg, exception3);
  800. }
  801. catch (IOException exception4)
  802. {
  803. commandLineSwitches.SetParameterError("ReadResponseFileError", unquotedCommandLineArg, exception4);
  804. }
  805. }
  806. private static string GetFriendlyCounterType(PerformanceCounterType type, string name)
  807. {
  808. if (name.IndexOf("bytes", StringComparison.OrdinalIgnoreCase) != -1)
  809. {
  810. return "bytes";
  811. }
  812. if (name.IndexOf("threads", StringComparison.OrdinalIgnoreCase) != -1)
  813. {
  814. return "threads";
  815. }
  816. switch (type)
  817. {
  818. case PerformanceCounterType.NumberOfItems64:
  819. case PerformanceCounterType.CounterDelta32:
  820. case PerformanceCounterType.CounterDelta64:
  821. case PerformanceCounterType.NumberOfItemsHEX32:
  822. case PerformanceCounterType.NumberOfItemsHEX64:
  823. case PerformanceCounterType.NumberOfItems32:
  824. case PerformanceCounterType.SampleCounter:
  825. case PerformanceCounterType.CountPerTimeInterval32:
  826. case PerformanceCounterType.CountPerTimeInterval64:
  827. case PerformanceCounterType.CounterTimer:
  828. case PerformanceCounterType.RateOfCountsPerSecond32:
  829. case PerformanceCounterType.RateOfCountsPerSecond64:
  830. case PerformanceCounterType.CounterMultiTimer:
  831. case PerformanceCounterType.CounterTimerInverse:
  832. case PerformanceCounterType.CounterMultiTimerInverse:
  833. case PerformanceCounterType.AverageCount64:
  834. return "#";
  835. case PerformanceCounterType.RawFraction:
  836. case PerformanceCounterType.CounterMultiTimer100Ns:
  837. case PerformanceCounterType.SampleFraction:
  838. case PerformanceCounterType.CounterMultiTimer100NsInverse:
  839. return "%";
  840. case PerformanceCounterType.Timer100NsInverse:
  841. case PerformanceCounterType.Timer100Ns:
  842. return "100ns";
  843. case PerformanceCounterType.AverageTimer32:
  844. case PerformanceCounterType.ElapsedTime:
  845. return "s";
  846. }
  847. return "?";
  848. }
  849. private static void HandleConfigurationException(Exception ex)
  850. {
  851. StringBuilder builder = new StringBuilder();
  852. Exception innerException = ex;
  853. do
  854. {
  855. string str = innerException.Message.TrimEnd(new char[0]);
  856. builder.Append(str);
  857. if (str[str.Length - 1] != '.')
  858. {
  859. builder.Append(".");
  860. }
  861. builder.Append(" ");
  862. innerException = innerException.InnerException;
  863. }
  864. while (innerException != null);
  865. Console.WriteLine(Microsoft.Build.Shared.ResourceUtilities.FormatResourceString("InvalidConfigurationFile", new object[] { builder.ToString() }));
  866. initialized = false;
  867. }
  868. internal static void Initialize()
  869. {
  870. }
  871. [MTAThread]
  872. public static int Main()
  873. {
  874. if (Environment.GetEnvironmentVariable("MSBUILDDUMPPROCESSCOUNTERS") == "1")
  875. {
  876. DumpCounters(true);
  877. }
  878. int num = (initialized && (Execute(Environment.CommandLine) == ExitType.Success)) ? 0 : 1;
  879. if (Environment.GetEnvironmentVariable("MSBUILDDUMPPROCESSCOUNTERS") == "1")
  880. {
  881. DumpCounters(false);
  882. }
  883. return num;
  884. }
  885. [MethodImpl(MethodImplOptions.NoInlining)]
  886. 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)
  887. {
  888. Console.WriteLine(Microsoft.Build.Shared.AssemblyResources.GetString("Using35Engine"));
  889. BuildPropertyGroup propertyBag = new BuildPropertyGroup();
  890. foreach (KeyValuePair<string, string> pair in globalProperties)
  891. {
  892. propertyBag.SetProperty(pair.Key, pair.Value);
  893. }
  894. if (!BuildProjectWithOldOM(projectFile, targets, toolsVersion, propertyBag, loggers, verbosity, null, needToValidateProject, schemaFile, cpuCount))
  895. {
  896. exitType = ExitType.BuildError;
  897. }
  898. return exitType;
  899. }
  900. private static Microsoft.Build.Logging.LoggerDescription ParseLoggingParameter(string parameter, string unquotedParameter, LoggerVerbosity verbosity)
  901. {
  902. string str;
  903. string loggerSwitchParameters = null;
  904. int num;
  905. string str5;
  906. ArrayList list = QuotingUtilities.SplitUnquoted(parameter, 2, true, false, out num, new char[] { ';' });
  907. Microsoft.Build.Shared.ErrorUtilities.VerifyThrow((list.Count >= 1) && (list.Count <= 2), "SplitUnquoted() must return at least one string, and no more than two.");
  908. CommandLineSwitchException.VerifyThrow(((string) list[0]).Length > 0, "InvalidLoggerError", unquotedParameter);
  909. if (list.Count == 2)
  910. {
  911. loggerSwitchParameters = QuotingUtilities.Unquote((string) list[1]);
  912. }
  913. ArrayList list2 = QuotingUtilities.SplitUnquoted((string) list[0], 2, true, false, out num, new char[] { ',' });
  914. Microsoft.Build.Shared.ErrorUtilities.VerifyThrow((list2.Count >= 1) && (list2.Count <= 2), "SplitUnquoted() must return at least one string, and no more than two.");
  915. if (list2.Count == 2)
  916. {
  917. str = QuotingUtilities.Unquote((string) list2[0]);
  918. str5 = QuotingUtilities.Unquote((string) list2[1]);
  919. }
  920. else
  921. {
  922. str = string.Empty;
  923. str5 = QuotingUtilities.Unquote((string) list2[0]);
  924. }
  925. CommandLineSwitchException.VerifyThrow(str5.Length > 0, "InvalidLoggerError", unquotedParameter);
  926. string loggerAssemblyName = null;
  927. string loggerAssemblyFile = null;
  928. if (string.Compare(str5, "Microsoft.Build.Engine", StringComparison.OrdinalIgnoreCase) == 0)
  929. {
  930. str5 = "Microsoft.Build.Engine,Version=4.0.0.0,Culture=neutral,PublicKeyToken=b03f5f7f11d50a3a";
  931. }
  932. if (File.Exists(str5))
  933. {
  934. loggerAssemblyFile = str5;
  935. }
  936. else
  937. {
  938. loggerAssemblyName = str5;
  939. }
  940. return new Microsoft.Build.Logging.LoggerDescription(str, loggerAssemblyName, loggerAssemblyFile, loggerSwitchParameters, verbosity);
  941. }
  942. private static bool ProcessCommandLineSwitches(CommandLineSwitches commandLineSwitches, ref string projectFile, ref string[] targets, ref string toolsVersion, ref Dictionary<string, string> globalProperties, ref ILogger[] loggers, ref LoggerVerbosity verbosity, ref List<DistributedLoggerRecord> distributedLoggerRecords, ref bool needToValidateProject, ref string schemaFile, ref int cpuCount, ref bool enableNodeReuse, ref TextWriter preprocessWriter, ref bool debugger, ref bool detailedSummary)
  943. {
  944. bool flag = false;
  945. if (!commandLineSwitches[CommandLineSwitches.Para

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