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 (BuildinTypes buildin)
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 (BuildinTypes buildin)
53 public override void AddCompiledType (TypeBuilder builder, TypeSpec spec)
57 protected override MemberKind DetermineKindFromBaseType (Type baseType)
59 if (baseType == typeof (ValueType))
60 return MemberKind.Struct;
62 if (baseType == typeof (System.Enum))
63 return MemberKind.Enum;
65 if (baseType == typeof (MulticastDelegate))
66 return MemberKind.Delegate;
68 return MemberKind.Class;
71 public override void GetCustomAttributeTypeName (CustomAttributeData cad, out string typeNamespace, out string typeName)
73 var dt = cad.Constructor.DeclaringType;
74 typeNamespace = dt.Namespace;
78 protected override bool HasVolatileModifier (Type[] modifiers)
80 foreach (var t in modifiers) {
81 if (t == typeof (IsVolatile))
88 public void ImportAssembly (Assembly assembly, RootNamespace targetNamespace)
90 // It can be used more than once when importing same assembly
91 // into 2 or more global aliases
92 var definition = GetAssemblyDefinition (assembly);
95 // This part tries to simulate loading of top-level
96 // types only, any missing dependencies are ignores here.
97 // Full error report is reported later when the type is
102 all_types = assembly.GetTypes ();
103 } catch (ReflectionTypeLoadException e) {
107 ImportTypes (all_types, targetNamespace, definition.HasExtensionMethod);
110 public ImportedModuleDefinition ImportModule (Module module, RootNamespace targetNamespace)
112 var module_definition = new ImportedModuleDefinition (module, this);
113 module_definition.ReadAttributes ();
117 all_types = module.GetTypes ();
118 } catch (ReflectionTypeLoadException e) {
122 ImportTypes (all_types, targetNamespace, false);
124 return module_definition;
127 void Initialize (BuildinTypes buildin)
130 // Setup mapping for build-in types to avoid duplication of their definition
132 compiled_types.Add (typeof (object), buildin.Object);
133 compiled_types.Add (typeof (System.ValueType), buildin.ValueType);
134 compiled_types.Add (typeof (System.Attribute), buildin.Attribute);
136 compiled_types.Add (typeof (int), buildin.Int);
137 compiled_types.Add (typeof (long), buildin.Long);
138 compiled_types.Add (typeof (uint), buildin.UInt);
139 compiled_types.Add (typeof (ulong), buildin.ULong);
140 compiled_types.Add (typeof (byte), buildin.Byte);
141 compiled_types.Add (typeof (sbyte), buildin.SByte);
142 compiled_types.Add (typeof (short), buildin.Short);
143 compiled_types.Add (typeof (ushort), buildin.UShort);
145 compiled_types.Add (typeof (System.Collections.IEnumerator), buildin.IEnumerator);
146 compiled_types.Add (typeof (System.Collections.IEnumerable), buildin.IEnumerable);
147 compiled_types.Add (typeof (System.IDisposable), buildin.IDisposable);
149 compiled_types.Add (typeof (char), buildin.Char);
150 compiled_types.Add (typeof (string), buildin.String);
151 compiled_types.Add (typeof (float), buildin.Float);
152 compiled_types.Add (typeof (double), buildin.Double);
153 compiled_types.Add (typeof (decimal), buildin.Decimal);
154 compiled_types.Add (typeof (bool), buildin.Bool);
155 compiled_types.Add (typeof (System.IntPtr), buildin.IntPtr);
156 compiled_types.Add (typeof (System.UIntPtr), buildin.UIntPtr);
158 compiled_types.Add (typeof (System.MulticastDelegate), buildin.MulticastDelegate);
159 compiled_types.Add (typeof (System.Delegate), buildin.Delegate);
160 compiled_types.Add (typeof (System.Enum), buildin.Enum);
161 compiled_types.Add (typeof (System.Array), buildin.Array);
162 compiled_types.Add (typeof (void), buildin.Void);
163 compiled_types.Add (typeof (System.Type), buildin.Type);
164 compiled_types.Add (typeof (System.Exception), buildin.Exception);
165 compiled_types.Add (typeof (System.RuntimeFieldHandle), buildin.RuntimeFieldHandle);
166 compiled_types.Add (typeof (System.RuntimeTypeHandle), buildin.RuntimeTypeHandle);
172 public class AssemblyDefinitionDynamic : AssemblyDefinition
175 // In-memory only assembly container
177 public AssemblyDefinitionDynamic (ModuleContainer module, string name)
178 : base (module, name)
183 // Assembly container with file output
185 public AssemblyDefinitionDynamic (ModuleContainer module, string name, string fileName)
186 : base (module, name, fileName)
190 public Module IncludeModule (string moduleFile)
192 return builder_extra.AddModule (moduleFile);
196 public override ModuleBuilder CreateModuleBuilder ()
198 if (file_name == null)
199 return Builder.DefineDynamicModule (Name, false);
201 return base.CreateModuleBuilder ();
205 // Initializes the code generator
207 public bool Create (AppDomain domain, AssemblyBuilderAccess access)
210 throw new NotSupportedException ();
212 ResolveAssemblySecurityAttributes ();
213 var an = CreateAssemblyName ();
216 Builder = file_name == null ?
217 domain.DefineDynamicAssembly (an, access) :
218 domain.DefineDynamicAssembly (an, access, Dirname (file_name));
219 } catch (ArgumentException) {
220 // specified key may not be exportable outside it's container
221 if (RootContext.StrongNameKeyContainer != null) {
222 Report.Error (1548, "Could not access the key inside the container `" +
223 RootContext.StrongNameKeyContainer + "'.");
228 module.Create (this, CreateModuleBuilder ());
229 builder_extra = new AssemblyBuilderMonoSpecific (Builder, Compiler);
234 static string Dirname (string name)
236 int pos = name.LastIndexOf ('/');
239 return name.Substring (0, pos);
241 pos = name.LastIndexOf ('\\');
243 return name.Substring (0, pos);
249 protected override void SaveModule (PortableExecutableKinds pekind, ImageFileMachine machine)
252 var module_only = typeof (AssemblyBuilder).GetProperty ("IsModuleOnly", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
253 var set_module_only = module_only.GetSetMethod (true);
255 set_module_only.Invoke (Builder, new object[] { true });
257 base.SaveModule (pekind, machine);
260 Builder.Save (file_name, pekind, machine);
266 // Extension to System.Reflection.Emit.AssemblyBuilder to have fully compatible
269 class AssemblyBuilderMonoSpecific : AssemblyBuilderExtension
271 static MethodInfo adder_method;
272 static MethodInfo add_permission;
273 static MethodInfo add_type_forwarder;
274 static MethodInfo win32_icon_define;
275 static FieldInfo assembly_version;
276 static FieldInfo assembly_algorithm;
277 static FieldInfo assembly_culture;
278 static FieldInfo assembly_flags;
280 AssemblyBuilder builder;
282 public AssemblyBuilderMonoSpecific (AssemblyBuilder ab, CompilerContext ctx)
288 public override Module AddModule (string module)
291 if (adder_method == null)
292 adder_method = typeof (AssemblyBuilder).GetMethod ("AddModule", BindingFlags.Instance | BindingFlags.NonPublic);
294 return (Module) adder_method.Invoke (builder, new object[] { module });
296 return base.AddModule (module);
300 public override void AddPermissionRequests (PermissionSet[] permissions)
303 if (add_permission == null)
304 add_permission = typeof (AssemblyBuilder).GetMethod ("AddPermissionRequests", BindingFlags.Instance | BindingFlags.NonPublic);
306 add_permission.Invoke (builder, permissions);
308 base.AddPermissionRequests (permissions);
312 public override void AddTypeForwarder (TypeSpec type, Location loc)
315 if (add_type_forwarder == null) {
316 add_type_forwarder = typeof (AssemblyBuilder).GetMethod ("AddTypeForwarder", BindingFlags.NonPublic | BindingFlags.Instance);
319 add_type_forwarder.Invoke (builder, new object[] { type.GetMetaInfo () });
321 base.AddTypeForwarder (type, loc);
325 public override void DefineWin32IconResource (string fileName)
328 if (win32_icon_define == null)
329 win32_icon_define = typeof (AssemblyBuilder).GetMethod ("DefineIconResource", BindingFlags.Instance | BindingFlags.NonPublic);
331 win32_icon_define.Invoke (builder, new object[] { fileName });
333 base.DefineWin32IconResource (fileName);
337 public override void SetAlgorithmId (uint value, Location loc)
340 if (assembly_algorithm == null)
341 assembly_algorithm = typeof (AssemblyBuilder).GetField ("algid", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.SetField);
343 assembly_algorithm.SetValue (builder, value);
345 base.SetAlgorithmId (value, loc);
349 public override void SetCulture (string culture, Location loc)
352 if (assembly_culture == null)
353 assembly_culture = typeof (AssemblyBuilder).GetField ("culture", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.SetField);
355 assembly_culture.SetValue (builder, culture);
357 base.SetCulture (culture, loc);
361 public override void SetFlags (uint flags, Location loc)
364 if (assembly_flags == null)
365 assembly_flags = typeof (AssemblyBuilder).GetField ("flags", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.SetField);
367 assembly_flags.SetValue (builder, flags);
369 base.SetFlags (flags, loc);
373 public override void SetVersion (Version version, Location loc)
376 if (assembly_version == null)
377 assembly_version = typeof (AssemblyBuilder).GetField ("version", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.SetField);
379 assembly_version.SetValue (builder, version.ToString (4));
381 base.SetVersion (version, loc);
387 // Reflection based references loader
389 class DynamicLoader : AssemblyReferencesLoader<Assembly>
391 readonly ReflectionImporter importer;
393 public DynamicLoader (ReflectionImporter importer, CompilerContext compiler)
396 paths.Add (GetSystemDir ());
398 this.importer = importer;
401 public ReflectionImporter Importer {
407 protected override string[] GetDefaultReferences ()
410 // For now the "default config" is harcoded into the compiler
411 // we can move this outside later
413 var default_references = new List<string> (8);
415 default_references.Add ("System");
416 default_references.Add ("System.Xml");
418 default_references.Add ("System.Net");
419 default_references.Add ("System.Windows");
420 default_references.Add ("System.Windows.Browser");
423 if (RootContext.Version > LanguageVersion.ISO_2)
424 default_references.Add ("System.Core");
425 if (RootContext.Version > LanguageVersion.V_3)
426 default_references.Add ("Microsoft.CSharp");
428 return default_references.ToArray ();
432 // Returns the directory where the system assemblies are installed
434 static string GetSystemDir ()
436 return Path.GetDirectoryName (typeof (object).Assembly.Location);
439 public override bool HasObjectType (Assembly assembly)
441 return assembly.GetType (compiler.BuildinTypes.Object.FullName) != null;
444 public override Assembly LoadAssemblyFile (string fileName)
446 return LoadAssemblyFile (fileName, false);
449 Assembly LoadAssemblyFile (string assembly, bool soft)
455 char[] path_chars = { '/', '\\' };
457 if (assembly.IndexOfAny (path_chars) != -1) {
458 a = Assembly.LoadFrom (assembly);
460 string ass = assembly;
461 if (ass.EndsWith (".dll") || ass.EndsWith (".exe"))
462 ass = assembly.Substring (0, assembly.Length - 4);
463 a = Assembly.Load (ass);
465 } catch (FileNotFoundException) {
467 foreach (string dir in paths) {
468 string full_path = Path.Combine (dir, assembly);
469 if (!assembly.EndsWith (".dll") && !assembly.EndsWith (".exe"))
473 a = Assembly.LoadFrom (full_path);
476 } catch (FileNotFoundException) {
481 Error_FileNotFound (assembly);
485 } catch (BadImageFormatException) {
486 Error_FileCorrupted (assembly);
492 public override Assembly LoadAssemblyDefault (string fileName)
494 return LoadAssemblyFile (fileName, true);
497 Module LoadModuleFile (AssemblyDefinitionDynamic assembly, string module)
499 string total_log = "";
503 return assembly.IncludeModule (module);
504 } catch (FileNotFoundException) {
506 foreach (string dir in paths) {
507 string full_path = Path.Combine (dir, module);
508 if (!module.EndsWith (".netmodule"))
509 full_path += ".netmodule";
512 return assembly.IncludeModule (full_path);
513 } catch (FileNotFoundException ff) {
514 total_log += ff.FusionLog;
518 Error_FileNotFound (module);
522 } catch (BadImageFormatException) {
523 Error_FileCorrupted (module);
529 public void LoadModules (AssemblyDefinitionDynamic assembly, RootNamespace targetNamespace)
531 if (RootContext.Modules.Count == 0)
534 foreach (var moduleName in RootContext.Modules) {
535 var m = LoadModuleFile (assembly, moduleName);
539 var md = importer.ImportModule (m, targetNamespace);
540 assembly.AddModule (md);
544 public override void LoadReferences (ModuleContainer module)
547 List<Tuple<RootNamespace, Assembly>> loaded;
548 base.LoadReferencesCore (module, out corlib, out loaded);
553 importer.ImportAssembly (corlib, module.GlobalRootNamespace);
554 foreach (var entry in loaded) {
555 importer.ImportAssembly (entry.Item2, entry.Item1);