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