Merge pull request #217 from QuickJack/master
[mono.git] / mcs / mcs / reflection.cs
1 //
2 // reflection.cs: System.Reflection and System.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 System.Reflection;
15 using System.IO;
16 using System.Runtime.CompilerServices;
17 using System.Reflection.Emit;
18 using System.Security;
19
20 namespace Mono.CSharp
21 {
22 #if STATIC
23         public class ReflectionImporter
24         {
25                 public ReflectionImporter (ModuleContainer module, 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 ImportedModuleDefinition ImportModule (Module module, RootNamespace targetNamespace)
36                 {
37                         throw new NotSupportedException ();
38                 }
39
40                 public TypeSpec ImportType (Type type)
41                 {
42                         throw new NotSupportedException ();
43                 }
44         }
45 #else
46         public sealed class ReflectionImporter : MetadataImporter
47         {
48                 public ReflectionImporter (ModuleContainer module, BuiltinTypes builtin)
49                         : base (module)
50                 {
51                         Initialize (builtin);
52                 }
53
54                 public override void AddCompiledType (TypeBuilder builder, TypeSpec spec)
55                 {
56                 }
57
58                 protected override MemberKind DetermineKindFromBaseType (Type baseType)
59                 {
60                         if (baseType == typeof (ValueType))
61                                 return MemberKind.Struct;
62
63                         if (baseType == typeof (System.Enum))
64                                 return MemberKind.Enum;
65
66                         if (baseType == typeof (MulticastDelegate))
67                                 return MemberKind.Delegate;
68
69                         return MemberKind.Class;
70                 }
71
72                 protected override bool HasVolatileModifier (Type[] modifiers)
73                 {
74                         foreach (var t in modifiers) {
75                                 if (t == typeof (IsVolatile))
76                                         return true;
77                         }
78
79                         return false;
80                 }
81
82                 public void ImportAssembly (Assembly assembly, RootNamespace targetNamespace)
83                 {
84                         // It can be used more than once when importing same assembly
85                         // into 2 or more global aliases
86                         var definition = GetAssemblyDefinition (assembly);
87
88                         //
89                         // This part tries to simulate loading of top-level
90                         // types only, any missing dependencies are ignores here.
91                         // Full error report is reported later when the type is
92                         // actually used
93                         //
94                         Type[] all_types;
95                         try {
96                                 all_types = assembly.GetTypes ();
97                         } catch (ReflectionTypeLoadException e) {
98                                 all_types = e.Types;
99                         }
100
101                         ImportTypes (all_types, targetNamespace, definition.HasExtensionMethod);
102                 }
103
104                 public ImportedModuleDefinition ImportModule (Module module, RootNamespace targetNamespace)
105                 {
106                         var module_definition = new ImportedModuleDefinition (module);
107                         module_definition.ReadAttributes ();
108
109                         Type[] all_types;
110                         try {
111                                 all_types = module.GetTypes ();
112                         } catch (ReflectionTypeLoadException e) {
113                                 all_types = e.Types;
114                         }
115
116                         ImportTypes (all_types, targetNamespace, false);
117
118                         return module_definition;
119                 }
120
121                 void Initialize (BuiltinTypes builtin)
122                 {
123                         //
124                         // Setup mapping for build-in types to avoid duplication of their definition
125                         //
126                         compiled_types.Add (typeof (object), builtin.Object);
127                         compiled_types.Add (typeof (System.ValueType), builtin.ValueType);
128                         compiled_types.Add (typeof (System.Attribute), builtin.Attribute);
129
130                         compiled_types.Add (typeof (int), builtin.Int);
131                         compiled_types.Add (typeof (long), builtin.Long);
132                         compiled_types.Add (typeof (uint), builtin.UInt);
133                         compiled_types.Add (typeof (ulong), builtin.ULong);
134                         compiled_types.Add (typeof (byte), builtin.Byte);
135                         compiled_types.Add (typeof (sbyte), builtin.SByte);
136                         compiled_types.Add (typeof (short), builtin.Short);
137                         compiled_types.Add (typeof (ushort), builtin.UShort);
138
139                         compiled_types.Add (typeof (System.Collections.IEnumerator), builtin.IEnumerator);
140                         compiled_types.Add (typeof (System.Collections.IEnumerable), builtin.IEnumerable);
141                         compiled_types.Add (typeof (System.IDisposable), builtin.IDisposable);
142
143                         compiled_types.Add (typeof (char), builtin.Char);
144                         compiled_types.Add (typeof (string), builtin.String);
145                         compiled_types.Add (typeof (float), builtin.Float);
146                         compiled_types.Add (typeof (double), builtin.Double);
147                         compiled_types.Add (typeof (decimal), builtin.Decimal);
148                         compiled_types.Add (typeof (bool), builtin.Bool);
149                         compiled_types.Add (typeof (System.IntPtr), builtin.IntPtr);
150                         compiled_types.Add (typeof (System.UIntPtr), builtin.UIntPtr);
151
152                         compiled_types.Add (typeof (System.MulticastDelegate), builtin.MulticastDelegate);
153                         compiled_types.Add (typeof (System.Delegate), builtin.Delegate);
154                         compiled_types.Add (typeof (System.Enum), builtin.Enum);
155                         compiled_types.Add (typeof (System.Array), builtin.Array);
156                         compiled_types.Add (typeof (void), builtin.Void);
157                         compiled_types.Add (typeof (System.Type), builtin.Type);
158                         compiled_types.Add (typeof (System.Exception), builtin.Exception);
159                         compiled_types.Add (typeof (System.RuntimeFieldHandle), builtin.RuntimeFieldHandle);
160                         compiled_types.Add (typeof (System.RuntimeTypeHandle), builtin.RuntimeTypeHandle);
161                 }
162         }
163
164         [System.Runtime.InteropServices.StructLayout (System.Runtime.InteropServices.LayoutKind.Explicit)]
165         struct SingleConverter
166         {
167                 [System.Runtime.InteropServices.FieldOffset (0)]
168                 int i;
169                 [System.Runtime.InteropServices.FieldOffset (0)]
170                 float f;
171
172                 public static int SingleToInt32Bits (float v)
173                 {
174                         SingleConverter c = new SingleConverter ();
175                         c.f = v;
176                         return c.i;
177                 }
178         }
179
180 #endif
181
182         public class AssemblyDefinitionDynamic : AssemblyDefinition
183         {
184                 //
185                 // In-memory only assembly container
186                 //
187                 public AssemblyDefinitionDynamic (ModuleContainer module, string name)
188                         : base (module, name)
189                 {
190                 }
191
192                 //
193                 // Assembly container with file output
194                 //
195                 public AssemblyDefinitionDynamic (ModuleContainer module, string name, string fileName)
196                         : base (module, name, fileName)
197                 {
198                 }
199
200                 public Module IncludeModule (string moduleFile)
201                 {
202                         return builder_extra.AddModule (moduleFile);
203                 }
204
205 #if !STATIC
206                 public override ModuleBuilder CreateModuleBuilder ()
207                 {
208                         if (file_name == null)
209                                 return Builder.DefineDynamicModule (Name, false);
210
211                         return base.CreateModuleBuilder ();
212                 }
213 #endif
214                 //
215                 // Initializes the code generator
216                 //
217                 public bool Create (AppDomain domain, AssemblyBuilderAccess access)
218                 {
219 #if STATIC
220                         throw new NotSupportedException ();
221 #else
222                         ResolveAssemblySecurityAttributes ();
223                         var an = CreateAssemblyName ();
224
225                         Builder = file_name == null ?
226                                 domain.DefineDynamicAssembly (an, access) :
227                                 domain.DefineDynamicAssembly (an, access, Dirname (file_name));
228
229                         module.Create (this, CreateModuleBuilder ());
230                         builder_extra = new AssemblyBuilderMonoSpecific (Builder, Compiler);
231                         return true;
232 #endif
233                 }
234
235                 static string Dirname (string name)
236                 {
237                         int pos = name.LastIndexOf ('/');
238
239                         if (pos != -1)
240                                 return name.Substring (0, pos);
241
242                         pos = name.LastIndexOf ('\\');
243                         if (pos != -1)
244                                 return name.Substring (0, pos);
245
246                         return ".";
247                 }
248
249 #if !STATIC
250                 protected override void SaveModule (PortableExecutableKinds pekind, ImageFileMachine machine)
251                 {
252                         try {
253                                 var module_only = typeof (AssemblyBuilder).GetProperty ("IsModuleOnly", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
254                                 var set_module_only = module_only.GetSetMethod (true);
255
256                                 set_module_only.Invoke (Builder, new object[] { true });
257                         } catch {
258                                 base.SaveModule (pekind, machine);
259                         }
260
261                         Builder.Save (file_name, pekind, machine);
262                 }
263 #endif
264         }
265
266         //
267         // Extension to System.Reflection.Emit.AssemblyBuilder to have fully compatible
268         // compiler
269         //
270         class AssemblyBuilderMonoSpecific : AssemblyBuilderExtension
271         {
272                 static MethodInfo adder_method;
273                 static MethodInfo add_permission;
274                 static MethodInfo add_type_forwarder;
275                 static MethodInfo win32_icon_define;
276                 static FieldInfo assembly_version;
277                 static FieldInfo assembly_algorithm;
278                 static FieldInfo assembly_culture;
279                 static FieldInfo assembly_flags;
280
281                 AssemblyBuilder builder;
282
283                 public AssemblyBuilderMonoSpecific (AssemblyBuilder ab, CompilerContext ctx)
284                         : base (ctx)
285                 {
286                         this.builder = ab;
287                 }
288
289                 public override Module AddModule (string module)
290                 {
291                         try {
292                                 if (adder_method == null)
293                                         adder_method = typeof (AssemblyBuilder).GetMethod ("AddModule", BindingFlags.Instance | BindingFlags.NonPublic);
294
295                                 return (Module) adder_method.Invoke (builder, new object[] { module });
296                         } catch {
297                                 return base.AddModule (module);
298                         }
299                 }
300
301                 public override void AddPermissionRequests (PermissionSet[] permissions)
302                 {
303                         try {
304                                 if (add_permission == null)
305                                         add_permission = typeof (AssemblyBuilder).GetMethod ("AddPermissionRequests", BindingFlags.Instance | BindingFlags.NonPublic);
306
307                                 add_permission.Invoke (builder, permissions);
308                         } catch {
309                                 base.AddPermissionRequests (permissions);
310                         }
311                 }
312
313                 public override void AddTypeForwarder (TypeSpec type, Location loc)
314                 {
315                         try {
316                                 if (add_type_forwarder == null) {
317                                         add_type_forwarder = typeof (AssemblyBuilder).GetMethod ("AddTypeForwarder", BindingFlags.NonPublic | BindingFlags.Instance);
318                                 }
319
320                                 add_type_forwarder.Invoke (builder, new object[] { type.GetMetaInfo () });
321                         } catch {
322                                 base.AddTypeForwarder (type, loc);
323                         }
324                 }
325
326                 public override void DefineWin32IconResource (string fileName)
327                 {
328                         try {
329                                 if (win32_icon_define == null)
330                                         win32_icon_define = typeof (AssemblyBuilder).GetMethod ("DefineIconResource", BindingFlags.Instance | BindingFlags.NonPublic);
331
332                                 win32_icon_define.Invoke (builder, new object[] { fileName });
333                         } catch {
334                                 base.DefineWin32IconResource (fileName);
335                         }
336                 }
337
338                 public override void SetAlgorithmId (uint value, Location loc)
339                 {
340                         try {
341                                 if (assembly_algorithm == null)
342                                         assembly_algorithm = typeof (AssemblyBuilder).GetField ("algid", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.SetField);
343
344                                 assembly_algorithm.SetValue (builder, value);
345                         } catch {
346                                 base.SetAlgorithmId (value, loc);
347                         }
348                 }
349
350                 public override void SetCulture (string culture, Location loc)
351                 {
352                         try {
353                                 if (assembly_culture == null)
354                                         assembly_culture = typeof (AssemblyBuilder).GetField ("culture", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.SetField);
355
356                                 assembly_culture.SetValue (builder, culture);
357                         } catch {
358                                 base.SetCulture (culture, loc);
359                         }
360                 }
361
362                 public override void SetFlags (uint flags, Location loc)
363                 {
364                         try {
365                                 if (assembly_flags == null)
366                                         assembly_flags = typeof (AssemblyBuilder).GetField ("flags", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.SetField);
367
368                                 assembly_flags.SetValue (builder, flags);
369                         } catch {
370                                 base.SetFlags (flags, loc);
371                         }
372                 }
373
374                 public override void SetVersion (Version version, Location loc)
375                 {
376                         try {
377                                 if (assembly_version == null)
378                                         assembly_version = typeof (AssemblyBuilder).GetField ("version", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.SetField);
379
380                                 assembly_version.SetValue (builder, version.ToString (4));
381                         } catch {
382                                 base.SetVersion (version, loc);
383                         }
384                 }
385         }
386
387         //
388         // Reflection based references loader
389         //
390         class DynamicLoader : AssemblyReferencesLoader<Assembly>
391         {
392                 readonly ReflectionImporter importer;
393
394                 public DynamicLoader (ReflectionImporter importer, CompilerContext compiler)
395                         : base (compiler)
396                 {
397                         paths.Add (GetSystemDir ());
398
399                         this.importer = importer;
400                 }
401
402                 public ReflectionImporter Importer {
403                         get {
404                                 return importer;
405                         }
406                 }
407
408                 protected override string[] GetDefaultReferences ()
409                 {
410                         //
411                         // For now the "default config" is harcoded into the compiler
412                         // we can move this outside later
413                         //
414                         var default_references = new List<string> (8);
415
416                         default_references.Add ("System");
417                         default_references.Add ("System.Xml");
418 #if NET_2_1
419                         default_references.Add ("System.Net");
420                         default_references.Add ("System.Windows");
421                         default_references.Add ("System.Windows.Browser");
422 #endif
423
424                         if (compiler.Settings.Version > LanguageVersion.ISO_2)
425                                 default_references.Add ("System.Core");
426                         if (compiler.Settings.Version > LanguageVersion.V_3)
427                                 default_references.Add ("Microsoft.CSharp");
428
429                         return default_references.ToArray ();
430                 }
431
432                 //
433                 // Returns the directory where the system assemblies are installed
434                 //
435                 static string GetSystemDir ()
436                 {
437                         return Path.GetDirectoryName (typeof (object).Assembly.Location);
438                 }
439
440                 public override bool HasObjectType (Assembly assembly)
441                 {
442                         return assembly.GetType (compiler.BuiltinTypes.Object.FullName) != null;
443                 }
444
445                 public override Assembly LoadAssemblyFile (string assembly, bool isImplicitReference)
446                 {
447                         Assembly a = null;
448
449                         try {
450                                 try {
451                                         char[] path_chars = { '/', '\\' };
452
453                                         if (assembly.IndexOfAny (path_chars) != -1) {
454                                                 a = Assembly.LoadFrom (assembly);
455                                         } else {
456                                                 string ass = assembly;
457                                                 if (ass.EndsWith (".dll") || ass.EndsWith (".exe"))
458                                                         ass = assembly.Substring (0, assembly.Length - 4);
459                                                 a = Assembly.Load (ass);
460                                         }
461                                 } catch (FileNotFoundException) {
462                                         bool err = !isImplicitReference;
463                                         foreach (string dir in paths) {
464                                                 string full_path = Path.Combine (dir, assembly);
465                                                 if (!assembly.EndsWith (".dll") && !assembly.EndsWith (".exe"))
466                                                         full_path += ".dll";
467
468                                                 try {
469                                                         a = Assembly.LoadFrom (full_path);
470                                                         err = false;
471                                                         break;
472                                                 } catch (FileNotFoundException) {
473                                                 }
474                                         }
475
476                                         if (err) {
477                                                 Error_FileNotFound (assembly);
478                                                 return a;
479                                         }
480                                 }
481                         } catch (BadImageFormatException) {
482                                 Error_FileCorrupted (assembly);
483                         }
484
485                         return a;
486                 }
487
488                 Module LoadModuleFile (AssemblyDefinitionDynamic assembly, string module)
489                 {
490                         string total_log = "";
491
492                         try {
493                                 try {
494                                         return assembly.IncludeModule (module);
495                                 } catch (FileNotFoundException) {
496                                         bool err = true;
497                                         foreach (string dir in paths) {
498                                                 string full_path = Path.Combine (dir, module);
499                                                 if (!module.EndsWith (".netmodule"))
500                                                         full_path += ".netmodule";
501
502                                                 try {
503                                                         return assembly.IncludeModule (full_path);
504                                                 } catch (FileNotFoundException ff) {
505                                                         total_log += ff.FusionLog;
506                                                 }
507                                         }
508                                         if (err) {
509                                                 Error_FileNotFound (module);
510                                                 return null;
511                                         }
512                                 }
513                         } catch (BadImageFormatException) {
514                                 Error_FileCorrupted (module);
515                         }
516
517                         return null;
518                 }
519
520                 public void LoadModules (AssemblyDefinitionDynamic assembly, RootNamespace targetNamespace)
521                 {
522                         foreach (var moduleName in compiler.Settings.Modules) {
523                                 var m = LoadModuleFile (assembly, moduleName);
524                                 if (m == null)
525                                         continue;
526
527                                 var md = importer.ImportModule (m, targetNamespace);
528                                 assembly.AddModule (md);
529                         }
530                 }
531
532                 public override void LoadReferences (ModuleContainer module)
533                 {
534                         Assembly corlib;
535                         List<Tuple<RootNamespace, Assembly>> loaded;
536                         base.LoadReferencesCore (module, out corlib, out loaded);
537
538                         if (corlib == null)
539                                 return;
540
541                         importer.ImportAssembly (corlib, module.GlobalRootNamespace);
542                         foreach (var entry in loaded) {
543                                 importer.ImportAssembly (entry.Item2, entry.Item1);
544                         }
545                 }
546         }
547 }