Welcome to mirror list, hosted at ThFree Co, Russian Federation.

RemoteBuildEngineManager.cs « MonoDevelop.Projects.MSBuild « MonoDevelop.Core « core « src « main - github.com/mono/monodevelop.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: e9e092f143aa133cd81ede7355839e642dc8220c (plain)
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
//
// RemoteBuildEngineManager.cs
//
// Author:
//       Lluis Sanchez Gual <lluis@novell.com>
//
// Copyright (c) 2017 Microsoft
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;
using MonoDevelop.Core;
using MonoDevelop.Core.Assemblies;
using MonoDevelop.Core.Execution;

namespace MonoDevelop.Projects.MSBuild
{
	/// <summary>
	/// Manages build engines running in external processes.
	/// </summary>
	static class RemoteBuildEngineManager
	{
		// A RemoteBuildEngine is a process that can build project using MSBuild.
		// A build engine is bound to a solution and it can usually build any
		// project of the solution.

		// Projects are built by using a RemoteProjectBuilder. A RemoteBuildEngine
		// will have a RemoteProjectBuilder intance for each project that
		// has been loaded into the remote engine.

		// Remote engines and builders are created on demand, when
		// GetRemoteProjectBuilder() is called. The manager first checks if
		// there is an engine currently running for the provided solution,
		// and starts a new one if there isn't. Then it checks if there is
		// a project builder for the provided project, and creates a new
		// one if there isn't.

		// It may happen that a builder exists when requested, but it may
		// be busy (executing a build). The requester can decide what to do in
		// that case: either force the creation of a new builder engine so that
		// the request can be immediately fullfilled, or just pick the busy
		// builder, in which case the task won't be executed until the current
		// one is finished.

		// RemoteProjectBuilder instances must be explicitly disposed after
		// use. When all project builders of a build engine are disposed,
		// the engine will be scheduled for disposal, and it will be disposed
		// if not used again after EngineDisposalDelay milliseconds
		// (see constant below). Build engines can also be explicitly
		// disposed by calling UnloadSolution(). That method is always called
		// when a solution is disposed. Also, at least one builder is always
		// kept alive for each solution.

		static bool searchPathConfigNeedsUpdate;
		static AsyncCriticalSection buildersLock = new AsyncCriticalSection ();
		static BuilderCache builders = new BuilderCache ();
		static bool shutDown;

		internal static int EngineDisposalDelay = 60000;

		class SessionInfo
		{
			public ProgressMonitor Monitor;
			public MSBuildLogger Logger;
			public MSBuildVerbosity Verbosity;
			public ProjectConfigurationInfo [] Configurations;
		}

		static RemoteBuildEngineManager ()
		{
			CleanCachedMSBuildExes ();
			MSBuildProjectService.GlobalPropertyProvidersChanged += HandleGlobalPropertyProviderChanged;
			MSBuildProjectService.ImportSearchPathsChanged += (s, e) => {
				// Reload all builders since search paths have changed
				searchPathConfigNeedsUpdate = true;
				RecycleAllBuilders ().Ignore ();
			};
			Runtime.ShuttingDown += Shutdown;
		}

		static async void Shutdown (object s, EventArgs a)
		{
			using (await buildersLock.EnterAsync ().ConfigureAwait (false)) {
				shutDown = true;
				foreach (var engine in builders.GetAllBuilders ().ToList ()) {
					// Signal all project builder of the engine to stop
					engine.Shutdown ();
					engine.CancelScheduledDisposal ();
					builders.Remove (engine);
					engine.DisposeGracefully ();
				}
			}
		}

		static void CheckShutDown ()
		{
			if (shutDown)
				throw new InvalidOperationException ("Runtime is shut down");
		}

		internal static int ActiveEnginesCount => builders.GetAllBuilders ().Where (b => !b.IsShuttingDown).Count ();

		internal static int EnginesCount => builders.GetAllBuilders ().Count ();

		// Used by unit tests
		internal static async Task<int> CountActiveBuildersForProject (string projectFile)
		{
			using (await buildersLock.EnterAsync ().ConfigureAwait (false)) {
				return builders.GetAllBuilders ().Count (b => b.IsProjectLoaded (projectFile));
			}
		}

		/// <summary>
		/// Gets or creates a remote build engine
		/// </summary>
		/// <returns>The build engine.</returns>
		/// <param name="projectFile">The project to build.</param>
		/// <param name="solutionFile">Solution to which the project belongs.</param>
		/// <param name="runtime">.NET Runtime to be used to run the builder</param>
		/// <param name="minToolsVersion">Minimum tools version that it has to support.</param>
		/// <param name="setBusy">If true, the engine will be set as busy once allocated.</param>
		/// <param name="allowBusy">If true, busy engines can be returned.</param>
		/// <remarks>
		/// After using it, the builder must be disposed.
		/// </remarks>
		public async static Task<IRemoteProjectBuilder> GetRemoteProjectBuilder (string projectFile, string solutionFile, TargetRuntime runtime, string minToolsVersion, object buildSessionId, bool setBusy = false, bool allowBusy = true)
		{
			CheckShutDown ();

			RemoteBuildEngine engine;
			using (await buildersLock.EnterAsync ().ConfigureAwait (false)) {
				// Get a builder with the provided requirements
				engine = await GetBuildEngine (runtime, minToolsVersion, solutionFile, "", buildSessionId, setBusy, allowBusy);

				// Add a reference to make sure the engine is alive while the builder is being used.
				// This reference will be freed when ReleaseReference() is invoked on the builder.
				engine.ReferenceCount++;
				try {
					return new RemoteProjectBuilderProxy (await engine.GetRemoteProjectBuilder (projectFile, true), setBusy);
				} catch {
					// Something went wrong, release the above engine reference, since it won't be possible to free it through the builder
					ReleaseProjectBuilderNoLock (engine).Ignore ();
					throw;
				}
			}
		}

		/// <summary>
		/// Gets or creates a remote build engine
		/// </summary>
		async static Task<RemoteBuildEngine> GetBuildEngine (TargetRuntime runtime, string minToolsVersion, string solutionFile, string group, object buildSessionId, bool setBusy = false, bool allowBusy = true)
		{
			var binDir = MSBuildProjectService.GetMSBuildBinPath (runtime);

			Version tv = Version.Parse (MSBuildProjectService.ToolsVersion);
			if (Version.TryParse (minToolsVersion, out Version mtv) && tv < mtv) {
				throw new InvalidOperationException (string.Format (
					"Project requires MSBuild ToolsVersion '{0}' which is not supported by runtime '{1}'",
					minToolsVersion, runtime.Id)
				);
			}

			// One builder per solution
			string builderKey = runtime.Id + " # " + solutionFile + " # " + group;

			RemoteBuildEngine builder = null;

			// Find builders which are not being shut down

			var candiateBuilders = builders.GetBuilders (builderKey).Where (b => !b.IsShuttingDown && (!b.IsBusy || allowBusy));

			if (buildSessionId != null) {

				// Look for a builder that already started the session.
				// If there isn't one, pick builders which don't have any session assigned, so a new one
				// can be started.

				var sessionBuilders = candiateBuilders.Where (b => b.BuildSessionId == buildSessionId);
				if (!sessionBuilders.Any ())
					sessionBuilders = candiateBuilders.Where (b => b.BuildSessionId == null);
				candiateBuilders = sessionBuilders;
			} else
				// Pick builders which are not bound to any session
				candiateBuilders = candiateBuilders.Where (b => b.BuildSessionId == null);

			// Prefer non-busy builders

			builder = candiateBuilders.FirstOrDefault (b => !b.IsBusy) ?? candiateBuilders.FirstOrDefault ();

			if (builder != null) {
				if (setBusy)
					builder.SetBusy ();
				if (builder.BuildSessionId == null && buildSessionId != null) {
					// If a new session is being assigned, signal the session start
					builder.BuildSessionId = buildSessionId;
					var si = (SessionInfo)buildSessionId;
					await builder.BeginBuildOperation (si.Monitor, si.Logger, si.Verbosity, si.Configurations).ConfigureAwait (false);
				}
				builder.CancelScheduledDisposal ();
				return builder;
			}

			// No builder available with the required constraints. Start a new builder

			return await Task.Run (async () => {

				// Always start the remote process explicitly, even if it's using the current runtime and fx
				// else it won't pick up the assembly redirects from the builder exe

				var exe = GetExeLocation (runtime);
				RemoteProcessConnection connection = null;

				try {
					var envVariables = new Dictionary<string, string> {
						{ "MONO_GC_PARAMS", "nursery-size=64m" },
					};

					connection = new RemoteProcessConnection (exe, null, envVariables, runtime.GetExecutionHandler ());
					await connection.Connect ().ConfigureAwait (false);

					var props = GetCoreGlobalProperties (solutionFile, binDir, MSBuildProjectService.ToolsVersion);
					foreach (var gpp in MSBuildProjectService.GlobalPropertyProviders) {
						foreach (var e in gpp.GetGlobalProperties ())
							props [e.Key] = e.Value;
					}

					await connection.SendMessage (new InitializeRequest {
						IdeProcessId = Process.GetCurrentProcess ().Id,
						BinDir = binDir,
						CultureName = GettextCatalog.UICulture.Name,
						GlobalProperties = props
					}).ConfigureAwait (false);

					builder = new RemoteBuildEngine (connection, solutionFile);

				} catch {
					if (connection != null) {
						try {
							connection.Dispose ();
						} catch {
						}
					}
					throw;
				}

				builders.Add (builderKey, builder);
				builder.ReferenceCount = 0;
				builder.BuildSessionId = buildSessionId;

				builder.Disconnected += OnBuilderDisconnected;
				if (setBusy)
					builder.SetBusy ();
				if (buildSessionId != null) {
					var si = (SessionInfo)buildSessionId;
					await builder.BeginBuildOperation (si.Monitor, si.Logger, si.Verbosity, si.Configurations);
				}
				return builder;
			});
		}

		// PERF: Avoid making this an instance method, as it will cause delegates to be retained.
		static async Task OnBuilderDisconnected (object sender, EventArgs args)
		{
			var disconnectedBuilder = (RemoteBuildEngine)sender;
			using (await buildersLock.EnterAsync ().ConfigureAwait (false))
				builders.Remove (disconnectedBuilder);
		}

		/// <summary>
		/// Unloads a project from all engines
		/// </summary>
		public static async Task UnloadProject (string projectFile)
		{
			List<RemoteBuildEngine> projectBuilders;
			using (await buildersLock.EnterAsync ().ConfigureAwait (false)) {
				if (shutDown) return;
				projectBuilders = builders.GetAllBuilders ().Where (b => b.IsProjectLoaded (projectFile)).ToList ();
			}
			foreach (var b in projectBuilders)
				(await b.GetRemoteProjectBuilder (projectFile, false)).Shutdown ();
		}

		/// <summary>
		/// Unloads all engines bound to a solution
		/// </summary>
		public static async Task UnloadSolution (string solutionFile)
		{
			using (await buildersLock.EnterAsync ().ConfigureAwait (false)) {
				if (shutDown) return;
				foreach (var engine in builders.GetAllBuilders ().Where (b => b.SolutionFile == solutionFile).ToList ())
					ShutdownBuilderNoLock (engine);
			}
		}

		/// <summary>
		/// Reloads a project in all engines that have it loaded
		/// </summary>
		public static async Task RefreshProject (string projectFile)
		{
			List<RemoteBuildEngine> projectBuilders;
			using (await buildersLock.EnterAsync ().ConfigureAwait (false)) {
				if (shutDown) return;
				projectBuilders = builders.GetAllBuilders ().Where (b => b.IsProjectLoaded (projectFile)).ToList ();
			}
			foreach (var b in projectBuilders)
				await (await b.GetRemoteProjectBuilder (projectFile, false)).Refresh ();
		}

		/// <summary>
		/// Refreshes the content of a project in all engines that have it loaded
		/// </summary>
		public static async Task RefreshProjectWithContent (string projectFile, string projectContent)
		{
			List<RemoteBuildEngine> projectBuilders;
			using (await buildersLock.EnterAsync ().ConfigureAwait (false)) {
				if (shutDown) return;
				projectBuilders = builders.GetAllBuilders ().Where (b => b.IsProjectLoaded (projectFile)).ToList ();
			}
			foreach (var b in projectBuilders)
				await (await b.GetRemoteProjectBuilder (projectFile, false)).RefreshWithContent (projectContent);
		}

		/// <summary>
		/// Forces the reload of all project builders
		/// </summary>
		/// <remarks>
		/// This method can be used to discard all currently active project builders, and force the creation
		/// of new ones. This method is useful when there is a change in the MSBuild options or environment
		/// that has an effect on all builders. If a builder is running a task, it will be discarded when
		/// the task ends.
		/// </remarks>
		public static async Task RecycleAllBuilders ()
		{
			using (await buildersLock.EnterAsync ().ConfigureAwait (false)) {
				if (shutDown) return;
				foreach (var b in builders.GetAllBuilders ().ToList ())
					ShutdownBuilderNoLock (b);
			}
		}

		/// <summary>
		/// Starts a build session that can span multiple builders and projects
		/// </summary>
		/// <returns>The build session handle.</returns>
		/// <param name="monitor">Progress monitor.</param>
		/// <param name="verbosity">MSBuild verbosity.</param>
		internal static object StartBuildSession (ProgressMonitor monitor, MSBuildLogger logger, MSBuildVerbosity verbosity, ProjectConfigurationInfo[] configurations)
		{
			CheckShutDown ();
			return new SessionInfo {
					Monitor = monitor,
					Verbosity = verbosity,
					Logger = logger,
					Configurations = configurations
				};
		}

		/// <summary>
		/// Ends the build session in all builders that are building projects that belong
		/// to the provided session handle.
		/// </summary>
		/// <param name="session">Session handle.</param>
		internal static async Task EndBuildSession (object session)
		{
			using (await buildersLock.EnterAsync ().ConfigureAwait (false)) {
				if (shutDown) return;
				foreach (var b in builders.GetAllBuilders ())
					if (b.BuildSessionId == session) {
						b.BuildSessionId = null;

						var si = (SessionInfo)session;
						await b.EndBuildOperation (si.Monitor);
					}
			}
		}

		static async void HandleGlobalPropertyProviderChanged (object sender, EventArgs e)
		{
			// Update the global properties in all builders

			using (await buildersLock.EnterAsync ().ConfigureAwait (false)) {
				if (shutDown) return;
				var gpp = (IMSBuildGlobalPropertyProvider)sender;
				foreach (var builder in builders.GetAllBuilders ())
					await builder.SetGlobalProperties (new Dictionary<string, string> (gpp.GetGlobalProperties ()));
			}
		}

		static Dictionary<string, string> GetCoreGlobalProperties (string slnFile, string binDir, string toolsVersion)
		{
			var dictionary = new Dictionary<string, string> ();

			// This causes build targets to behave how they should inside an IDE, instead of in a command-line process
			dictionary.Add ("BuildingInsideVisualStudio", "true");

			// We don't have host compilers in MD, and this is set to true by some of the MS targets
			// which causes it to always run the CoreCompile task if BuildingInsideVisualStudio is also
			// true, because the VS in-process compiler would take care of the deps tracking
			dictionary.Add ("UseHostCompilerIfAvailable", "false");

			if (string.IsNullOrEmpty (slnFile))
				return dictionary;

			dictionary.Add ("SolutionPath", Path.GetFullPath (slnFile));
			dictionary.Add ("SolutionName", Path.GetFileNameWithoutExtension (slnFile));
			dictionary.Add ("SolutionFilename", Path.GetFileName (slnFile));
			dictionary.Add ("SolutionDir", Path.GetDirectoryName (slnFile) + Path.DirectorySeparatorChar);

			// When running the dev15 MSBuild from commandline or inside MSBuild, it sets "VSToolsPath" correctly. when running from MD, it falls back to a bad default. override it.
			if (Platform.IsWindows) {
				dictionary.Add ("VSToolsPath", Path.GetFullPath (Path.Combine (binDir, "..", "..", "Microsoft", "VisualStudio", "v" + toolsVersion)));
			}

			return dictionary;
		}

		/// <summary>
		/// Gets the project builder exe to be used to for a specific runtime and tools version
		/// </summary>
		static string GetExeLocation (TargetRuntime runtime)
		{
			// Return a local copy of the builder executable.
			// That local copy is configured to add additional msbuild search paths defined by add-ins.
			return GetLocalMSBuildExeLocation (runtime);
		}

		/// <summary>
		/// Locate the project builder exe in the MD directory
		/// </summary>
		static string GetExeLocationInBundle (string toolsVersion)
		{
			var mdBinDir = new FilePath (typeof (MSBuildProjectService).Assembly.Location).ParentDirectory;
			var exe = mdBinDir.Combine ("MonoDevelop.MSBuildBuilder.exe");
			if (File.Exists (exe))
				return exe;

			throw new InvalidOperationException ($"Did not find MSBuild builder '{exe}'");
		}

		static string GetLocalMSBuildExeLocation (TargetRuntime runtime)
		{
			// Gets a path to the local copy of the project builder for the provided runtime.
			// If no local copy exists, create one.

			// Builders are copied to a folder inside the cache folder. This folder is cleaned
			// every time XS is started, removing unused builders. The process id is used
			// as folder name, so it is easy to check if the folder is currently in use or not.

			var dirId = Process.GetCurrentProcess ().Id.ToString () + "_" + runtime.InternalId;
			var exesDir = UserProfile.Current.CacheDir.Combine ("MSBuild").Combine (dirId);
			var originalExe = GetExeLocationInBundle (MSBuildProjectService.ToolsVersion);
			var originalExeConfig = originalExe + ".config";
			var destinationExe = exesDir.Combine (Path.GetFileName (originalExe));
			var destinationExeConfig = destinationExe + ".config";

			var localResolversDir = Path.Combine (exesDir, "SdkResolvers");
			var mdResolverDir = Path.Combine (localResolversDir, "MonoDevelop.MSBuildResolver");
			var mdResolverConfig = Path.Combine (mdResolverDir, "sdks.config");

			string binDir = MSBuildProjectService.GetMSBuildBinPath (runtime);

			if (Platform.IsWindows) {
				// on Windows copy the official MSBuild.exe.config from the VS 2017 install
				// and use this as the starting point
				originalExeConfig = Path.Combine (binDir, "MSBuild.exe.config");
			}

			if (!Directory.Exists (exesDir)) {
				// Copy the builder to the local dir, including the debug file and config file.
				Directory.CreateDirectory (exesDir);
				File.Copy (originalExe, destinationExe);
				var exeMdb = originalExe + ".mdb";
				if (File.Exists (exeMdb))
					File.Copy (exeMdb, exesDir.Combine (Path.GetFileName (exeMdb)));
				var exePdb = Path.ChangeExtension (originalExe, ".pdb");
				if (File.Exists (exePdb))
					File.Copy (exePdb, exesDir.Combine (Path.GetFileName (exePdb)));

				// Copy the whole MSBuild bin folder and subfolders. We need all support assemblies
				// and files.
				FileService.CopyDirectory (binDir, exesDir);

				CopyMonoDevelopResolver (mdResolverDir);

				if (Platform.IsWindows) {
					PatchNuGetSdkResolver (binDir, localResolversDir);
				}

				searchPathConfigNeedsUpdate = true;
			}

			if (searchPathConfigNeedsUpdate) {
				// There is already a local copy of the builder, but the config file needs to be updated.
				searchPathConfigNeedsUpdate = false;
				UpdateMSBuildExeConfigFile (runtime, originalExeConfig, destinationExeConfig, mdResolverConfig, binDir);
			}
			return destinationExe;
		}

		static void CopyMonoDevelopResolver (string mdResolverDir)
		{
			// Copy the MonoDevelop resolver, used for sdks registered by add-ins.
			// This resolver will load registered sdks from the file sdks.config
			if (!Directory.Exists (mdResolverDir))
				Directory.CreateDirectory (mdResolverDir);

			var builderDir = new FilePath (typeof (MSBuildProjectService).Assembly.Location).ParentDirectory.Combine ("MSBuild");
			File.Copy (Path.Combine (builderDir, "MonoDevelop.MSBuildResolver.dll"), Path.Combine (mdResolverDir, "MonoDevelop.MSBuildResolver.dll"));
		}

		/// <summary>
		/// Make sure our copy of the manifest XML points at the valid NuGet resolver location within Visual Studio path.
		/// When we copy the manifest XML the relative path becomes invalid.
		/// </summary>
		/// <param name="msbuildBinDir">A path similar to C:\Program Files (x86)\Microsoft Visual Studio\Preview\Enterprise\MSBuild\15.0\Bin</param>
		/// <param name="localSdkResolversDir">A path similar to C:\Users\user\AppData\Local\MonoDevelop\7.0\Cache\MSBuild\6976_1\SdkResolvers</param>
		static void PatchNuGetSdkResolver (string msbuildBinDir, string localSdkResolversDir)
		{
			var resolverXml = Path.Combine (localSdkResolversDir, "Microsoft.Build.NuGetSdkResolver", "Microsoft.Build.NuGetSdkResolver.xml");
			if (File.Exists (resolverXml)) {
				var vsRoot = new FilePath (msbuildBinDir).ParentDirectory.ParentDirectory.ParentDirectory;
				var resolverDll = vsRoot.Combine ("Common7", "IDE", "CommonExtensions", "Microsoft", "NuGet", "Microsoft.Build.NuGetSdkResolver.dll");
				var newText = $@"<SdkResolver>
  <Path>{resolverDll}</Path>
</SdkResolver>";
				File.WriteAllText (resolverXml, newText);
			}
		}

		static void UpdateMSBuildExeConfigFile (TargetRuntime runtime, string sourceConfigFile, string destinationConfigFile, string mdResolverConfig, string binDir)
		{
			// Creates an MSBuild config file with the search paths registered by add-ins.

			var doc = XDocument.Load (sourceConfigFile);
			var configuration = doc.Root;

			if (Platform.IsWindows) {
				// we want the config file to have the UseLegacyPathHandling=false switch
				// https://blogs.msdn.microsoft.com/jeremykuhne/2016/06/21/more-on-new-net-path-handling/
				var runtimeElement = configuration.Element ("runtime");
				ConfigFileUtilities.SetOrAppendSubelementAttributeValue (runtimeElement, "AppContextSwitchOverrides", "value", "Switch.System.IO.UseLegacyPathHandling=false");
			}

			foreach (var toolset in doc.Root.Elements ("msbuildToolsets").FirstOrDefault ()?.Elements ("toolset") ?? Enumerable.Empty<XElement> ()) {

				// This is required for MSBuild to properly load the searchPaths element (@radical knows why)
				SetMSBuildConfigProperty (toolset, "MSBuildBinPath", binDir, append: false, insertBefore: true);

				// this must match MSBuildBinPath w/MSBuild15
				SetMSBuildConfigProperty (toolset, "MSBuildToolsPath", binDir, append: false, insertBefore: true);

				if (Platform.IsWindows) {
					var extensionsPath = Path.GetDirectoryName (Path.GetDirectoryName (binDir));
					var vsInstallRoot = Path.GetDirectoryName (extensionsPath);
					var devEnvDir = Path.Combine (vsInstallRoot, @"Common7\IDE");
					SetMSBuildConfigProperty (toolset, "MSBuildExtensionsPath", extensionsPath);
					SetMSBuildConfigProperty (toolset, "MSBuildExtensionsPath32", extensionsPath);
					SetMSBuildConfigProperty (toolset, "MSBuildToolsPath", binDir);
					SetMSBuildConfigProperty (toolset, "MSBuildToolsPath32", binDir);
					SetMSBuildConfigProperty (toolset, "VsInstallRoot", vsInstallRoot);
					SetMSBuildConfigProperty (toolset, "DevEnvDir", devEnvDir + "\\");
					SetMSBuildConfigProperty (toolset, "NuGetRestoreTargets", Path.Combine(devEnvDir, @"CommonExtensions\Microsoft\NuGet\NuGet.targets"));

					var sdksPath = Path.Combine (extensionsPath, "Sdks");
					SetMSBuildConfigProperty (toolset, "MSBuildSDKsPath", sdksPath);

					var roslynTargetsPath = Path.Combine (binDir, "Roslyn");
					SetMSBuildConfigProperty (toolset, "RoslynTargetsPath", roslynTargetsPath);

					var vcTargetsPath = Path.Combine (devEnvDir, "VC", "VCTargets");
					SetMSBuildConfigProperty (toolset, "VCTargetsPath", vcTargetsPath);
				} else {
					var path = MSBuildProjectService.GetProjectImportSearchPaths (runtime, false).FirstOrDefault (p => p.Property == "MSBuildSDKsPath");
					if (path != null)
						SetMSBuildConfigProperty (toolset, path.Property, path.Path);
				}

				var projectImportSearchPaths = toolset.Element ("projectImportSearchPaths");
				if (projectImportSearchPaths != null) {
					var os = Platform.IsMac ? "osx" : Platform.IsWindows ? "windows" : "unix";
					XElement searchPaths = projectImportSearchPaths.Elements ("searchPaths").FirstOrDefault (sp => sp.Attribute ("os")?.Value == os);
					if (searchPaths == null) {
						searchPaths = new XElement ("searchPaths");
						searchPaths.SetAttributeValue ("os", os);
						projectImportSearchPaths.Add (searchPaths);
					}
					foreach (var path in MSBuildProjectService.GetProjectImportSearchPaths (runtime, false))
						SetMSBuildConfigProperty (searchPaths, path.Property, path.Path, append: true, insertBefore: false);
				}
			}

			doc.Save (destinationConfigFile);

			// Update the sdk list for the MD resolver
			SdkInfo.SaveConfig (mdResolverConfig, MSBuildProjectService.FindRegisteredSdks ());
		}

		static void SetMSBuildConfigProperty (XElement elem, string name, string value, bool append = false, bool insertBefore = false)
		{
			var prop = elem.Elements ("property").FirstOrDefault (p => p.Attribute ("name")?.Value == name);
			if (prop != null) {
				var val = prop.Attribute ("value")?.Value;
				if (append)
					prop.SetAttributeValue ("value", val + ";" + value);
				else
					prop.SetAttributeValue ("value", value);
			} else {
				prop = new XElement ("property");
				prop.SetAttributeValue ("name", name);
				prop.SetAttributeValue ("value", value);
				if (insertBefore)
					elem.AddFirst (prop);
				else
					elem.Add (prop);
			}
		}

		static void CleanCachedMSBuildExes ()
		{
			// Removes local copies of project builders that are not currently being used.

			var exesDir = UserProfile.Current.CacheDir.Combine ("MSBuild");
			if (!Directory.Exists (exesDir))
				return;

			foreach (var dir in Directory.GetDirectories (exesDir)) {
				// The file name has to parts: <process-id>_<runtime-id>
				var spid = Path.GetFileName (dir);
				int i = spid.IndexOf ('_');
				if (i == -1)
					continue;
				spid = spid.Substring (0, i);
				int pid;
				if (int.TryParse (Path.GetFileName (spid), out pid)) {
					try {
						if (Platform.IsWindows) {
							// Avoid a common first-chance ArgumentException on Windows.
							// It's better to take a small perf hit on Windows then to 
							// hit this exception every time during debugging.
							if (Process.GetProcesses().Any(p => p.Id == pid)) {
								continue;
							}
						}
						// If there is a process running with this id it means the builder is still being used
						else if (Process.GetProcessById (pid) != null)
							continue;
					} catch {
						// Ignore
					}
					// No process for this id, it should be safe to delete the folder
					try {
						Directory.Delete (dir, true);
					} catch (Exception ex) {
						LoggingService.LogError ("Could not delete MSBuild cache folder", ex);
					}
				}
			}
		}

		internal static async Task ReleaseProjectBuilder (RemoteBuildEngine engine)
		{
			using (await buildersLock.EnterAsync ().ConfigureAwait (false)) {
				await ReleaseProjectBuilderNoLock (engine);
			}
		}

		static void ShutdownBuilderNoLock (RemoteBuildEngine engine)
		{
			// Signal all project builder of the engine to stop
			engine.Shutdown ();

			// If there are no references it means the engine is not being used, so it can be disposed now.
			// Otherwise it will be disposed when all references are released
			if (engine.ReferenceCount == 0) {
				engine.CancelScheduledDisposal ();
				builders.Remove (engine);
				engine.DisposeGracefully ();
			}
		}

		static Task ReleaseProjectBuilderNoLock (RemoteBuildEngine engine)
		{
			if (shutDown)
				return Task.CompletedTask;
			if (--engine.ReferenceCount != 0)
				return Task.CompletedTask;
			if (engine.IsShuttingDown) {
				// If the engine is being shut down, dispose it now.
				builders.Remove (engine);
				engine.DisposeGracefully ();
			} else {
				// Wait a bit before disposing the engine. We may need to use it again.
				engine.ScheduleForDisposal (EngineDisposalDelay).ContinueWith (async t => {
					using (await buildersLock.EnterAsync ().ConfigureAwait (false)) {
						// If this is the last standing build engine for the solution, don't dispose it.
						// In this way there will always be at least one build engine for each solution,
						// until explicitly unloaded.
						if (!builders.GetAllBuilders ().Where (b => !b.IsShuttingDown && b != engine && b.SolutionFile == engine.SolutionFile).Any ())
							return;
						// If after the wait there are still 0 references, dispose the builder
						if (engine.ReferenceCount == 0) {
							builders.Remove (engine);
							engine.DisposeGracefully ();
						}
					}
				}, TaskContinuationOptions.NotOnCanceled);
			}
			return Task.CompletedTask;
		}
	}
}