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