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)
51 IgnoreCompilerGeneratedField = false;
56 public override void AddCompiledType (TypeBuilder builder, TypeSpec spec)
60 protected override MemberKind DetermineKindFromBaseType (Type baseType)
62 if (baseType == typeof (ValueType))
63 return MemberKind.Struct;
65 if (baseType == typeof (System.Enum))
66 return MemberKind.Enum;
68 if (baseType == typeof (MulticastDelegate))
69 return MemberKind.Delegate;
71 return MemberKind.Class;
74 protected override bool HasVolatileModifier (Type[] modifiers)
76 foreach (var t in modifiers) {
77 if (t == typeof (IsVolatile))
84 public void ImportAssembly (Assembly assembly, RootNamespace targetNamespace)
86 // It can be used more than once when importing same assembly
87 // into 2 or more global aliases
88 GetAssemblyDefinition (assembly);
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
98 all_types = assembly.GetTypes ();
99 } catch (ReflectionTypeLoadException e) {
103 ImportTypes (all_types, targetNamespace, true);
106 public ImportedModuleDefinition ImportModule (Module module, RootNamespace targetNamespace)
108 var module_definition = new ImportedModuleDefinition (module);
109 module_definition.ReadAttributes ();
113 all_types = module.GetTypes ();
114 } catch (ReflectionTypeLoadException e) {
118 ImportTypes (all_types, targetNamespace, false);
120 return module_definition;
123 void Initialize (BuiltinTypes builtin)
126 // Setup mapping for build-in types to avoid duplication of their definition
128 compiled_types.Add (typeof (object), builtin.Object);
129 compiled_types.Add (typeof (System.ValueType), builtin.ValueType);
130 compiled_types.Add (typeof (System.Attribute), builtin.Attribute);
132 compiled_types.Add (typeof (int), builtin.Int);
133 compiled_types.Add (typeof (long), builtin.Long);
134 compiled_types.Add (typeof (uint), builtin.UInt);
135 compiled_types.Add (typeof (ulong), builtin.ULong);
136 compiled_types.Add (typeof (byte), builtin.Byte);
137 compiled_types.Add (typeof (sbyte), builtin.SByte);
138 compiled_types.Add (typeof (short), builtin.Short);
139 compiled_types.Add (typeof (ushort), builtin.UShort);
141 compiled_types.Add (typeof (System.Collections.IEnumerator), builtin.IEnumerator);
142 compiled_types.Add (typeof (System.Collections.IEnumerable), builtin.IEnumerable);
143 compiled_types.Add (typeof (System.IDisposable), builtin.IDisposable);
145 compiled_types.Add (typeof (char), builtin.Char);
146 compiled_types.Add (typeof (string), builtin.String);
147 compiled_types.Add (typeof (float), builtin.Float);
148 compiled_types.Add (typeof (double), builtin.Double);
149 compiled_types.Add (typeof (decimal), builtin.Decimal);
150 compiled_types.Add (typeof (bool), builtin.Bool);
151 compiled_types.Add (typeof (System.IntPtr), builtin.IntPtr);
152 compiled_types.Add (typeof (System.UIntPtr), builtin.UIntPtr);
154 compiled_types.Add (typeof (System.MulticastDelegate), builtin.MulticastDelegate);
155 compiled_types.Add (typeof (System.Delegate), builtin.Delegate);
156 compiled_types.Add (typeof (System.Enum), builtin.Enum);
157 compiled_types.Add (typeof (System.Array), builtin.Array);
158 compiled_types.Add (typeof (void), builtin.Void);
159 compiled_types.Add (typeof (System.Type), builtin.Type);
160 compiled_types.Add (typeof (System.Exception), builtin.Exception);
161 compiled_types.Add (typeof (System.RuntimeFieldHandle), builtin.RuntimeFieldHandle);
162 compiled_types.Add (typeof (System.RuntimeTypeHandle), builtin.RuntimeTypeHandle);
166 [System.Runtime.InteropServices.StructLayout (System.Runtime.InteropServices.LayoutKind.Explicit)]
167 struct SingleConverter
169 [System.Runtime.InteropServices.FieldOffset (0)]
172 #pragma warning disable 414
173 [System.Runtime.InteropServices.FieldOffset (0)]
175 #pragma warning restore 414
177 public static int SingleToInt32Bits (float v)
179 SingleConverter c = new SingleConverter ();
187 public class AssemblyDefinitionDynamic : AssemblyDefinition
190 // In-memory only assembly container
192 public AssemblyDefinitionDynamic (ModuleContainer module, string name)
193 : base (module, name)
198 // Assembly container with file output
200 public AssemblyDefinitionDynamic (ModuleContainer module, string name, string fileName)
201 : base (module, name, fileName)
205 public Module IncludeModule (string moduleFile)
207 return builder_extra.AddModule (moduleFile);
211 public override ModuleBuilder CreateModuleBuilder ()
213 if (file_name == null)
214 return Builder.DefineDynamicModule (Name, false);
216 return base.CreateModuleBuilder ();
220 // Initializes the code generator
222 public bool Create (AppDomain domain, AssemblyBuilderAccess access)
224 #if STATIC || FULL_AOT_RUNTIME
225 throw new NotSupportedException ();
227 ResolveAssemblySecurityAttributes ();
228 var an = CreateAssemblyName ();
230 Builder = file_name == null ?
231 domain.DefineDynamicAssembly (an, access) :
232 domain.DefineDynamicAssembly (an, access, Dirname (file_name));
234 module.Create (this, CreateModuleBuilder ());
235 builder_extra = new AssemblyBuilderMonoSpecific (Builder, Compiler);
240 static string Dirname (string name)
242 int pos = name.LastIndexOf ('/');
245 return name.Substring (0, pos);
247 pos = name.LastIndexOf ('\\');
249 return name.Substring (0, pos);
255 protected override void SaveModule (PortableExecutableKinds pekind, ImageFileMachine machine)
258 var module_only = typeof (AssemblyBuilder).GetProperty ("IsModuleOnly", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
259 var set_module_only = module_only.GetSetMethod (true);
261 set_module_only.Invoke (Builder, new object[] { true });
263 base.SaveModule (pekind, machine);
266 Builder.Save (file_name, pekind, machine);
272 // Extension to System.Reflection.Emit.AssemblyBuilder to have fully compatible
275 class AssemblyBuilderMonoSpecific : AssemblyBuilderExtension
277 static MethodInfo adder_method;
278 static MethodInfo add_permission;
279 static MethodInfo add_type_forwarder;
280 static MethodInfo win32_icon_define;
281 static FieldInfo assembly_version;
282 static FieldInfo assembly_algorithm;
283 static FieldInfo assembly_culture;
284 static FieldInfo assembly_flags;
286 AssemblyBuilder builder;
288 public AssemblyBuilderMonoSpecific (AssemblyBuilder ab, CompilerContext ctx)
294 public override Module AddModule (string module)
297 if (adder_method == null)
298 adder_method = typeof (AssemblyBuilder).GetMethod ("AddModule", BindingFlags.Instance | BindingFlags.NonPublic);
300 return (Module) adder_method.Invoke (builder, new object[] { module });
302 return base.AddModule (module);
306 public override void AddPermissionRequests (PermissionSet[] permissions)
309 if (add_permission == null)
310 add_permission = typeof (AssemblyBuilder).GetMethod ("AddPermissionRequests", BindingFlags.Instance | BindingFlags.NonPublic);
312 add_permission.Invoke (builder, permissions);
314 base.AddPermissionRequests (permissions);
318 public override void AddTypeForwarder (TypeSpec type, Location loc)
321 if (add_type_forwarder == null) {
322 add_type_forwarder = typeof (AssemblyBuilder).GetMethod ("AddTypeForwarder", BindingFlags.NonPublic | BindingFlags.Instance);
325 add_type_forwarder.Invoke (builder, new object[] { type.GetMetaInfo () });
327 base.AddTypeForwarder (type, loc);
331 public override void DefineWin32IconResource (string fileName)
334 if (win32_icon_define == null)
335 win32_icon_define = typeof (AssemblyBuilder).GetMethod ("DefineIconResource", BindingFlags.Instance | BindingFlags.NonPublic);
337 win32_icon_define.Invoke (builder, new object[] { fileName });
339 base.DefineWin32IconResource (fileName);
343 public override void SetAlgorithmId (uint value, Location loc)
346 if (assembly_algorithm == null)
347 assembly_algorithm = typeof (AssemblyBuilder).GetField ("algid", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.SetField);
349 assembly_algorithm.SetValue (builder, value);
351 base.SetAlgorithmId (value, loc);
355 public override void SetCulture (string culture, Location loc)
358 if (assembly_culture == null)
359 assembly_culture = typeof (AssemblyBuilder).GetField ("culture", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.SetField);
361 assembly_culture.SetValue (builder, culture);
363 base.SetCulture (culture, loc);
367 public override void SetFlags (uint flags, Location loc)
370 if (assembly_flags == null)
371 assembly_flags = typeof (AssemblyBuilder).GetField ("flags", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.SetField);
373 assembly_flags.SetValue (builder, flags);
375 base.SetFlags (flags, loc);
379 public override void SetVersion (Version version, Location loc)
382 if (assembly_version == null)
383 assembly_version = typeof (AssemblyBuilder).GetField ("version", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.SetField);
385 assembly_version.SetValue (builder, version.ToString (4));
387 base.SetVersion (version, loc);
393 // Reflection based references loader
395 class DynamicLoader : AssemblyReferencesLoader<Assembly>
397 readonly ReflectionImporter importer;
399 public DynamicLoader (ReflectionImporter importer, CompilerContext compiler)
402 paths.Add (GetSystemDir ());
404 this.importer = importer;
407 public ReflectionImporter Importer {
413 protected override string[] GetDefaultReferences ()
416 // For now the "default config" is harcoded into the compiler
417 // we can move this outside later
419 var default_references = new List<string> (8);
421 default_references.Add ("System");
422 default_references.Add ("System.Xml");
424 default_references.Add ("System.Net");
425 default_references.Add ("System.Windows");
426 default_references.Add ("System.Windows.Browser");
429 if (compiler.Settings.Version > LanguageVersion.ISO_2)
430 default_references.Add ("System.Core");
431 if (compiler.Settings.Version > LanguageVersion.V_3)
432 default_references.Add ("Microsoft.CSharp");
434 return default_references.ToArray ();
438 // Returns the directory where the system assemblies are installed
440 static string GetSystemDir ()
442 return Path.GetDirectoryName (typeof (object).Assembly.Location);
445 public override Assembly HasObjectType (Assembly assembly)
447 return assembly.GetType (compiler.BuiltinTypes.Object.FullName) == null ? null : assembly;
450 public override Assembly LoadAssemblyFile (string assembly, bool isImplicitReference)
456 char[] path_chars = { '/', '\\' };
458 if (assembly.IndexOfAny (path_chars) != -1) {
459 a = Assembly.LoadFrom (assembly);
461 string ass = assembly;
462 if (ass.EndsWith (".dll") || ass.EndsWith (".exe"))
463 ass = assembly.Substring (0, assembly.Length - 4);
464 a = Assembly.Load (ass);
466 } catch (FileNotFoundException) {
467 bool err = !isImplicitReference;
468 foreach (string dir in paths) {
469 string full_path = Path.Combine (dir, assembly);
470 if (!assembly.EndsWith (".dll") && !assembly.EndsWith (".exe"))
474 a = Assembly.LoadFrom (full_path);
477 } catch (FileNotFoundException) {
482 Error_FileNotFound (assembly);
486 } catch (BadImageFormatException) {
487 Error_FileCorrupted (assembly);
493 Module LoadModuleFile (AssemblyDefinitionDynamic assembly, string module)
495 string total_log = "";
499 return assembly.IncludeModule (module);
500 } catch (FileNotFoundException) {
502 foreach (string dir in paths) {
503 string full_path = Path.Combine (dir, module);
504 if (!module.EndsWith (".netmodule"))
505 full_path += ".netmodule";
508 return assembly.IncludeModule (full_path);
509 } catch (FileNotFoundException ff) {
510 total_log += ff.FusionLog;
514 Error_FileNotFound (module);
518 } catch (BadImageFormatException) {
519 Error_FileCorrupted (module);
525 public void LoadModules (AssemblyDefinitionDynamic assembly, RootNamespace targetNamespace)
527 foreach (var moduleName in compiler.Settings.Modules) {
528 var m = LoadModuleFile (assembly, moduleName);
532 var md = importer.ImportModule (m, targetNamespace);
533 assembly.AddModule (md);
537 public override void LoadReferences (ModuleContainer module)
540 List<Tuple<RootNamespace, Assembly>> loaded;
541 base.LoadReferencesCore (module, out corlib, out loaded);
546 importer.ImportAssembly (corlib, module.GlobalRootNamespace);
547 foreach (var entry in loaded) {
548 importer.ImportAssembly (entry.Item2, entry.Item1);