Submodule ikvm reflection
[mono.git] / mcs / mcs / ikvm.cs
1 //
2 // ikvm.cs: IKVM.Reflection and IKVM.Reflection.Emit specific implementations
3 //
4 // Author: Marek Safar (marek.safar@gmail.com)
5 //
6 // Dual licensed under the terms of the MIT X11 or GNU GPL
7 //
8 // Copyright 2009-2010 Novell, Inc. 
9 // Copyright 2011 Xamarin Inc
10 //
11 //
12
13 using System;
14 using System.Collections.Generic;
15 using MetaType = IKVM.Reflection.Type;
16 using IKVM.Reflection;
17 using IKVM.Reflection.Emit;
18 using System.IO;
19 using System.Configuration.Assemblies;
20
21 namespace Mono.CSharp
22 {
23 #if !STATIC
24         public class StaticImporter
25         {
26                 public StaticImporter (BuiltinTypes builtin)
27                 {
28                         throw new NotSupportedException ();
29                 }
30
31                 public void ImportAssembly (Assembly assembly, RootNamespace targetNamespace)
32                 {
33                         throw new NotSupportedException ();
34                 }
35
36                 public void ImportModule (Module module, RootNamespace targetNamespace)
37                 {
38                         throw new NotSupportedException ();
39                 }
40
41                 public TypeSpec ImportType (System.Type type)
42                 {
43                         throw new NotSupportedException ();
44                 }
45         }
46
47 #else
48
49         sealed class StaticImporter : MetadataImporter
50         {
51                 public StaticImporter (ModuleContainer module)
52                         : base (module)
53                 {
54                 }
55
56                 public void AddCompiledAssembly (AssemblyDefinitionStatic assembly)
57                 {
58                         assembly_2_definition.Add (assembly.Builder, assembly);
59                 }
60
61                 public override void AddCompiledType (TypeBuilder type, TypeSpec spec)
62                 {
63                         compiled_types.Add (type, spec);
64                 }
65
66                 protected override MemberKind DetermineKindFromBaseType (MetaType baseType)
67                 {
68                         string name = baseType.Name;
69
70                         if (name == "ValueType" && baseType.Namespace == "System")
71                                 return MemberKind.Struct;
72
73                         if (name == "Enum" && baseType.Namespace == "System")
74                                 return MemberKind.Enum;
75
76                         if (name == "MulticastDelegate" && baseType.Namespace == "System")
77                                 return MemberKind.Delegate;
78
79                         return MemberKind.Class;
80                 }
81
82                 protected override bool HasVolatileModifier (MetaType[] modifiers)
83                 {
84                         foreach (var t in modifiers) {
85                                 if (t.Name == "IsVolatile" && t.Namespace == CompilerServicesNamespace)
86                                         return true;
87                         }
88
89                         return false;
90                 }
91
92                 public void ImportAssembly (Assembly assembly, RootNamespace targetNamespace)
93                 {
94                         // It can be used more than once when importing same assembly
95                         // into 2 or more global aliases
96                         var definition = GetAssemblyDefinition (assembly);
97
98                         var all_types = assembly.GetTypes ();
99                         ImportTypes (all_types, targetNamespace, definition.HasExtensionMethod);
100
101                         all_types = assembly.ManifestModule.__GetExportedTypes ();
102                         if (all_types.Length != 0)
103                                 ImportForwardedTypes (all_types, targetNamespace);
104                 }
105
106                 public ImportedModuleDefinition ImportModule (Module module, RootNamespace targetNamespace)
107                 {
108                         var module_definition = new ImportedModuleDefinition (module);
109                         module_definition.ReadAttributes ();
110
111                         var all_types = module.GetTypes ();
112                         ImportTypes (all_types, targetNamespace, false);
113
114                         return module_definition;
115                 }
116
117                 void ImportForwardedTypes (MetaType[] types, Namespace targetNamespace)
118                 {
119                         Namespace ns = targetNamespace;
120                         string prev_namespace = null;
121                         foreach (var t in types) {
122                                 // IsMissing tells us the type has been forwarded and target assembly is missing 
123                                 if (!t.__IsMissing)
124                                         continue;
125
126                                 if (t.Name[0] == '<')
127                                         continue;
128
129                                 var it = CreateType (t, null, new DynamicTypeReader (t), true);
130                                 if (it == null)
131                                         continue;
132
133                                 if (prev_namespace != t.Namespace) {
134                                         ns = t.Namespace == null ? targetNamespace : targetNamespace.GetNamespace (t.Namespace, true);
135                                         prev_namespace = t.Namespace;
136                                 }
137
138                                 ns.AddType (module, it);
139                         }
140                 }
141
142                 public void InitializeBuiltinTypes (BuiltinTypes builtin, Assembly corlib)
143                 {
144                         //
145                         // Setup mapping for build-in types to avoid duplication of their definition
146                         //
147                         foreach (var type in builtin.AllTypes) {
148                                 compiled_types.Add (corlib.GetType (type.FullName), type);
149                         }
150                 }
151         }
152 #endif
153
154         class AssemblyDefinitionStatic : AssemblyDefinition
155         {
156                 readonly StaticLoader loader;
157
158                 //
159                 // Assembly container with file output
160                 //
161                 public AssemblyDefinitionStatic (ModuleContainer module, StaticLoader loader, string name, string fileName)
162                         : base (module, name, fileName)
163                 {
164                         this.loader = loader;
165                         Importer = loader.MetadataImporter;
166                 }
167
168                 //
169                 // Initializes the assembly SRE domain
170                 //
171                 public void Create (Universe domain)
172                 {
173                         ResolveAssemblySecurityAttributes ();
174                         var an = CreateAssemblyName ();
175
176                         Builder = domain.DefineDynamicAssembly (an, AssemblyBuilderAccess.Save, Path.GetDirectoryName (file_name));
177                         module.Create (this, CreateModuleBuilder ());
178                 }
179
180                 public override void Emit ()
181                 {
182                         if (loader.Corlib != null && !(loader.Corlib is AssemblyBuilder)) {
183                                 Builder.__SetImageRuntimeVersion (loader.Corlib.ImageRuntimeVersion, 0x20000);
184                         } else {
185                                 // Sets output file metadata version when there is no mscorlib
186                                 switch (module.Compiler.Settings.StdLibRuntimeVersion) {
187                                 case RuntimeVersion.v4:
188                                         Builder.__SetImageRuntimeVersion ("v4.0.30319", 0x20000);
189                                         break;
190                                 case RuntimeVersion.v2:
191                                         Builder.__SetImageRuntimeVersion ("v2.0.50727", 0x20000);
192                                         break;
193                                 case RuntimeVersion.v1:
194                                         // Compiler does not do any checks whether the produced metadata
195                                         // are valid in the context of 1.0 stream version
196                                         Builder.__SetImageRuntimeVersion ("v1.1.4322", 0x10000);
197                                         break;
198                                 default:
199                                         throw new NotImplementedException ();
200                                 }
201                         }
202
203                         builder_extra = new AssemblyBuilderIKVM (Builder, Compiler);
204
205                         base.Emit ();
206                 }
207
208                 public Module IncludeModule (RawModule moduleFile)
209                 {
210                         return Builder.__AddModule (moduleFile);
211                 }
212
213                 protected override void SaveModule (PortableExecutableKinds pekind, ImageFileMachine machine)
214                 {
215                         module.Builder.__Save (pekind, machine);
216                 }
217         }
218
219         class StaticLoader : AssemblyReferencesLoader<Assembly>, IDisposable
220         {
221                 readonly StaticImporter importer;
222                 readonly Universe domain;
223                 Assembly corlib;
224                 List<Tuple<AssemblyName, string, Assembly>> loaded_names;
225                 static readonly Dictionary<string, string[]> sdk_directory;
226
227                 static StaticLoader ()
228                 {
229                         sdk_directory = new Dictionary<string, string[]> ();
230                         sdk_directory.Add ("2", new string[] { "2.0", "net_2_0", "v2.0.50727" });
231                         sdk_directory.Add ("4", new string[] { "4.0", "net_4_0", "v4.0.30319" });
232                         sdk_directory.Add ("4.5", new string[] { "4.5", "net_4_5", "v4.0.30319" });
233                 }
234
235                 public StaticLoader (StaticImporter importer, CompilerContext compiler)
236                         : base (compiler)
237                 {
238                         this.importer = importer;
239                         domain = new Universe ();
240                         domain.EnableMissingMemberResolution ();
241                         domain.AssemblyResolve += AssemblyReferenceResolver;
242                         loaded_names = new List<Tuple<AssemblyName, string, Assembly>> ();
243
244                         if (compiler.Settings.StdLib) {
245                                 var corlib_path = Path.GetDirectoryName (typeof (object).Assembly.Location);
246                                 string fx_path = corlib_path.Substring (0, corlib_path.LastIndexOf (Path.DirectorySeparatorChar));
247
248                                 string sdk_path = null;
249
250                                 string sdk_version = compiler.Settings.SdkVersion ?? "4.5";
251                                 string[] sdk_sub_dirs;
252
253                                 if (!sdk_directory.TryGetValue (sdk_version, out sdk_sub_dirs))
254                                         sdk_sub_dirs = new string[] { sdk_version };
255
256                                 foreach (var dir in sdk_sub_dirs) {
257                                         sdk_path = Path.Combine (fx_path, dir);
258                                         if (File.Exists (Path.Combine (sdk_path, "mscorlib.dll")))
259                                                 break;
260
261                                         sdk_path = null;
262                                 }
263
264                                 if (sdk_path == null) {
265                                         compiler.Report.Warning (-1, 1, "SDK path could not be resolved");
266                                         sdk_path = corlib_path;
267                                 }
268
269                                 paths.Add (sdk_path);
270                         }
271                 }
272
273                 #region Properties
274
275                 public Assembly Corlib {
276                         get {
277                                 return corlib;
278                         }
279                 }
280
281                 public Universe Domain {
282                         get {
283                                 return domain;
284                         }
285                 }
286
287                 public StaticImporter MetadataImporter {
288                         get {
289                                 return importer;
290                         }
291                 }
292
293                 #endregion
294
295                 Assembly AssemblyReferenceResolver (object sender, IKVM.Reflection.ResolveEventArgs args)
296                 {
297                         var refname = args.Name;
298                         if (refname == "mscorlib")
299                                 return corlib;
300
301                         Assembly version_mismatch = null;
302                         bool is_fx_assembly = false;
303
304                         foreach (var assembly in domain.GetAssemblies ()) {
305                                 AssemblyComparisonResult result;
306                                 if (!Fusion.CompareAssemblyIdentityPure (refname, false, assembly.FullName, false, out result)) {
307                                         if ((result == AssemblyComparisonResult.NonEquivalentVersion || result == AssemblyComparisonResult.NonEquivalentPartialVersion) &&
308                                                 (version_mismatch == null || version_mismatch.GetName ().Version < assembly.GetName ().Version) &&
309                                                 !is_fx_assembly) {
310                                                 version_mismatch = assembly;
311                                         }
312
313                                         continue;
314                                 }
315
316                                 if (result == AssemblyComparisonResult.EquivalentFullMatch ||
317                                         result == AssemblyComparisonResult.EquivalentWeakNamed ||
318                                         result == AssemblyComparisonResult.EquivalentPartialMatch) {
319                                         return assembly;
320                                 }
321
322                                 if (result == AssemblyComparisonResult.EquivalentFXUnified) {
323                                         is_fx_assembly = true;
324
325                                         if (version_mismatch == null || version_mismatch.GetName ().Version < assembly.GetName ().Version)
326                                                 version_mismatch = assembly;
327
328                                         continue;
329                                 }
330
331                                 throw new NotImplementedException ("Assembly equality = " + result.ToString ());
332                         }
333
334                         if (version_mismatch != null) {
335                                 if (version_mismatch is AssemblyBuilder)
336                                         return version_mismatch;
337
338                                 var v1 = new AssemblyName (refname).Version;
339                                 var v2 = version_mismatch.GetName ().Version;
340
341                                 if (v1 > v2) {
342 //                                      compiler.Report.SymbolRelatedToPreviousError (args.RequestingAssembly.Location);
343                                         compiler.Report.Error (1705, "Assembly `{0}' references `{1}' which has a higher version number than imported assembly `{2}'",
344                                                 args.RequestingAssembly.FullName, refname, version_mismatch.GetName ().FullName);
345
346                                         return domain.CreateMissingAssembly (args.Name);
347                                 }
348
349                                 if (!is_fx_assembly) {
350                                         if (v1.Major != v2.Major || v1.Minor != v2.Minor) {
351                                                 compiler.Report.Warning (1701, 2,
352                                                         "Assuming assembly reference `{0}' matches assembly `{1}'. You may need to supply runtime policy",
353                                                         refname, version_mismatch.GetName ().FullName);
354                                         } else {
355                                                 compiler.Report.Warning (1702, 3,
356                                                         "Assuming assembly reference `{0}' matches assembly `{1}'. You may need to supply runtime policy",
357                                                         refname, version_mismatch.GetName ().FullName);
358                                         }
359                                 }
360
361                                 return version_mismatch;
362                         }
363
364                         // AssemblyReference has not been found in the domain
365                         // create missing reference and continue
366                         return domain.CreateMissingAssembly (args.Name);
367                 }
368
369                 public void Dispose ()
370                 {
371                         domain.Dispose ();
372                 }
373
374                 protected override string[] GetDefaultReferences ()
375                 {
376                         //
377                         // For now the "default config" is harcoded into the compiler
378                         // we can move this outside later
379                         //
380                         var default_references = new List<string> (4);
381
382                         default_references.Add ("System.dll");
383                         default_references.Add ("System.Xml.dll");
384                         default_references.Add ("System.Core.dll");
385
386                         if (corlib != null && corlib.GetName ().Version.Major >= 4) {
387                                 default_references.Add ("Microsoft.CSharp.dll");
388                         }
389
390                         return default_references.ToArray ();
391                 }
392
393                 public override bool HasObjectType (Assembly assembly)
394                 {
395                         return assembly.GetType (compiler.BuiltinTypes.Object.FullName) != null;
396                 }
397
398                 public override Assembly LoadAssemblyFile (string fileName, bool isImplicitReference)
399                 {
400                         bool? has_extension = null;
401                         foreach (var path in paths) {
402                                 var file = Path.Combine (path, fileName);
403                                 if (compiler.Settings.DebugFlags > 0)
404                                         Console.WriteLine ("Probing assembly location `{0}'", file);
405
406                                 if (!File.Exists (file)) {
407                                         if (!has_extension.HasValue)
408                                                 has_extension = fileName.EndsWith (".dll", StringComparison.Ordinal) || fileName.EndsWith (".exe", StringComparison.Ordinal);
409
410                                         if (has_extension.Value)
411                                                 continue;
412
413                                         file += ".dll";
414                                         if (!File.Exists (file))
415                                                 continue;
416                                 }
417
418                                 try {
419                                         using (RawModule module = domain.OpenRawModule (file)) {
420                                                 if (!module.IsManifestModule) {
421                                                         Error_AssemblyIsModule (fileName);
422                                                         return null;
423                                                 }
424
425                                                 //
426                                                 // check whether the assembly can be actually imported without
427                                                 // collision
428                                                 //
429                                                 var an = module.GetAssemblyName ();
430                                                 foreach (var entry in loaded_names) {
431                                                         var loaded_name = entry.Item1;
432                                                         if (an.Name != loaded_name.Name)
433                                                                 continue;
434
435                                                         if (module.ModuleVersionId == entry.Item3.ManifestModule.ModuleVersionId)
436                                                                 return entry.Item3;
437                                                         
438                                                         if (((an.Flags | loaded_name.Flags) & AssemblyNameFlags.PublicKey) == 0) {
439                                                                 compiler.Report.SymbolRelatedToPreviousError (entry.Item2);
440                                                                 compiler.Report.SymbolRelatedToPreviousError (fileName);
441                                                                 compiler.Report.Error (1704,
442                                                                         "An assembly with the same name `{0}' has already been imported. Consider removing one of the references or sign the assembly",
443                                                                         an.Name);
444                                                                 return null;
445                                                         }
446
447                                                         if ((an.Flags & AssemblyNameFlags.PublicKey) == (loaded_name.Flags & AssemblyNameFlags.PublicKey) && an.Version.Equals (loaded_name.Version)) {
448                                                                 compiler.Report.SymbolRelatedToPreviousError (entry.Item2);
449                                                                 compiler.Report.SymbolRelatedToPreviousError (fileName);
450                                                                 compiler.Report.Error (1703,
451                                                                         "An assembly with the same identity `{0}' has already been imported. Consider removing one of the references",
452                                                                         an.FullName);
453                                                                 return null;
454                                                         }
455                                                 }
456
457                                                 if (compiler.Settings.DebugFlags > 0)
458                                                         Console.WriteLine ("Loading assembly `{0}'", fileName);
459
460                                                 var assembly = domain.LoadAssembly (module);
461                                                 if (assembly != null)
462                                                         loaded_names.Add (Tuple.Create (an, fileName, assembly));
463
464                                                 return assembly;
465                                         }
466                                 } catch {
467                                         if (!isImplicitReference)
468                                                 Error_FileCorrupted (file);
469
470                                         return null;
471                                 }
472                         }
473
474                         if (!isImplicitReference)
475                                 Error_FileNotFound (fileName);
476
477                         return null;
478                 }
479
480                 public RawModule LoadModuleFile (string moduleName)
481                 {
482                         foreach (var path in paths) {
483                                 var file = Path.Combine (path, moduleName);
484                                 if (!File.Exists (file)) {
485                                         if (moduleName.EndsWith (".netmodule", StringComparison.Ordinal))
486                                                 continue;
487
488                                         file += ".netmodule";
489                                         if (!File.Exists (file))
490                                                 continue;
491                                 }
492
493                                 try {
494                                         return domain.OpenRawModule (file);
495                                 } catch {
496                                         Error_FileCorrupted (file);
497                                         return null;
498                                 }
499                         }
500
501                         Error_FileNotFound (moduleName);
502                         return null;                            
503                 }
504
505                 public override void LoadReferences (ModuleContainer module)
506                 {
507                         List<Tuple<RootNamespace, Assembly>> loaded;
508                         base.LoadReferencesCore (module, out corlib, out loaded);
509
510                         compiler.TimeReporter.Start (TimeReporter.TimerType.ReferencesImporting);
511
512                         if (corlib == null) {
513                                 // System.Object was not found in any referenced assembly, use compiled assembly as corlib
514                                 corlib = module.DeclaringAssembly.Builder;
515                         } else {
516                                 importer.InitializeBuiltinTypes (compiler.BuiltinTypes, corlib);
517                                 importer.ImportAssembly (corlib, module.GlobalRootNamespace);
518                         }
519
520                         foreach (var entry in loaded) {
521                                 importer.ImportAssembly (entry.Item2, entry.Item1);
522                         }
523
524                         compiler.TimeReporter.Stop (TimeReporter.TimerType.ReferencesImporting);
525                 }
526
527                 public void LoadModules (AssemblyDefinitionStatic assembly, RootNamespace targetNamespace)
528                 {
529                         foreach (var moduleName in compiler.Settings.Modules) {
530                                 var m = LoadModuleFile (moduleName);
531                                 if (m == null)
532                                         continue;
533
534                                 if (m.IsManifestModule) {
535                                         Error_ModuleIsAssembly (moduleName);
536                                         continue;
537                                 }
538
539                                 var md = importer.ImportModule (assembly.IncludeModule (m), targetNamespace);
540                                 assembly.AddModule (md);
541                         }
542                 }
543         }
544
545         class AssemblyBuilderIKVM : AssemblyBuilderExtension
546         {
547                 readonly AssemblyBuilder builder;
548
549                 public AssemblyBuilderIKVM (AssemblyBuilder builder, CompilerContext ctx)
550                         : base (ctx)
551                 {
552                         this.builder = builder;
553                 }
554
555                 public override void AddTypeForwarder (TypeSpec type, Location loc)
556                 {
557                         builder.__AddTypeForwarder (type.GetMetaInfo ());
558                 }
559
560                 public override void DefineWin32IconResource (string fileName)
561                 {
562                         builder.__DefineIconResource (File.ReadAllBytes (fileName));
563                 }
564
565                 public override void SetAlgorithmId (uint value, Location loc)
566                 {
567                         builder.__SetAssemblyAlgorithmId ((AssemblyHashAlgorithm) value);
568                 }
569
570                 public override void SetCulture (string culture, Location loc)
571                 {
572                         builder.__SetAssemblyCulture (culture);
573                 }
574
575                 public override void SetFlags (uint flags, Location loc)
576                 {
577                         builder.__AssemblyFlags = (AssemblyNameFlags) flags;
578                 }
579
580                 public override void SetVersion (Version version, Location loc)
581                 {
582                         builder.__SetAssemblyVersion (version);
583                 }
584         }
585 }