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 protected override MemberKind DetermineKindFromBaseType (Type baseType)
55 if (baseType == typeof (ValueType))
56 return MemberKind.Struct;
58 if (baseType == typeof (System.Enum))
59 return MemberKind.Enum;
61 if (baseType == typeof (MulticastDelegate))
62 return MemberKind.Delegate;
64 return MemberKind.Class;
67 public override void GetCustomAttributeTypeName (CustomAttributeData cad, out string typeNamespace, out string typeName)
69 var dt = cad.Constructor.DeclaringType;
70 typeNamespace = dt.Namespace;
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 var definition = 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, definition.HasExtensionMethod);
106 public ImportedModuleDefinition ImportModule (Module module, RootNamespace targetNamespace)
108 var module_definition = new ImportedModuleDefinition (module, this);
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 (BuildinTypes buildin)
126 // Setup mapping for build-in types to avoid duplication of their definition
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);
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);
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);
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);
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);
168 public class AssemblyDefinitionDynamic : AssemblyDefinition
171 // In-memory only assembly container
173 public AssemblyDefinitionDynamic (ModuleContainer module, string name)
174 : base (module, name)
179 // Assembly container with file output
181 public AssemblyDefinitionDynamic (ModuleContainer module, string name, string fileName)
182 : base (module, name, fileName)
186 public Module IncludeModule (string moduleFile)
188 return builder_extra.AddModule (moduleFile);
192 public override ModuleBuilder CreateModuleBuilder ()
194 if (file_name == null)
195 return Builder.DefineDynamicModule (Name, false);
197 return base.CreateModuleBuilder ();
201 // Initializes the code generator
203 public bool Create (AppDomain domain, AssemblyBuilderAccess access)
206 throw new NotSupportedException ();
208 ResolveAssemblySecurityAttributes ();
209 var an = CreateAssemblyName ();
212 Builder = file_name == null ?
213 domain.DefineDynamicAssembly (an, access) :
214 domain.DefineDynamicAssembly (an, access, Dirname (file_name));
215 } catch (ArgumentException) {
216 // specified key may not be exportable outside it's container
217 if (RootContext.StrongNameKeyContainer != null) {
218 Report.Error (1548, "Could not access the key inside the container `" +
219 RootContext.StrongNameKeyContainer + "'.");
224 builder_extra = new AssemblyBuilderMonoSpecific (Builder, Compiler);
229 static string Dirname (string name)
231 int pos = name.LastIndexOf ('/');
234 return name.Substring (0, pos);
236 pos = name.LastIndexOf ('\\');
238 return name.Substring (0, pos);
244 protected override void SaveModule (PortableExecutableKinds pekind, ImageFileMachine machine)
247 var module_only = typeof (AssemblyBuilder).GetProperty ("IsModuleOnly", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
248 var set_module_only = module_only.GetSetMethod (true);
250 set_module_only.Invoke (Builder, new object[] { true });
252 base.SaveModule (pekind, machine);
255 Builder.Save (file_name, pekind, machine);
261 // Extension to System.Reflection.Emit.AssemblyBuilder to have fully compatible
264 class AssemblyBuilderMonoSpecific : AssemblyBuilderExtension
266 static MethodInfo adder_method;
267 static MethodInfo add_permission;
268 static MethodInfo add_type_forwarder;
269 static MethodInfo win32_icon_define;
270 static FieldInfo assembly_version;
271 static FieldInfo assembly_algorithm;
272 static FieldInfo assembly_culture;
273 static FieldInfo assembly_flags;
275 AssemblyBuilder builder;
277 public AssemblyBuilderMonoSpecific (AssemblyBuilder ab, CompilerContext ctx)
283 public override Module AddModule (string module)
286 if (adder_method == null)
287 adder_method = typeof (AssemblyBuilder).GetMethod ("AddModule", BindingFlags.Instance | BindingFlags.NonPublic);
289 return (Module) adder_method.Invoke (builder, new object[] { module });
291 return base.AddModule (module);
295 public override void AddPermissionRequests (PermissionSet[] permissions)
298 if (add_permission == null)
299 add_permission = typeof (AssemblyBuilder).GetMethod ("AddPermissionRequests", BindingFlags.Instance | BindingFlags.NonPublic);
301 add_permission.Invoke (builder, permissions);
303 base.AddPermissionRequests (permissions);
307 public override void AddTypeForwarder (TypeSpec type, Location loc)
310 if (add_type_forwarder == null) {
311 add_type_forwarder = typeof (AssemblyBuilder).GetMethod ("AddTypeForwarder", BindingFlags.NonPublic | BindingFlags.Instance);
314 add_type_forwarder.Invoke (builder, new object[] { type.GetMetaInfo () });
316 base.AddTypeForwarder (type, loc);
320 public override void DefineWin32IconResource (string fileName)
323 if (win32_icon_define == null)
324 win32_icon_define = typeof (AssemblyBuilder).GetMethod ("DefineIconResource", BindingFlags.Instance | BindingFlags.NonPublic);
326 win32_icon_define.Invoke (builder, new object[] { fileName });
328 base.DefineWin32IconResource (fileName);
332 public override void SetAlgorithmId (uint value, Location loc)
335 if (assembly_algorithm == null)
336 assembly_algorithm = typeof (AssemblyBuilder).GetField ("algid", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.SetField);
338 assembly_algorithm.SetValue (builder, value);
340 base.SetAlgorithmId (value, loc);
344 public override void SetCulture (string culture, Location loc)
347 if (assembly_culture == null)
348 assembly_culture = typeof (AssemblyBuilder).GetField ("culture", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.SetField);
350 assembly_culture.SetValue (builder, culture);
352 base.SetCulture (culture, loc);
356 public override void SetFlags (uint flags, Location loc)
359 if (assembly_flags == null)
360 assembly_flags = typeof (AssemblyBuilder).GetField ("flags", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.SetField);
362 assembly_flags.SetValue (builder, flags);
364 base.SetFlags (flags, loc);
368 public override void SetVersion (Version version, Location loc)
371 if (assembly_version == null)
372 assembly_version = typeof (AssemblyBuilder).GetField ("version", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.SetField);
374 assembly_version.SetValue (builder, version.ToString (4));
376 base.SetVersion (version, loc);
382 // Reflection based references loader
384 class DynamicLoader : AssemblyReferencesLoader<Assembly>
386 readonly ReflectionImporter importer;
388 public DynamicLoader (ReflectionImporter importer, CompilerContext compiler)
391 paths.Add (GetSystemDir ());
393 this.importer = importer;
396 public ReflectionImporter Importer {
402 protected override string[] GetDefaultReferences ()
405 // For now the "default config" is harcoded into the compiler
406 // we can move this outside later
408 var default_references = new List<string> (8);
410 default_references.Add ("System");
411 default_references.Add ("System.Xml");
413 default_references.Add ("System.Net");
414 default_references.Add ("System.Windows");
415 default_references.Add ("System.Windows.Browser");
418 if (RootContext.Version > LanguageVersion.ISO_2)
419 default_references.Add ("System.Core");
420 if (RootContext.Version > LanguageVersion.V_3)
421 default_references.Add ("Microsoft.CSharp");
423 return default_references.ToArray ();
427 // Returns the directory where the system assemblies are installed
429 static string GetSystemDir ()
431 return Path.GetDirectoryName (typeof (object).Assembly.Location);
434 public override bool HasObjectType (Assembly assembly)
436 return assembly.GetType (compiler.BuildinTypes.Object.FullName) != null;
439 public override Assembly LoadAssemblyFile (string fileName)
441 return LoadAssemblyFile (fileName, false);
444 Assembly LoadAssemblyFile (string assembly, bool soft)
450 char[] path_chars = { '/', '\\' };
452 if (assembly.IndexOfAny (path_chars) != -1) {
453 a = Assembly.LoadFrom (assembly);
455 string ass = assembly;
456 if (ass.EndsWith (".dll") || ass.EndsWith (".exe"))
457 ass = assembly.Substring (0, assembly.Length - 4);
458 a = Assembly.Load (ass);
460 } catch (FileNotFoundException) {
462 foreach (string dir in paths) {
463 string full_path = Path.Combine (dir, assembly);
464 if (!assembly.EndsWith (".dll") && !assembly.EndsWith (".exe"))
468 a = Assembly.LoadFrom (full_path);
471 } catch (FileNotFoundException) {
476 Error_FileNotFound (assembly);
480 } catch (BadImageFormatException) {
481 Error_FileCorrupted (assembly);
487 public override Assembly LoadAssemblyDefault (string fileName)
489 return LoadAssemblyFile (fileName, true);
492 Module LoadModuleFile (AssemblyDefinitionDynamic assembly, string module)
494 string total_log = "";
498 return assembly.IncludeModule (module);
499 } catch (FileNotFoundException) {
501 foreach (string dir in paths) {
502 string full_path = Path.Combine (dir, module);
503 if (!module.EndsWith (".netmodule"))
504 full_path += ".netmodule";
507 return assembly.IncludeModule (full_path);
508 } catch (FileNotFoundException ff) {
509 total_log += ff.FusionLog;
513 Error_FileNotFound (module);
517 } catch (BadImageFormatException) {
518 Error_FileCorrupted (module);
524 public void LoadModules (AssemblyDefinitionDynamic assembly, RootNamespace targetNamespace)
526 if (RootContext.Modules.Count == 0)
529 foreach (var moduleName in RootContext.Modules) {
530 var m = LoadModuleFile (assembly, moduleName);
534 var md = importer.ImportModule (m, targetNamespace);
535 assembly.AddModule (md);
539 public override void LoadReferences (ModuleContainer module)
542 List<Tuple<RootNamespace, Assembly>> loaded;
543 base.LoadReferencesCore (module, out corlib, out loaded);
548 importer.ImportAssembly (corlib, module.GlobalRootNamespace);
549 foreach (var entry in loaded) {
550 importer.ImportAssembly (entry.Item2, entry.Item1);