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

TargetRuntime.cs « MonoDevelop.Core.Assemblies « MonoDevelop.Core « core « src « main - github.com/mono/monodevelop.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: b29e6b028b8f352788e3e6f11fd0ef58a8a65a8c (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
// 
// TargetRuntime.cs
//  
// Author:
//   Todd Berman <tberman@sevenl.net>
//   Lluis Sanchez Gual <lluis@novell.com>
//
// Copyright (C) 2004 Todd Berman
// Copyright (C) 2005 Novell, Inc (http://www.novell.com)
// 
// 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.Threading;
using System.IO;
using System.Xml;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Collections.Specialized;
using MonoDevelop.Core.Execution;
using MonoDevelop.Core.AddIns;
using MonoDevelop.Core.Serialization;
using Mono.Addins;
using Mono.PkgConfig;
using MonoDevelop.Core.Instrumentation;

namespace MonoDevelop.Core.Assemblies
{
	public abstract class TargetRuntime
	{
		HashSet<string> corePackages = new HashSet<string> ();
		
		object initLock = new object ();
		object initEventLock = new object ();
		bool initialized;
		bool initializing;
		bool backgroundInitialize;
		bool extensionInitialized;
		
		Dictionary<TargetFrameworkMoniker,TargetFrameworkBackend> frameworkBackends
			= new Dictionary<TargetFrameworkMoniker, TargetFrameworkBackend> ();
		
		RuntimeAssemblyContext assemblyContext;
		ComposedAssemblyContext composedAssemblyContext;
		ITimeTracker timer;
		TargetFramework[] customFrameworks = new TargetFramework[0];
		
		protected bool ShuttingDown { get; private set; }
		
		public TargetRuntime ()
		{
			assemblyContext = new RuntimeAssemblyContext (this);
			composedAssemblyContext = new ComposedAssemblyContext ();
			composedAssemblyContext.Add (Runtime.SystemAssemblyService.UserAssemblyContext);
			composedAssemblyContext.Add (assemblyContext);
			
			Runtime.ShuttingDown += delegate {
				ShuttingDown = true;
			};
		}
		
		public bool IsInitialized {
			get { return initialized; }
		}
		
		protected object InitializationLock {
			get { return initLock; }
		}
		
		internal void StartInitialization ()
		{
			backgroundInitialize = true;
			initializing = true;
			ThreadPool.QueueUserWorkItem (BackgroundInitialize);
		}
		
		/// <summary>
		/// Display name of the runtime. For example "The Mono Runtime 2.6"
		/// </summary>
		public virtual string DisplayName {
			get {
				if (string.IsNullOrEmpty (Version))
					return DisplayRuntimeName;
				else
					return DisplayRuntimeName + " " + Version;
			}
		}
		
		/// <summary>
		/// Unique identifier of this runtime. For example "Mono 2.6".
		/// </summary>
		public string Id {
			get {
				if (string.IsNullOrEmpty (Version))
					return RuntimeId;
				else
					return RuntimeId + " " + Version;
			}
		}

		/// <summary>
		/// Core display name of the runtime. For example "The Mono Runtime"
		/// </summary>
		public virtual string DisplayRuntimeName {
			get { return RuntimeId; }
		}
		
		/// <summary>
		/// Core identifier the runtime. For example, if there are several
		/// versions of Mono installed, each of them will have "Mono" as RuntimeId
		/// </summary>
		public abstract string RuntimeId { get; }
		
		/// <summary>
		/// Version of the runtime.
		/// This string is strictly for displaying to the user or logging. It should never be used for version checks.
		/// </summary>
		public abstract string Version { get; }
		
		/// <summary>
		/// Returns 'true' if this runtime is the one currently running MonoDevelop.
		/// </summary>
		public abstract bool IsRunning { get; }
		
		public virtual IEnumerable<FilePath> GetReferenceFrameworkDirectories ()
		{
			yield break;
		}
		
		public IEnumerable<TargetFramework> CustomFrameworks {
			get { return customFrameworks; }
		}
		
		protected abstract void OnInitialize ();
		
		/// <summary>
		/// Returns an IExecutionHandler which can be used to execute commands in this runtime.
		/// </summary>
		public abstract IExecutionHandler GetExecutionHandler ();
		
		/// <summary>
		/// Returns an IAssemblyContext which can be used to discover assemblies through this runtime.
		/// It includes assemblies from directories manually registered by the user.
		/// </summary>
		public IAssemblyContext AssemblyContext {
			get {
				EnsureInitialized ();
				return composedAssemblyContext;
			}
		}
		
		/// <summary>
		/// Returns an IAssemblyContext which can be used to discover assemblies provided by this runtime
		/// </summary>
		public RuntimeAssemblyContext RuntimeAssemblyContext {
			get {
				EnsureInitialized ();
				return assemblyContext;
			}
		}

		/// <summary>
		/// Given an assembly file name, returns the corresponding debug information file name.
		/// (.mdb for Mono, .pdb for MS.NET)
		/// </summary>
		public abstract string GetAssemblyDebugInfoFile (string assemblyPath);
		
		/// <summary>
		/// Executes an assembly using this runtime
		/// </summary>
		public Process ExecuteAssembly (string file, string arguments)
		{
			return ExecuteAssembly (file, arguments, null);
		}
		
		/// <summary>
		/// Executes an assembly using this runtime and the specified framework.
		/// </summary>
		public Process ExecuteAssembly (string file, string arguments, TargetFramework fx)
		{
			ProcessStartInfo pi = new ProcessStartInfo (file, arguments);
			pi.UseShellExecute = false;
			return ExecuteAssembly (pi, fx);
		}

		/// <summary>
		/// Executes an assembly using this runtime.
		/// </summary>
		/// <param name="pinfo">
		/// Information of the process to execute
		/// </param>
		/// <returns>
		/// The started process.
		/// </returns>
		public Process ExecuteAssembly (ProcessStartInfo pinfo)
		{
			return ExecuteAssembly (pinfo, null);
		}

		/// <summary>
		/// Executes an assembly using this runtime and the specified framework.
		/// </summary>
		/// <param name="pinfo">
		/// Information of the process to execute
		/// </param>
		/// <param name="fx">
		/// Framework on which the assembly has to be executed.
		/// </param>
		/// <returns>
		/// The started process.
		/// </returns>
		public virtual Process ExecuteAssembly (ProcessStartInfo pinfo, TargetFramework fx)
		{
			if (fx == null) {
				TargetFrameworkMoniker fxId = Runtime.SystemAssemblyService.GetTargetFrameworkForAssembly (this, pinfo.FileName);
				fx = Runtime.SystemAssemblyService.GetTargetFramework (fxId);
				if (!IsInstalled (fx)) {
					// Look for a compatible framework which is installed
					foreach (TargetFramework f in Runtime.SystemAssemblyService.GetTargetFrameworks ()) {
						if (IsInstalled (f) && f.CanReferenceAssembliesTargetingFramework (fx)) {
							fx = f;
							break;
						}
					}
				}
				if (!IsInstalled (fx))
					throw new InvalidOperationException (string.Format ("No compatible framework found for assembly '{0}' (required framework: {1})", pinfo.FileName, fxId));
			}
			
			ConvertAssemblyProcessStartInfo (pinfo);
			return Process.Start (pinfo);
		}
		
		protected virtual void ConvertAssemblyProcessStartInfo (ProcessStartInfo pinfo)
		{
		}
		
		protected TargetFrameworkBackend GetBackend (TargetFramework fx)
		{
			EnsureInitialized ();
			lock (frameworkBackends) {
				TargetFrameworkBackend backend;
				if (frameworkBackends.TryGetValue (fx.Id, out backend))
					return backend;
				backend = fx.CreateBackendForRuntime (this);
				if (backend == null) {
					backend = CreateBackend (fx);
					if (backend == null)
						backend = new NotSupportedFrameworkBackend ();
				}
				backend.Initialize (this, fx);
				frameworkBackends[fx.Id] = backend;
				return backend;
			}
		}
		
		protected virtual TargetFrameworkBackend CreateBackend (TargetFramework fx)
		{
			return null;
		}
		
		internal protected virtual IEnumerable<string> GetFrameworkFolders (TargetFramework fx)
		{
			return GetBackend (fx).GetFrameworkFolders ();
		}
		
		/// <summary>
		/// Returns a list of environment variables that should be set when running tools using this runtime
		/// </summary>
		public virtual ExecutionEnvironment GetToolsExecutionEnvironment (TargetFramework fx)
		{
			return new ExecutionEnvironment (GetBackend (fx).GetToolsEnvironmentVariables ());
		}
		
		/// <summary>
		/// Looks for the specified tool in this runtime. The name can be a script or a .exe.
		/// </summary>
		public virtual string GetToolPath (TargetFramework fx, string toolName)
		{
			return GetBackend (fx).GetToolPath (toolName);
		}
		
		/// <summary>
		/// Returns a list of paths which can contain tools for this runtime.
		/// </summary>
		public virtual IEnumerable<string> GetToolsPaths (TargetFramework fx)
		{
			return GetBackend (fx).GetToolsPaths ();
		}

		/// <summary>
		/// Returns the MSBuild bin path for this runtime.
		/// </summary>
		public abstract string GetMSBuildBinPath (TargetFramework fx);
		
		/// <summary>
		/// Returns the MSBuild extensions path.
		/// </summary>
		public abstract string GetMSBuildExtensionsPath ();

		/// <summary>
		/// Returns all GAC locations for this runtime.
		/// </summary>
		internal protected abstract IEnumerable<string> GetGacDirectories ();
		
		EventHandler initializedEvent;

		/// <summary>
		/// This event is fired when the runtime has finished initializing. Runtimes are initialized
		/// in a background thread, so they are not guaranteed to be ready just after the IDE has
		/// finished loading. If the runtime is already initialized when the event is subscribed, then the
		/// subscribed handler will be automatically invoked.
		/// </summary>
		public event EventHandler Initialized {
			add {
				lock (initEventLock) {
					if (initialized) {
						if (!ShuttingDown)
							value (this, EventArgs.Empty);
					}
					else
						initializedEvent += value;
				}
			}
			remove {
				lock (initEventLock) {
					initializedEvent -= value;
				}
			}
		}
		
		internal void EnsureInitialized ()
		{
			lock (initLock) {
				if (!initialized && !initializing) {
					if (!backgroundInitialize) {
						initializing = true;
						BackgroundInitialize (null);
					}
					else
						// If we are here, that's because 1) the runtime has been initialized, or 2) the runtime is being initialized by *this* thread
						throw new InvalidOperationException ("Runtime intialization not started");
				}
				if (!extensionInitialized && !initializing) {
					// Get assemblies registered using the extension point.
					// This is not done in BackgroundInitialize because the add-in manager is not thread safe
					extensionInitialized = true;
					AddinManager.AddExtensionNodeHandler ("/MonoDevelop/Core/SupportPackages", OnPackagesChanged);
				}
			}
		}
		
		void BackgroundInitialize (object state)
		{
			timer = Counters.TargetRuntimesLoading.BeginTiming ("Initializing Runtime " + Id);
			lock (initLock) {
				try {
					RunInitialization ();
				} catch (Exception ex) {
					LogReporting.LogReportingService.ReportUnhandledException (ex, false);
					LoggingService.LogFatalError ("Unhandled exception in SystemAssemblyService background initialisation thread.", ex);
				} finally {
					lock (initEventLock) {
						initializing = false;
						initialized = true;
						try {
							if (initializedEvent != null && !ShuttingDown)
								initializedEvent (this, EventArgs.Empty);
						} catch (Exception ex) {
							LoggingService.LogError ("Error while initializing the runtime: " + Id, ex);
						}
					}
					timer.End ();
				}
			}
		}
		
		void RunInitialization ()
		{
			if (ShuttingDown)
				return;
			
			timer.Trace ("Finding custom frameworks");
			var customFrameworksList = new List<TargetFramework> ();
			try {
				foreach (var dir in GetReferenceFrameworkDirectories ()) {
					if (!string.IsNullOrEmpty (dir) && Directory.Exists (dir)) {
						customFrameworksList.AddRange (FindTargetFrameworks (dir));
					}
				}
			} catch (Exception ex) {
				LoggingService.LogError ("Error finding custom frameworks", ex);
			}
			customFrameworks = customFrameworksList.ToArray ();
			
			timer.Trace ("Creating frameworks");
			CreateFrameworks ();
			
			if (ShuttingDown)
				return;
			
			timer.Trace ("Initializing frameworks");
			OnInitialize ();
		}
		
		void OnPackagesChanged (object s, ExtensionNodeEventArgs args)
		{
			PackageExtensionNode node = (PackageExtensionNode) args.ExtensionNode;
			SystemPackageInfo pi = node.GetPackageInfo ();
			
			if (args.Change == ExtensionChange.Add) {
				var existing = assemblyContext.GetPackageInternal (pi.Name);
				if (existing == null || (!existing.IsFrameworkPackage || pi.IsFrameworkPackage))
					RegisterPackage (pi, node.Assemblies);
			}
			else {
				SystemPackage p = assemblyContext.GetPackage (pi.Name, pi.Version);
				if (p.IsInternalPackage)
					assemblyContext.UnregisterPackage (pi.Name, pi.Version);
			}
		}

		/// <summary>
		/// Registers a package. It can be used by add-ins to register a package for a set of assemblies
		/// they provide.
		/// </summary>
		/// <param name="pinfo">
		/// Information about the package.
		/// </param>
		/// <param name="assemblyFiles">
		/// Assemblies that belong to the package
		/// </param>
		/// <returns>
		/// The registered package
		/// </returns>
		public SystemPackage RegisterPackage (SystemPackageInfo pinfo, params string[] assemblyFiles)
		{
			return RegisterPackage (pinfo, true, assemblyFiles);
		}

		/// <summary>
		/// Registers a package.
		/// </summary>
		/// <param name="pinfo">
		/// Information about the package.
		/// </param>
		/// <param name="isInternal">
		/// Set to true if this package is provided by an add-in and is not installed in the system.
		/// </param>
		/// <param name="assemblyFiles">
		/// A <see cref="System.String[]"/>
		/// </param>
		/// <returns>
		/// A <see cref="SystemPackage"/>
		/// </returns>
		public SystemPackage RegisterPackage (SystemPackageInfo pinfo, bool isInternal, params string[] assemblyFiles)
		{
			EnsureInitialized ();
			return assemblyContext.RegisterPackage (pinfo, isInternal, assemblyFiles);
		}
		
		/// <summary>
		/// Checks if a framework is installed in this runtime.
		/// </summary>
		/// <param name="fx">
		/// The runtime to check.
		/// </param>
		/// <returns>
		/// True if the framework is installed
		/// </returns>
		public bool IsInstalled (TargetFramework fx)
		{
			return GetBackend (fx).IsInstalled;
		}

		void CreateFrameworks ()
		{
			var frameworks = new HashSet<TargetFrameworkMoniker> ();
			
			foreach (TargetFramework fx in Runtime.SystemAssemblyService.GetKnownFrameworks ()) {
				// A framework is installed if the assemblies directory exists and the first
				// assembly of the list exists.
				if (frameworks.Add (fx.Id) && IsInstalled (fx)) {
					timer.Trace ("Registering assemblies for framework " + fx.Id);
					RegisterSystemAssemblies (fx);
				}
			}
			
			foreach (TargetFramework fx in CustomFrameworks) {
				if (frameworks.Add (fx.Id) && IsInstalled (fx)) {
					timer.Trace ("Registering assemblies for framework " + fx.Id);
					RegisterSystemAssemblies (fx);
				}
			}
		}
		
		protected bool IsCorePackage (string pname)
		{
			return corePackages.Contains (pname);
		}

		void RegisterSystemAssemblies (TargetFramework fx)
		{
			Dictionary<string,List<SystemAssembly>> assemblies = new Dictionary<string, List<SystemAssembly>> ();
			Dictionary<string,SystemPackage> packs = new Dictionary<string, SystemPackage> ();
			
			IEnumerable<string> dirs = GetFrameworkFolders (fx);

			foreach (AssemblyInfo assembly in fx.Assemblies) {
				foreach (string dir in dirs) {
					string file = Path.Combine (dir, assembly.Name) + ".dll";
					if (File.Exists (file)) {
						if (assembly.Version == null && IsRunning) {
							try {
								AssemblyName aname = SystemAssemblyService.GetAssemblyNameObj (file);
								assembly.Update (aname);
							} catch {
								// If something goes wrong when getting the name, just ignore the assembly
							}
						}
						string pkg = assembly.Package ?? string.Empty;
						SystemPackage package;
						if (!packs.TryGetValue (pkg, out package)) {
							packs [pkg] = package = new SystemPackage ();
							assemblies [pkg] = new List<SystemAssembly> ();
						}
						List<SystemAssembly> list = assemblies [pkg];
						list.Add (assemblyContext.AddAssembly (file, assembly, package));
						break;
					}
				}
			}
			
			foreach (string pkg in packs.Keys) {
				SystemPackage package = packs [pkg];
				List<SystemAssembly> list = assemblies [pkg];
				SystemPackageInfo info = GetFrameworkPackageInfo (fx, pkg);
				if (!info.IsCorePackage)
					corePackages.Add (info.Name);
				package.Initialize (info, list.ToArray (), false);
				assemblyContext.InternalAddPackage (package);
			}
		}
		
		protected virtual SystemPackageInfo GetFrameworkPackageInfo (TargetFramework fx, string packageName)
		{
			return GetBackend (fx).GetFrameworkPackageInfo (packageName);
		}

		protected static IEnumerable<TargetFramework> FindTargetFrameworks (FilePath frameworksDirectory)
		{
			return FindTargetFrameworks (frameworksDirectory, false);
		}

		protected static IEnumerable<TargetFramework> FindTargetFrameworks (FilePath frameworksDirectory, bool rescanKnownFrameworks)
		{
			foreach (FilePath idDir in Directory.GetDirectories (frameworksDirectory)) {
				var id = idDir.FileName;
				foreach (FilePath versionDir in Directory.GetDirectories (idDir)) {
					var version = versionDir.FileName;
					var moniker = new TargetFrameworkMoniker (id, version);
					if (rescanKnownFrameworks || !Runtime.SystemAssemblyService.IsKnownFramework (moniker)) {
						var fx = ReadTargetFramework (moniker, versionDir);
						if (fx != null)
							yield return (fx);
					}
					var profileListDir = versionDir.Combine ("Profile");
					if (!Directory.Exists (profileListDir))
						continue;
					foreach (FilePath profileDir in Directory.GetDirectories (profileListDir)) {
						var profile = profileDir.FileName;
						moniker = new TargetFrameworkMoniker (id, version, profile);
						if (rescanKnownFrameworks || !Runtime.SystemAssemblyService.IsKnownFramework (moniker)) {
							var fx = ReadTargetFramework (moniker, profileDir);
							if (fx != null)
								yield return (fx);
						}
					}
				}
			}
		}
		
		static TargetFramework ReadTargetFramework (TargetFrameworkMoniker moniker, FilePath directory)
		{
			try {
				return TargetFramework.FromFrameworkDirectory (moniker, directory);
			} catch (Exception ex) {
				LoggingService.LogError ("Error reading framework definition '" + directory + "'", ex);
			}
			return null;
		}
	}
}