2 // reflection.cs: System.Reflection and System.Reflection.Emit specific implementations
4 // Author: Marek Safar (marek.safar@gmail.com)
6 // Dual licensed under the terms of the MIT X11 or GNU GPL
8 // Copyright 2009-2010 Novell, Inc.
13 using System.Collections.Generic;
14 using System.Reflection;
16 using System.Runtime.CompilerServices;
17 using System.Reflection.Emit;
18 using System.Security;
23 public class ReflectionImporter
25 public ReflectionImporter (ModuleContainer module, BuiltinTypes builtin)
27 throw new NotSupportedException ();
30 public void ImportAssembly (Assembly assembly, RootNamespace targetNamespace)
32 throw new NotSupportedException ();
35 public ImportedModuleDefinition ImportModule (Module module, RootNamespace targetNamespace)
37 throw new NotSupportedException ();
40 public TypeSpec ImportType (Type type)
42 throw new NotSupportedException ();
46 public sealed class ReflectionImporter : MetadataImporter
48 public ReflectionImporter (ModuleContainer module, BuiltinTypes builtin)
54 public override void AddCompiledType (TypeBuilder builder, TypeSpec spec)
58 protected override MemberKind DetermineKindFromBaseType (Type baseType)
60 if (baseType == typeof (ValueType))
61 return MemberKind.Struct;
63 if (baseType == typeof (System.Enum))
64 return MemberKind.Enum;
66 if (baseType == typeof (MulticastDelegate))
67 return MemberKind.Delegate;
69 return MemberKind.Class;
72 protected override bool HasVolatileModifier (Type[] modifiers)
74 foreach (var t in modifiers) {
75 if (t == typeof (IsVolatile))
82 public void ImportAssembly (Assembly assembly, RootNamespace targetNamespace)
84 // It can be used more than once when importing same assembly
85 // into 2 or more global aliases
86 var definition = GetAssemblyDefinition (assembly);
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
96 all_types = assembly.GetTypes ();
97 } catch (ReflectionTypeLoadException e) {
101 ImportTypes (all_types, targetNamespace, definition.HasExtensionMethod);
104 public ImportedModuleDefinition ImportModule (Module module, RootNamespace targetNamespace)
106 var module_definition = new ImportedModuleDefinition (module);
107 module_definition.ReadAttributes ();
111 all_types = module.GetTypes ();
112 } catch (ReflectionTypeLoadException e) {
116 ImportTypes (all_types, targetNamespace, false);
118 return module_definition;
121 void Initialize (BuiltinTypes builtin)
124 // Setup mapping for build-in types to avoid duplication of their definition
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);
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);
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);
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);
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);
164 [System.Runtime.InteropServices.StructLayout (System.Runtime.InteropServices.LayoutKind.Explicit)]
165 struct SingleConverter
167 [System.Runtime.InteropServices.FieldOffset (0)]
169 [System.Runtime.InteropServices.FieldOffset (0)]
172 public static int SingleToInt32Bits (float v)
174 SingleConverter c = new SingleConverter ();
182 public class AssemblyDefinitionDynamic : AssemblyDefinition
185 // In-memory only assembly container
187 public AssemblyDefinitionDynamic (ModuleContainer module, string name)
188 : base (module, name)
193 // Assembly container with file output
195 public AssemblyDefinitionDynamic (ModuleContainer module, string name, string fileName)
196 : base (module, name, fileName)
200 public Module IncludeModule (string moduleFile)
202 return builder_extra.AddModule (moduleFile);
206 public override ModuleBuilder CreateModuleBuilder ()
208 if (file_name == null)
209 return Builder.DefineDynamicModule (Name, false);
211 return base.CreateModuleBuilder ();
215 // Initializes the code generator
217 public bool Create (AppDomain domain, AssemblyBuilderAccess access)
220 throw new NotSupportedException ();
222 ResolveAssemblySecurityAttributes ();
223 var an = CreateAssemblyName ();
225 Builder = file_name == null ?
226 domain.DefineDynamicAssembly (an, access) :
227 domain.DefineDynamicAssembly (an, access, Dirname (file_name));
229 module.Create (this, CreateModuleBuilder ());
230 builder_extra = new AssemblyBuilderMonoSpecific (Builder, Compiler);
235 static string Dirname (string name)
237 int pos = name.LastIndexOf ('/');
240 return name.Substring (0, pos);
242 pos = name.LastIndexOf ('\\');
244 return name.Substring (0, pos);
250 protected override void SaveModule (PortableExecutableKinds pekind, ImageFileMachine machine)
253 var module_only = typeof (AssemblyBuilder).GetProperty ("IsModuleOnly", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
254 var set_module_only = module_only.GetSetMethod (true);
256 set_module_only.Invoke (Builder, new object[] { true });
258 base.SaveModule (pekind, machine);
261 Builder.Save (file_name, pekind, machine);
267 // Extension to System.Reflection.Emit.AssemblyBuilder to have fully compatible
270 class AssemblyBuilderMonoSpecific : AssemblyBuilderExtension
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;
281 AssemblyBuilder builder;
283 public AssemblyBuilderMonoSpecific (AssemblyBuilder ab, CompilerContext ctx)
289 public override Module AddModule (string module)
292 if (adder_method == null)
293 adder_method = typeof (AssemblyBuilder).GetMethod ("AddModule", BindingFlags.Instance | BindingFlags.NonPublic);
295 return (Module) adder_method.Invoke (builder, new object[] { module });
297 return base.AddModule (module);
301 public override void AddPermissionRequests (PermissionSet[] permissions)
304 if (add_permission == null)
305 add_permission = typeof (AssemblyBuilder).GetMethod ("AddPermissionRequests", BindingFlags.Instance | BindingFlags.NonPublic);
307 add_permission.Invoke (builder, permissions);
309 base.AddPermissionRequests (permissions);
313 public override void AddTypeForwarder (TypeSpec type, Location loc)
316 if (add_type_forwarder == null) {
317 add_type_forwarder = typeof (AssemblyBuilder).GetMethod ("AddTypeForwarder", BindingFlags.NonPublic | BindingFlags.Instance);
320 add_type_forwarder.Invoke (builder, new object[] { type.GetMetaInfo () });
322 base.AddTypeForwarder (type, loc);
326 public override void DefineWin32IconResource (string fileName)
329 if (win32_icon_define == null)
330 win32_icon_define = typeof (AssemblyBuilder).GetMethod ("DefineIconResource", BindingFlags.Instance | BindingFlags.NonPublic);
332 win32_icon_define.Invoke (builder, new object[] { fileName });
334 base.DefineWin32IconResource (fileName);
338 public override void SetAlgorithmId (uint value, Location loc)
341 if (assembly_algorithm == null)
342 assembly_algorithm = typeof (AssemblyBuilder).GetField ("algid", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.SetField);
344 assembly_algorithm.SetValue (builder, value);
346 base.SetAlgorithmId (value, loc);
350 public override void SetCulture (string culture, Location loc)
353 if (assembly_culture == null)
354 assembly_culture = typeof (AssemblyBuilder).GetField ("culture", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.SetField);
356 assembly_culture.SetValue (builder, culture);
358 base.SetCulture (culture, loc);
362 public override void SetFlags (uint flags, Location loc)
365 if (assembly_flags == null)
366 assembly_flags = typeof (AssemblyBuilder).GetField ("flags", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.SetField);
368 assembly_flags.SetValue (builder, flags);
370 base.SetFlags (flags, loc);
374 public override void SetVersion (Version version, Location loc)
377 if (assembly_version == null)
378 assembly_version = typeof (AssemblyBuilder).GetField ("version", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.SetField);
380 assembly_version.SetValue (builder, version.ToString (4));
382 base.SetVersion (version, loc);
388 // Reflection based references loader
390 class DynamicLoader : AssemblyReferencesLoader<Assembly>
392 readonly ReflectionImporter importer;
394 public DynamicLoader (ReflectionImporter importer, CompilerContext compiler)
397 paths.Add (GetSystemDir ());
399 this.importer = importer;
402 public ReflectionImporter Importer {
408 protected override string[] GetDefaultReferences ()
411 // For now the "default config" is harcoded into the compiler
412 // we can move this outside later
414 var default_references = new List<string> (8);
416 default_references.Add ("System");
417 default_references.Add ("System.Xml");
419 default_references.Add ("System.Net");
420 default_references.Add ("System.Windows");
421 default_references.Add ("System.Windows.Browser");
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");
429 return default_references.ToArray ();
433 // Returns the directory where the system assemblies are installed
435 static string GetSystemDir ()
437 return Path.GetDirectoryName (typeof (object).Assembly.Location);
440 public override bool HasObjectType (Assembly assembly)
442 return assembly.GetType (compiler.BuiltinTypes.Object.FullName) != null;
445 public override Assembly LoadAssemblyFile (string assembly, bool isImplicitReference)
451 char[] path_chars = { '/', '\\' };
453 if (assembly.IndexOfAny (path_chars) != -1) {
454 a = Assembly.LoadFrom (assembly);
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);
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"))
469 a = Assembly.LoadFrom (full_path);
472 } catch (FileNotFoundException) {
477 Error_FileNotFound (assembly);
481 } catch (BadImageFormatException) {
482 Error_FileCorrupted (assembly);
488 Module LoadModuleFile (AssemblyDefinitionDynamic assembly, string module)
490 string total_log = "";
494 return assembly.IncludeModule (module);
495 } catch (FileNotFoundException) {
497 foreach (string dir in paths) {
498 string full_path = Path.Combine (dir, module);
499 if (!module.EndsWith (".netmodule"))
500 full_path += ".netmodule";
503 return assembly.IncludeModule (full_path);
504 } catch (FileNotFoundException ff) {
505 total_log += ff.FusionLog;
509 Error_FileNotFound (module);
513 } catch (BadImageFormatException) {
514 Error_FileCorrupted (module);
520 public void LoadModules (AssemblyDefinitionDynamic assembly, RootNamespace targetNamespace)
522 foreach (var moduleName in compiler.Settings.Modules) {
523 var m = LoadModuleFile (assembly, moduleName);
527 var md = importer.ImportModule (m, targetNamespace);
528 assembly.AddModule (md);
532 public override void LoadReferences (ModuleContainer module)
535 List<Tuple<RootNamespace, Assembly>> loaded;
536 base.LoadReferencesCore (module, out corlib, out loaded);
541 importer.ImportAssembly (corlib, module.GlobalRootNamespace);
542 foreach (var entry in loaded) {
543 importer.ImportAssembly (entry.Item2, entry.Item1);