summaryrefslogtreecommitdiff
path: root/mcs/mcs/ikvm.cs
blob: 0d3232c75ae40e4a1f69cf54059a031515b54988 (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
//
// ikvm.cs: IKVM.Reflection and IKVM.Reflection.Emit specific implementations
//
// Author: Marek Safar (marek.safar@gmail.com)
//
// Dual licensed under the terms of the MIT X11 or GNU GPL
//
// Copyright 2009-2010 Novell, Inc. 
// Copyright 2011 Xamarin Inc
//
//

using System;
using System.Collections.Generic;
using MetaType = IKVM.Reflection.Type;
using IKVM.Reflection;
using IKVM.Reflection.Emit;
using System.IO;
using System.Configuration.Assemblies;

namespace Mono.CSharp
{
#if !STATIC
	public class StaticImporter
	{
		public StaticImporter (BuiltinTypes builtin)
		{
			throw new NotSupportedException ();
		}

		public void ImportAssembly (Assembly assembly, RootNamespace targetNamespace)
		{
			throw new NotSupportedException ();
		}

		public void ImportModule (Module module, RootNamespace targetNamespace)
		{
			throw new NotSupportedException ();
		}

		public TypeSpec ImportType (System.Type type)
		{
			throw new NotSupportedException ();
		}
	}

#else

	sealed class StaticImporter : MetadataImporter
	{
		public StaticImporter (ModuleContainer module)
			: base (module)
		{
		}

		public void AddCompiledAssembly (AssemblyDefinitionStatic assembly)
		{
			assembly_2_definition.Add (assembly.Builder, assembly);
		}

		public override void AddCompiledType (TypeBuilder type, TypeSpec spec)
		{
			compiled_types.Add (type, spec);
		}

		protected override MemberKind DetermineKindFromBaseType (MetaType baseType)
		{
			string name = baseType.Name;

			if (name == "ValueType" && baseType.Namespace == "System")
				return MemberKind.Struct;

			if (name == "Enum" && baseType.Namespace == "System")
				return MemberKind.Enum;

			if (name == "MulticastDelegate" && baseType.Namespace == "System")
				return MemberKind.Delegate;

			return MemberKind.Class;
		}

		protected override bool HasVolatileModifier (MetaType[] modifiers)
		{
			foreach (var t in modifiers) {
				if (t.Name == "IsVolatile" && t.Namespace == CompilerServicesNamespace)
					return true;
			}

			return false;
		}

		public void ImportAssembly (Assembly assembly, RootNamespace targetNamespace)
		{
			try {
				// It can be used more than once when importing same assembly
				// into 2 or more global aliases
				// TODO: Should be just Add
				GetAssemblyDefinition (assembly);

				var all_types = assembly.GetTypes ();
				ImportTypes (all_types, targetNamespace, true);

				all_types = assembly.ManifestModule.__GetExportedTypes ();
				if (all_types.Length != 0)
					ImportForwardedTypes (all_types, targetNamespace);
			} catch (Exception e) {
				throw new InternalErrorException (e, "Failed to import assembly `{0}'", assembly.FullName);
			}
		}

		public ImportedModuleDefinition ImportModule (Module module, RootNamespace targetNamespace)
		{
			var module_definition = new ImportedModuleDefinition (module);
			module_definition.ReadAttributes ();

			var all_types = module.GetTypes ();
			ImportTypes (all_types, targetNamespace, false);

			return module_definition;
		}

		void ImportForwardedTypes (MetaType[] types, Namespace targetNamespace)
		{
			Namespace ns = targetNamespace;
			string prev_namespace = null;
			foreach (var t in types) {
				if (!t.__IsTypeForwarder)
					continue;

				// IsMissing tells us the type has been forwarded and target assembly is missing 
				if (!t.__IsMissing)
					continue;

				if (t.Name[0] == '<')
					continue;

				var it = CreateType (t, null, new DynamicTypeReader (t), true);
				if (it == null)
					continue;

				if (prev_namespace != t.Namespace) {
					ns = t.Namespace == null ? targetNamespace : targetNamespace.GetNamespace (t.Namespace, true);
					prev_namespace = t.Namespace;
				}

				ns.AddType (module, it);
			}
		}

		public void InitializeBuiltinTypes (BuiltinTypes builtin, Assembly corlib)
		{
			//
			// Setup mapping for build-in types to avoid duplication of their definition
			//
			foreach (var type in builtin.AllTypes) {
				compiled_types.Add (corlib.GetType (type.FullName), type);
			}
		}
	}
#endif

	class AssemblyDefinitionStatic : AssemblyDefinition
	{
		readonly StaticLoader loader;

		//
		// Assembly container with file output
		//
		public AssemblyDefinitionStatic (ModuleContainer module, StaticLoader loader, string name, string fileName)
			: base (module, name, fileName)
		{
			this.loader = loader;
			Importer = loader.MetadataImporter;
		}

		//
		// Initializes the assembly SRE domain
		//
		public void Create (Universe domain)
		{
			ResolveAssemblySecurityAttributes ();
			var an = CreateAssemblyName ();

			Builder = domain.DefineDynamicAssembly (an, AssemblyBuilderAccess.Save, Path.GetDirectoryName (file_name));
			module.Create (this, CreateModuleBuilder ());
		}

		public override void Emit ()
		{
			if (loader.Corlib != null && !(loader.Corlib is AssemblyBuilder)) {
				Builder.__SetImageRuntimeVersion (loader.Corlib.ImageRuntimeVersion, 0x20000);
			} else {
				// Sets output file metadata version when there is no mscorlib
				switch (module.Compiler.Settings.StdLibRuntimeVersion) {
				case RuntimeVersion.v4:
					Builder.__SetImageRuntimeVersion ("v4.0.30319", 0x20000);
					break;
				case RuntimeVersion.v2:
					Builder.__SetImageRuntimeVersion ("v2.0.50727", 0x20000);
					break;
				case RuntimeVersion.v1:
					// Compiler does not do any checks whether the produced metadata
					// are valid in the context of 1.0 stream version
					Builder.__SetImageRuntimeVersion ("v1.1.4322", 0x10000);
					break;
				default:
					throw new NotImplementedException ();
				}
			}

			builder_extra = new AssemblyBuilderIKVM (Builder, Compiler);

			base.Emit ();
		}

		public Module IncludeModule (RawModule moduleFile)
		{
			return Builder.__AddModule (moduleFile);
		}

		protected override void SaveModule (PortableExecutableKinds pekind, ImageFileMachine machine)
		{
			module.Builder.__Save (pekind, machine);
		}
	}

	class StaticLoader : AssemblyReferencesLoader<Assembly>, IDisposable
	{
		readonly StaticImporter importer;
		readonly Universe domain;
		Assembly corlib;
		readonly List<Tuple<AssemblyName, string, Assembly>> loaded_names;
		static readonly Dictionary<string, string[]> sdk_directory;

		static StaticLoader ()
		{
			sdk_directory = new Dictionary<string, string[]> ();
			sdk_directory.Add ("2", new string[] { "2.0", "net_2_0", "v2.0.50727" });
			sdk_directory.Add ("4", new string[] { "4.0", "net_4_0", "v4.0.30319" });
			sdk_directory.Add ("4.5", new string[] { "4.5", "net_4_5", "v4.0.30319" });
		}

		public StaticLoader (StaticImporter importer, CompilerContext compiler)
			: base (compiler)
		{
			this.importer = importer;
			domain = new Universe (UniverseOptions.MetadataOnly | UniverseOptions.ResolveMissingMembers | UniverseOptions.DisableFusion);
			domain.AssemblyResolve += AssemblyReferenceResolver;
			loaded_names = new List<Tuple<AssemblyName, string, Assembly>> ();

			if (compiler.Settings.StdLib) {
				var corlib_path = Path.GetDirectoryName (typeof (object).Assembly.Location);
				string fx_path = corlib_path.Substring (0, corlib_path.LastIndexOf (Path.DirectorySeparatorChar));

				string sdk_path = null;

				string sdk_version = compiler.Settings.SdkVersion ?? "4.5";
				string[] sdk_sub_dirs;

				if (!sdk_directory.TryGetValue (sdk_version, out sdk_sub_dirs))
					sdk_sub_dirs = new string[] { sdk_version };

				foreach (var dir in sdk_sub_dirs) {
					sdk_path = Path.Combine (fx_path, dir);
					if (File.Exists (Path.Combine (sdk_path, "mscorlib.dll")))
						break;

					sdk_path = null;
				}

				if (sdk_path == null) {
					compiler.Report.Warning (-1, 1, "SDK path could not be resolved");
					sdk_path = corlib_path;
				}

				paths.Add (sdk_path);
			}
		}

		#region Properties

		public Assembly Corlib {
			get {
				return corlib;
			}
		}

		public AssemblyDefinitionStatic CompiledAssembly {  get; set; }

		public Universe Domain {
			get {
				return domain;
			}
		}

		public StaticImporter MetadataImporter {
			get {
				return importer;
			}
		}

		#endregion

		Assembly AssemblyReferenceResolver (object sender, IKVM.Reflection.ResolveEventArgs args)
		{
			var refname = args.Name;
			if (refname == "mscorlib")
				return corlib;

			Assembly version_mismatch = null;
			bool is_fx_assembly = false;

			foreach (var assembly in domain.GetAssemblies ()) {
				AssemblyComparisonResult result;
				if (!domain.CompareAssemblyIdentity (refname, false, assembly.FullName, false, out result)) {
					if ((result == AssemblyComparisonResult.NonEquivalentVersion || result == AssemblyComparisonResult.NonEquivalentPartialVersion) &&
						(version_mismatch == null || version_mismatch.GetName ().Version < assembly.GetName ().Version) &&
						!is_fx_assembly) {
						version_mismatch = assembly;
					}

					continue;
				}

				if (result == AssemblyComparisonResult.EquivalentFullMatch ||
					result == AssemblyComparisonResult.EquivalentWeakNamed ||
					result == AssemblyComparisonResult.EquivalentPartialMatch) {
					return assembly;
				}

				if (result == AssemblyComparisonResult.EquivalentFXUnified) {
					is_fx_assembly = true;

					if (version_mismatch == null || version_mismatch.GetName ().Version < assembly.GetName ().Version)
						version_mismatch = assembly;

					continue;
				}

				throw new NotImplementedException ("Assembly equality = " + result.ToString ());
			}

			if (version_mismatch != null) {
				if (version_mismatch is AssemblyBuilder)
					return version_mismatch;

				var v1 = new AssemblyName (refname).Version;
				var v2 = version_mismatch.GetName ().Version;

				if (v1 > v2) {
//					compiler.Report.SymbolRelatedToPreviousError (args.RequestingAssembly.Location);
					compiler.Report.Error (1705, "Assembly `{0}' references `{1}' which has a higher version number than imported assembly `{2}'",
						args.RequestingAssembly.FullName, refname, version_mismatch.GetName ().FullName);

					return domain.CreateMissingAssembly (args.Name);
				}

				if (!is_fx_assembly) {
					if (v1.Major != v2.Major || v1.Minor != v2.Minor) {
						compiler.Report.Warning (1701, 2,
							"Assuming assembly reference `{0}' matches assembly `{1}'. You may need to supply runtime policy",
							refname, version_mismatch.GetName ().FullName);
					} else {
						compiler.Report.Warning (1702, 3,
							"Assuming assembly reference `{0}' matches assembly `{1}'. You may need to supply runtime policy",
							refname, version_mismatch.GetName ().FullName);
					}
				}

				return version_mismatch;
			}

			//
			// Recursive reference to compiled assembly checks name only. Any other
			// details (PublicKey, Version, etc) are not yet known hence cannot be checked
			//
			ParsedAssemblyName referenced_assembly;
			if (Fusion.ParseAssemblyName (args.Name, out referenced_assembly) == ParseAssemblyResult.OK && CompiledAssembly.Name == referenced_assembly.Name)
				return CompiledAssembly.Builder;

			// AssemblyReference has not been found in the domain
			// create missing reference and continue
			return domain.CreateMissingAssembly (args.Name);
		}

		public void Dispose ()
		{
			domain.Dispose ();
		}

		protected override string[] GetDefaultReferences ()
		{
			//
			// For now the "default config" is harcoded into the compiler
			// we can move this outside later
			//
			var default_references = new List<string> (4);

			default_references.Add ("System.dll");
			default_references.Add ("System.Xml.dll");
			default_references.Add ("System.Core.dll");

			if (corlib != null && corlib.GetName ().Version.Major >= 4) {
				default_references.Add ("Microsoft.CSharp.dll");
			}

			return default_references.ToArray ();
		}

		public override bool HasObjectType (Assembly assembly)
		{
			return assembly.GetType (compiler.BuiltinTypes.Object.FullName) != null;
		}

		public override Assembly LoadAssemblyFile (string fileName, bool isImplicitReference)
		{
			bool? has_extension = null;
			foreach (var path in paths) {
				var file = Path.Combine (path, fileName);
				if (compiler.Settings.DebugFlags > 0)
					Console.WriteLine ("Probing assembly location `{0}'", file);

				if (!File.Exists (file)) {
					if (!has_extension.HasValue)
						has_extension = fileName.EndsWith (".dll", StringComparison.Ordinal) || fileName.EndsWith (".exe", StringComparison.Ordinal);

					if (has_extension.Value)
						continue;

					file += ".dll";
					if (!File.Exists (file))
						continue;
				}

				try {
					using (var stream = new FileStream (file, FileMode.Open, FileAccess.Read, FileShare.Read)) {
						using (RawModule module = domain.OpenRawModule (stream, file)) {
							if (!module.IsManifestModule) {
								Error_AssemblyIsModule (fileName);
								return null;
							}

							//
							// check whether the assembly can be actually imported without
							// collision
							//
							var an = module.GetAssemblyName ();
							foreach (var entry in loaded_names) {
								var loaded_name = entry.Item1;
								if (an.Name != loaded_name.Name)
									continue;

								if (module.ModuleVersionId == entry.Item3.ManifestModule.ModuleVersionId)
									return entry.Item3;
							
								if (((an.Flags | loaded_name.Flags) & AssemblyNameFlags.PublicKey) == 0) {
									compiler.Report.SymbolRelatedToPreviousError (entry.Item2);
									compiler.Report.SymbolRelatedToPreviousError (fileName);
									compiler.Report.Error (1704,
										"An assembly with the same name `{0}' has already been imported. Consider removing one of the references or sign the assembly",
										an.Name);
									return null;
								}

								if ((an.Flags & AssemblyNameFlags.PublicKey) == (loaded_name.Flags & AssemblyNameFlags.PublicKey) && an.Version.Equals (loaded_name.Version)) {
									compiler.Report.SymbolRelatedToPreviousError (entry.Item2);
									compiler.Report.SymbolRelatedToPreviousError (fileName);
									compiler.Report.Error (1703,
										"An assembly with the same identity `{0}' has already been imported. Consider removing one of the references",
										an.FullName);
									return null;
								}
							}

							if (compiler.Settings.DebugFlags > 0)
								Console.WriteLine ("Loading assembly `{0}'", fileName);

							var assembly = domain.LoadAssembly (module);
							if (assembly != null)
								loaded_names.Add (Tuple.Create (an, fileName, assembly));

							return assembly;
						}
					}
				} catch (Exception e) {
					if (compiler.Settings.DebugFlags > 0)
						Console.WriteLine ("Exception during loading: {0}'", e.ToString ());

					if (!isImplicitReference)
						Error_FileCorrupted (file);

					return null;
				}
			}

			if (!isImplicitReference)
				Error_FileNotFound (fileName);

			return null;
		}

		public RawModule LoadModuleFile (string moduleName)
		{
			foreach (var path in paths) {
				var file = Path.Combine (path, moduleName);
				if (!File.Exists (file)) {
					if (moduleName.EndsWith (".netmodule", StringComparison.Ordinal))
						continue;

					file += ".netmodule";
					if (!File.Exists (file))
						continue;
				}

				try {
					return domain.OpenRawModule (file);
				} catch {
					Error_FileCorrupted (file);
					return null;
				}
			}

			Error_FileNotFound (moduleName);
			return null;				
		}

		public override void LoadReferences (ModuleContainer module)
		{
			List<Tuple<RootNamespace, Assembly>> loaded;
			base.LoadReferencesCore (module, out corlib, out loaded);

			compiler.TimeReporter.Start (TimeReporter.TimerType.ReferencesImporting);

			if (corlib == null) {
				// System.Object was not found in any referenced assembly, use compiled assembly as corlib
				corlib = module.DeclaringAssembly.Builder;
			} else {
				importer.InitializeBuiltinTypes (compiler.BuiltinTypes, corlib);
				importer.ImportAssembly (corlib, module.GlobalRootNamespace);
			}

			foreach (var entry in loaded) {
				importer.ImportAssembly (entry.Item2, entry.Item1);
			}

			compiler.TimeReporter.Stop (TimeReporter.TimerType.ReferencesImporting);
		}

		public void LoadModules (AssemblyDefinitionStatic assembly, RootNamespace targetNamespace)
		{
			foreach (var moduleName in compiler.Settings.Modules) {
				var m = LoadModuleFile (moduleName);
				if (m == null)
					continue;

				if (m.IsManifestModule) {
					Error_ModuleIsAssembly (moduleName);
					continue;
				}

				var md = importer.ImportModule (assembly.IncludeModule (m), targetNamespace);
				assembly.AddModule (md);
			}
		}
	}

	class AssemblyBuilderIKVM : AssemblyBuilderExtension
	{
		readonly AssemblyBuilder builder;

		public AssemblyBuilderIKVM (AssemblyBuilder builder, CompilerContext ctx)
			: base (ctx)
		{
			this.builder = builder;
		}

		public override void AddTypeForwarder (TypeSpec type, Location loc)
		{
			builder.__AddTypeForwarder (type.GetMetaInfo ());
		}

		public override void DefineWin32IconResource (string fileName)
		{
			builder.__DefineIconResource (File.ReadAllBytes (fileName));
		}

		public override void SetAlgorithmId (uint value, Location loc)
		{
			builder.__SetAssemblyAlgorithmId ((AssemblyHashAlgorithm) value);
		}

		public override void SetCulture (string culture, Location loc)
		{
			builder.__SetAssemblyCulture (culture);
		}

		public override void SetFlags (uint flags, Location loc)
		{
			builder.__AssemblyFlags = (AssemblyNameFlags) flags;
		}

		public override void SetVersion (Version version, Location loc)
		{
			builder.__SetAssemblyVersion (version);
		}
	}
}