Merge pull request #606 from sesef/master
[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                         // TODO: Should be just Add
97                         GetAssemblyDefinition (assembly);
98
99                         var all_types = assembly.GetTypes ();
100                         ImportTypes (all_types, targetNamespace, true);
101
102                         all_types = assembly.ManifestModule.__GetExportedTypes ();
103                         if (all_types.Length != 0)
104                                 ImportForwardedTypes (all_types, targetNamespace);
105                 }
106
107                 public ImportedModuleDefinition ImportModule (Module module, RootNamespace targetNamespace)
108                 {
109                         var module_definition = new ImportedModuleDefinition (module);
110                         module_definition.ReadAttributes ();
111
112                         var all_types = module.GetTypes ();
113                         ImportTypes (all_types, targetNamespace, false);
114
115                         return module_definition;
116                 }
117
118                 void ImportForwardedTypes (MetaType[] types, Namespace targetNamespace)
119                 {
120                         Namespace ns = targetNamespace;
121                         string prev_namespace = null;
122                         foreach (var t in types) {
123                                 // IsMissing tells us the type has been forwarded and target assembly is missing 
124                                 if (!t.__IsMissing)
125                                         continue;
126
127                                 if (t.Name[0] == '<')
128                                         continue;
129
130                                 var it = CreateType (t, null, new DynamicTypeReader (t), true);
131                                 if (it == null)
132                                         continue;
133
134                                 if (prev_namespace != t.Namespace) {
135                                         ns = t.Namespace == null ? targetNamespace : targetNamespace.GetNamespace (t.Namespace, true);
136                                         prev_namespace = t.Namespace;
137                                 }
138
139                                 ns.AddType (module, it);
140                         }
141                 }
142
143                 public void InitializeBuiltinTypes (BuiltinTypes builtin, Assembly corlib)
144                 {
145                         //
146                         // Setup mapping for build-in types to avoid duplication of their definition
147                         //
148                         foreach (var type in builtin.AllTypes) {
149                                 compiled_types.Add (corlib.GetType (type.FullName), type);
150                         }
151                 }
152         }
153 #endif
154
155         class AssemblyDefinitionStatic : AssemblyDefinition
156         {
157                 readonly StaticLoader loader;
158
159                 //
160                 // Assembly container with file output
161                 //
162                 public AssemblyDefinitionStatic (ModuleContainer module, StaticLoader loader, string name, string fileName)
163                         : base (module, name, fileName)
164                 {
165                         this.loader = loader;
166                         Importer = loader.MetadataImporter;
167                 }
168
169                 //
170                 // Initializes the assembly SRE domain
171                 //
172                 public void Create (Universe domain)
173                 {
174                         ResolveAssemblySecurityAttributes ();
175                         var an = CreateAssemblyName ();
176
177                         Builder = domain.DefineDynamicAssembly (an, AssemblyBuilderAccess.Save, Path.GetDirectoryName (file_name));
178                         module.Create (this, CreateModuleBuilder ());
179                 }
180
181                 public override void Emit ()
182                 {
183                         if (loader.Corlib != null && !(loader.Corlib is AssemblyBuilder)) {
184                                 Builder.__SetImageRuntimeVersion (loader.Corlib.ImageRuntimeVersion, 0x20000);
185                         } else {
186                                 // Sets output file metadata version when there is no mscorlib
187                                 switch (module.Compiler.Settings.StdLibRuntimeVersion) {
188                                 case RuntimeVersion.v4:
189                                         Builder.__SetImageRuntimeVersion ("v4.0.30319", 0x20000);
190                                         break;
191                                 case RuntimeVersion.v2:
192                                         Builder.__SetImageRuntimeVersion ("v2.0.50727", 0x20000);
193                                         break;
194                                 case RuntimeVersion.v1:
195                                         // Compiler does not do any checks whether the produced metadata
196                                         // are valid in the context of 1.0 stream version
197                                         Builder.__SetImageRuntimeVersion ("v1.1.4322", 0x10000);
198                                         break;
199                                 default:
200                                         throw new NotImplementedException ();
201                                 }
202                         }
203
204                         builder_extra = new AssemblyBuilderIKVM (Builder, Compiler);
205
206                         base.Emit ();
207                 }
208
209                 public Module IncludeModule (RawModule moduleFile)
210                 {
211                         return Builder.__AddModule (moduleFile);
212                 }
213
214                 protected override void SaveModule (PortableExecutableKinds pekind, ImageFileMachine machine)
215                 {
216                         module.Builder.__Save (pekind, machine);
217                 }
218         }
219
220         class StaticLoader : AssemblyReferencesLoader<Assembly>, IDisposable
221         {
222                 readonly StaticImporter importer;
223                 readonly Universe domain;
224                 Assembly corlib;
225                 List<Tuple<AssemblyName, string, Assembly>> loaded_names;
226                 static readonly Dictionary<string, string[]> sdk_directory;
227
228                 static StaticLoader ()
229                 {
230                         sdk_directory = new Dictionary<string, string[]> ();
231                         sdk_directory.Add ("2", new string[] { "2.0", "net_2_0", "v2.0.50727" });
232                         sdk_directory.Add ("4", new string[] { "4.0", "net_4_0", "v4.0.30319" });
233                         sdk_directory.Add ("4.5", new string[] { "4.5", "net_4_5", "v4.0.30319" });
234                 }
235
236                 public StaticLoader (StaticImporter importer, CompilerContext compiler)
237                         : base (compiler)
238                 {
239                         this.importer = importer;
240                         domain = new Universe (UniverseOptions.MetadataOnly | UniverseOptions.ResolveMissingMembers);
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 (var stream = new FileStream (file, FileMode.Open, FileAccess.Read, FileShare.Read)) {
420                                                 using (RawModule module = domain.OpenRawModule (stream, file)) {
421                                                         if (!module.IsManifestModule) {
422                                                                 Error_AssemblyIsModule (fileName);
423                                                                 return null;
424                                                         }
425
426                                                         //
427                                                         // check whether the assembly can be actually imported without
428                                                         // collision
429                                                         //
430                                                         var an = module.GetAssemblyName ();
431                                                         foreach (var entry in loaded_names) {
432                                                                 var loaded_name = entry.Item1;
433                                                                 if (an.Name != loaded_name.Name)
434                                                                         continue;
435
436                                                                 if (module.ModuleVersionId == entry.Item3.ManifestModule.ModuleVersionId)
437                                                                         return entry.Item3;
438                                                         
439                                                                 if (((an.Flags | loaded_name.Flags) & AssemblyNameFlags.PublicKey) == 0) {
440                                                                         compiler.Report.SymbolRelatedToPreviousError (entry.Item2);
441                                                                         compiler.Report.SymbolRelatedToPreviousError (fileName);
442                                                                         compiler.Report.Error (1704,
443                                                                                 "An assembly with the same name `{0}' has already been imported. Consider removing one of the references or sign the assembly",
444                                                                                 an.Name);
445                                                                         return null;
446                                                                 }
447
448                                                                 if ((an.Flags & AssemblyNameFlags.PublicKey) == (loaded_name.Flags & AssemblyNameFlags.PublicKey) && an.Version.Equals (loaded_name.Version)) {
449                                                                         compiler.Report.SymbolRelatedToPreviousError (entry.Item2);
450                                                                         compiler.Report.SymbolRelatedToPreviousError (fileName);
451                                                                         compiler.Report.Error (1703,
452                                                                                 "An assembly with the same identity `{0}' has already been imported. Consider removing one of the references",
453                                                                                 an.FullName);
454                                                                         return null;
455                                                                 }
456                                                         }
457
458                                                         if (compiler.Settings.DebugFlags > 0)
459                                                                 Console.WriteLine ("Loading assembly `{0}'", fileName);
460
461                                                         var assembly = domain.LoadAssembly (module);
462                                                         if (assembly != null)
463                                                                 loaded_names.Add (Tuple.Create (an, fileName, assembly));
464
465                                                         return assembly;
466                                                 }
467                                         }
468                                 } catch (Exception e) {
469                                         if (compiler.Settings.DebugFlags > 0)
470                                                 Console.WriteLine ("Exception during loading: {0}'", e.ToString ());
471
472                                         if (!isImplicitReference)
473                                                 Error_FileCorrupted (file);
474
475                                         return null;
476                                 }
477                         }
478
479                         if (!isImplicitReference)
480                                 Error_FileNotFound (fileName);
481
482                         return null;
483                 }
484
485                 public RawModule LoadModuleFile (string moduleName)
486                 {
487                         foreach (var path in paths) {
488                                 var file = Path.Combine (path, moduleName);
489                                 if (!File.Exists (file)) {
490                                         if (moduleName.EndsWith (".netmodule", StringComparison.Ordinal))
491                                                 continue;
492
493                                         file += ".netmodule";
494                                         if (!File.Exists (file))
495                                                 continue;
496                                 }
497
498                                 try {
499                                         return domain.OpenRawModule (file);
500                                 } catch {
501                                         Error_FileCorrupted (file);
502                                         return null;
503                                 }
504                         }
505
506                         Error_FileNotFound (moduleName);
507                         return null;                            
508                 }
509
510                 public override void LoadReferences (ModuleContainer module)
511                 {
512                         List<Tuple<RootNamespace, Assembly>> loaded;
513                         base.LoadReferencesCore (module, out corlib, out loaded);
514
515                         compiler.TimeReporter.Start (TimeReporter.TimerType.ReferencesImporting);
516
517                         if (corlib == null) {
518                                 // System.Object was not found in any referenced assembly, use compiled assembly as corlib
519                                 corlib = module.DeclaringAssembly.Builder;
520                         } else {
521                                 importer.InitializeBuiltinTypes (compiler.BuiltinTypes, corlib);
522                                 importer.ImportAssembly (corlib, module.GlobalRootNamespace);
523                         }
524
525                         foreach (var entry in loaded) {
526                                 importer.ImportAssembly (entry.Item2, entry.Item1);
527                         }
528
529                         compiler.TimeReporter.Stop (TimeReporter.TimerType.ReferencesImporting);
530                 }
531
532                 public void LoadModules (AssemblyDefinitionStatic assembly, RootNamespace targetNamespace)
533                 {
534                         foreach (var moduleName in compiler.Settings.Modules) {
535                                 var m = LoadModuleFile (moduleName);
536                                 if (m == null)
537                                         continue;
538
539                                 if (m.IsManifestModule) {
540                                         Error_ModuleIsAssembly (moduleName);
541                                         continue;
542                                 }
543
544                                 var md = importer.ImportModule (assembly.IncludeModule (m), targetNamespace);
545                                 assembly.AddModule (md);
546                         }
547                 }
548         }
549
550         class AssemblyBuilderIKVM : AssemblyBuilderExtension
551         {
552                 readonly AssemblyBuilder builder;
553
554                 public AssemblyBuilderIKVM (AssemblyBuilder builder, CompilerContext ctx)
555                         : base (ctx)
556                 {
557                         this.builder = builder;
558                 }
559
560                 public override void AddTypeForwarder (TypeSpec type, Location loc)
561                 {
562                         builder.__AddTypeForwarder (type.GetMetaInfo ());
563                 }
564
565                 public override void DefineWin32IconResource (string fileName)
566                 {
567                         builder.__DefineIconResource (File.ReadAllBytes (fileName));
568                 }
569
570                 public override void SetAlgorithmId (uint value, Location loc)
571                 {
572                         builder.__SetAssemblyAlgorithmId ((AssemblyHashAlgorithm) value);
573                 }
574
575                 public override void SetCulture (string culture, Location loc)
576                 {
577                         builder.__SetAssemblyCulture (culture);
578                 }
579
580                 public override void SetFlags (uint flags, Location loc)
581                 {
582                         builder.__AssemblyFlags = (AssemblyNameFlags) flags;
583                 }
584
585                 public override void SetVersion (Version version, Location loc)
586                 {
587                         builder.__SetAssemblyVersion (version);
588                 }
589         }
590 }