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