3 // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
5 // Permission is hereby granted, free of charge, to any person obtaining
6 // a copy of this software and associated documentation files (the
7 // "Software"), to deal in the Software without restriction, including
8 // without limitation the rights to use, copy, modify, merge, publish,
9 // distribute, sublicense, and/or sell copies of the Software, and to
10 // permit persons to whom the Software is furnished to do so, subject to
11 // the following conditions:
13 // The above copyright notice and this permission notice shall be
14 // included in all copies or substantial portions of the Software.
16 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
19 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
20 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
21 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
22 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
26 // System.Reflection.Emit/ModuleBuilder.cs
29 // Paolo Molaro (lupus@ximian.com)
31 // (C) 2001 Ximian, Inc. http://www.ximian.com
35 using System.Reflection;
36 using System.Collections;
37 using System.Runtime.CompilerServices;
38 using System.Runtime.InteropServices;
39 using System.Diagnostics.SymbolStore;
41 using System.Resources;
42 using System.Globalization;
44 namespace System.Reflection.Emit {
47 [ComDefaultInterface (typeof (_ModuleBuilder))]
49 [ClassInterface (ClassInterfaceType.None)]
50 public class ModuleBuilder : Module, _ModuleBuilder {
51 #region Sync with reflection.h
52 private IntPtr dynamic_image;
53 private int num_types;
54 private TypeBuilder[] types;
55 private CustomAttributeBuilder[] cattrs;
57 private int table_idx;
58 internal AssemblyBuilder assemblyb;
59 private MethodBuilder[] global_methods;
60 private FieldBuilder[] global_fields;
62 private MonoResource[] resources;
64 private TypeBuilder global_type;
65 private Type global_type_created;
67 Hashtable us_string_cache = new Hashtable ();
68 private int[] table_indexes;
70 ModuleBuilderTokenGenerator token_gen;
71 ArrayList resource_writers = null;
72 ISymbolWriter symbolWriter;
74 [MethodImplAttribute(MethodImplOptions.InternalCall)]
75 private static extern void basic_init (ModuleBuilder ab);
77 internal ModuleBuilder (AssemblyBuilder assb, string name, string fullyqname, bool emitSymbolInfo, bool transient) {
78 this.name = this.scopename = name;
79 this.fqname = fullyqname;
80 this.assembly = this.assemblyb = assb;
81 this.transient = transient;
82 // to keep mcs fast we do not want CryptoConfig wo be involved to create the RNG
83 guid = Guid.FastNewGuidArray ();
84 // guid = Guid.NewGuid().ToByteArray ();
85 table_idx = get_next_table_index (this, 0x00, true);
86 name_cache = new Hashtable ();
93 Assembly asm = Assembly.LoadWithPartialName ("Mono.CompilerServices.SymbolWriter");
94 Type t = asm.GetType ("Mono.CompilerServices.SymbolWriter.SymbolWriterImpl");
96 symbolWriter = (ISymbolWriter) Activator.CreateInstance (t, new object[] { this });
97 string fileName = fqname;
98 if (assemblyb.AssemblyDir != null)
99 fileName = Path.Combine (assemblyb.AssemblyDir, fileName);
100 symbolWriter.Initialize (IntPtr.Zero, fileName, true);
105 public override string FullyQualifiedName {get { return fqname;}}
107 public bool IsTransient () {
111 public void CreateGlobalFunctions ()
113 if (global_type_created != null)
114 throw new InvalidOperationException ("global methods already created");
115 if (global_type != null)
116 global_type_created = global_type.CreateType ();
119 public FieldBuilder DefineInitializedData( string name, byte[] data, FieldAttributes attributes) {
121 throw new ArgumentNullException ("data");
123 FieldBuilder fb = DefineUninitializedData (name, data.Length,
124 attributes | FieldAttributes.HasFieldRVA);
125 fb.SetRVAData (data);
130 public FieldBuilder DefineUninitializedData( string name, int size, FieldAttributes attributes) {
132 throw new ArgumentNullException ("name");
133 if (global_type_created != null)
134 throw new InvalidOperationException ("global fields already created");
135 if (global_type == null)
136 global_type = new TypeBuilder (this, 0);
138 string typeName = "$ArrayType$" + size;
139 Type datablobtype = GetType (typeName, false, false);
140 if (datablobtype == null) {
141 TypeBuilder tb = DefineType (typeName,
142 TypeAttributes.Public|TypeAttributes.ExplicitLayout|TypeAttributes.Sealed,
143 assemblyb.corlib_value_type, null, PackingSize.Size1, size);
147 FieldBuilder fb = global_type.DefineField (name, datablobtype, attributes|FieldAttributes.Static);
149 if (global_fields != null) {
150 FieldBuilder[] new_fields = new FieldBuilder [global_fields.Length+1];
151 System.Array.Copy (global_fields, new_fields, global_fields.Length);
152 new_fields [global_fields.Length] = fb;
153 global_fields = new_fields;
155 global_fields = new FieldBuilder [1];
156 global_fields [0] = fb;
161 private void addGlobalMethod (MethodBuilder mb) {
162 if (global_methods != null) {
163 MethodBuilder[] new_methods = new MethodBuilder [global_methods.Length+1];
164 System.Array.Copy (global_methods, new_methods, global_methods.Length);
165 new_methods [global_methods.Length] = mb;
166 global_methods = new_methods;
168 global_methods = new MethodBuilder [1];
169 global_methods [0] = mb;
173 public MethodBuilder DefineGlobalMethod (string name, MethodAttributes attributes, Type returnType, Type[] parameterTypes)
175 return DefineGlobalMethod (name, attributes, CallingConventions.Standard, returnType, parameterTypes);
178 public MethodBuilder DefineGlobalMethod (string name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes) {
179 return DefineGlobalMethod (name, attributes, callingConvention, returnType, null, null, parameterTypes, null, null);
182 #if NET_2_0 || BOOTSTRAP_NET_2_0
187 MethodBuilder DefineGlobalMethod (string name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] requiredReturnTypeCustomModifiers, Type[] optionalReturnTypeCustomModifiers, Type[] parameterTypes, Type[][] requiredParameterTypeCustomModifiers, Type[][] optionalParameterTypeCustomModifiers)
190 throw new ArgumentNullException ("name");
191 if ((attributes & MethodAttributes.Static) == 0)
192 throw new ArgumentException ("global methods must be static");
193 if (global_type_created != null)
194 throw new InvalidOperationException ("global methods already created");
195 if (global_type == null)
196 global_type = new TypeBuilder (this, 0);
197 MethodBuilder mb = global_type.DefineMethod (name, attributes, callingConvention, returnType, requiredReturnTypeCustomModifiers, optionalReturnTypeCustomModifiers, parameterTypes, requiredParameterTypeCustomModifiers, optionalParameterTypeCustomModifiers);
199 addGlobalMethod (mb);
203 public MethodBuilder DefinePInvokeMethod (string name, string dllName, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes, CallingConvention nativeCallConv, CharSet nativeCharSet) {
204 return DefinePInvokeMethod (name, dllName, name, attributes, callingConvention, returnType, parameterTypes, nativeCallConv, nativeCharSet);
207 public MethodBuilder DefinePInvokeMethod (string name, string dllName, string entryName, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes, CallingConvention nativeCallConv, CharSet nativeCharSet) {
209 throw new ArgumentNullException ("name");
210 if ((attributes & MethodAttributes.Static) == 0)
211 throw new ArgumentException ("global methods must be static");
212 if (global_type_created != null)
213 throw new InvalidOperationException ("global methods already created");
214 if (global_type == null)
215 global_type = new TypeBuilder (this, 0);
216 MethodBuilder mb = global_type.DefinePInvokeMethod (name, dllName, entryName, attributes, callingConvention, returnType, parameterTypes, nativeCallConv, nativeCharSet);
218 addGlobalMethod (mb);
222 public TypeBuilder DefineType (string name) {
223 return DefineType (name, 0);
226 public TypeBuilder DefineType (string name, TypeAttributes attr) {
227 if ((attr & TypeAttributes.Interface) != 0)
228 return DefineType (name, attr, null, null);
229 return DefineType (name, attr, typeof(object), null);
232 public TypeBuilder DefineType (string name, TypeAttributes attr, Type parent) {
233 return DefineType (name, attr, parent, null);
236 private void AddType (TypeBuilder tb)
239 if (types.Length == num_types) {
240 TypeBuilder[] new_types = new TypeBuilder [types.Length * 2];
241 System.Array.Copy (types, new_types, num_types);
245 types = new TypeBuilder [1];
247 types [num_types] = tb;
251 private TypeBuilder DefineType (string name, TypeAttributes attr, Type parent, Type[] interfaces, PackingSize packsize, int typesize) {
252 if (name_cache.Contains (name))
253 throw new ArgumentException ("Duplicate type name within an assembly.");
255 TypeBuilder res = new TypeBuilder (this, name, attr, parent, interfaces, packsize, typesize, null);
257 name_cache.Add (name, res);
261 internal void RegisterTypeName (TypeBuilder tb, string name) {
262 name_cache.Add (name, tb);
268 public TypeBuilder DefineType (string name, TypeAttributes attr, Type parent, Type[] interfaces) {
269 return DefineType (name, attr, parent, interfaces, PackingSize.Unspecified, TypeBuilder.UnspecifiedTypeSize);
272 public TypeBuilder DefineType (string name, TypeAttributes attr, Type parent, int typesize) {
273 return DefineType (name, attr, parent, null, PackingSize.Unspecified, TypeBuilder.UnspecifiedTypeSize);
276 public TypeBuilder DefineType (string name, TypeAttributes attr, Type parent, PackingSize packsize) {
277 return DefineType (name, attr, parent, null, packsize, TypeBuilder.UnspecifiedTypeSize);
280 public TypeBuilder DefineType (string name, TypeAttributes attr, Type parent, PackingSize packsize, int typesize) {
281 return DefineType (name, attr, parent, null, packsize, typesize);
284 public MethodInfo GetArrayMethod( Type arrayClass, string methodName, CallingConventions callingConvention, Type returnType, Type[] parameterTypes) {
285 return new MonoArrayMethod (arrayClass, methodName, callingConvention, returnType, parameterTypes);
288 public EnumBuilder DefineEnum( string name, TypeAttributes visibility, Type underlyingType) {
289 if (name_cache.Contains (name))
290 throw new ArgumentException ("Duplicate type name within an assembly.");
292 EnumBuilder eb = new EnumBuilder (this, name, visibility, underlyingType);
293 TypeBuilder res = eb.GetTypeBuilder ();
295 name_cache.Add (name, res);
302 public override Type GetType( string className) {
303 return GetType (className, false, false);
309 public override Type GetType( string className, bool ignoreCase) {
310 return GetType (className, false, ignoreCase);
313 private TypeBuilder search_in_array (TypeBuilder[] arr, int validElementsInArray, string className) {
315 for (i = 0; i < validElementsInArray; ++i) {
316 if (String.Compare (className, arr [i].FullName, true, CultureInfo.InvariantCulture) == 0) {
323 private TypeBuilder search_nested_in_array (TypeBuilder[] arr, int validElementsInArray, string className) {
325 for (i = 0; i < validElementsInArray; ++i) {
326 if (String.Compare (className, arr [i].Name, true, CultureInfo.InvariantCulture) == 0)
332 [MethodImplAttribute(MethodImplOptions.InternalCall)]
333 private static extern Type create_modified_type (TypeBuilder tb, string modifiers);
335 static readonly char [] type_modifiers = {'&', '[', '*'};
337 private TypeBuilder GetMaybeNested (TypeBuilder t, string className) {
341 subt = className.IndexOf ('+');
343 if (t.subtypes != null)
344 return search_nested_in_array (t.subtypes, t.subtypes.Length, className);
347 if (t.subtypes != null) {
348 pname = className.Substring (0, subt);
349 rname = className.Substring (subt + 1);
350 TypeBuilder result = search_nested_in_array (t.subtypes, t.subtypes.Length, pname);
352 return GetMaybeNested (result, rname);
360 public override Type GetType (string className, bool throwOnError, bool ignoreCase) {
362 string orig = className;
364 TypeBuilder result = null;
366 if (types == null && throwOnError)
367 throw new TypeLoadException (className);
369 subt = className.IndexOfAny (type_modifiers);
371 modifiers = className.Substring (subt);
372 className = className.Substring (0, subt);
377 result = name_cache [className] as TypeBuilder;
379 subt = className.IndexOf ('+');
382 result = search_in_array (types, num_types, className);
385 pname = className.Substring (0, subt);
386 rname = className.Substring (subt + 1);
387 result = search_in_array (types, num_types, pname);
389 result = GetMaybeNested (result, rname);
392 if ((result == null) && throwOnError)
393 throw new TypeLoadException (orig);
394 if (result != null && (modifiers != null))
395 return create_modified_type (result, modifiers);
399 internal int get_next_table_index (object obj, int table, bool inc) {
400 if (table_indexes == null) {
401 table_indexes = new int [64];
402 for (int i=0; i < 64; ++i)
403 table_indexes [i] = 1;
404 /* allow room for .<Module> in TypeDef table */
405 table_indexes [0x02] = 2;
407 // Console.WriteLine ("getindex for table "+table.ToString()+" got "+table_indexes [table].ToString());
409 return table_indexes [table]++;
410 return table_indexes [table];
413 public void SetCustomAttribute( CustomAttributeBuilder customBuilder) {
414 if (cattrs != null) {
415 CustomAttributeBuilder[] new_array = new CustomAttributeBuilder [cattrs.Length + 1];
416 cattrs.CopyTo (new_array, 0);
417 new_array [cattrs.Length] = customBuilder;
420 cattrs = new CustomAttributeBuilder [1];
421 cattrs [0] = customBuilder;
428 public void SetCustomAttribute( ConstructorInfo con, byte[] binaryAttribute) {
429 SetCustomAttribute (new CustomAttributeBuilder (con, binaryAttribute));
432 public ISymbolWriter GetSymWriter () {
436 public ISymbolDocumentWriter DefineDocument (string url, Guid language, Guid languageVendor, Guid documentType)
438 if (symbolWriter != null)
439 return symbolWriter.DefineDocument (url, language, languageVendor, documentType);
444 public override Type [] GetTypes ()
447 return new TypeBuilder [0];
450 TypeBuilder [] copy = new TypeBuilder [n];
451 Array.Copy (types, copy, n);
456 public IResourceWriter DefineResource (string name, string description, ResourceAttributes attribute)
459 throw new ArgumentNullException ("name");
460 if (name == String.Empty)
461 throw new ArgumentException ("name cannot be empty");
463 throw new InvalidOperationException ("The module is transient");
464 if (!assemblyb.IsSave)
465 throw new InvalidOperationException ("The assembly is transient");
466 ResourceWriter writer = new ResourceWriter (new MemoryStream ());
467 if (resource_writers == null)
468 resource_writers = new ArrayList ();
469 resource_writers.Add (writer);
471 // The data is filled out later
472 if (resources != null) {
473 MonoResource[] new_r = new MonoResource [resources.Length + 1];
474 System.Array.Copy(resources, new_r, resources.Length);
477 resources = new MonoResource [1];
479 int p = resources.Length - 1;
480 resources [p].name = name;
481 resources [p].attrs = attribute;
486 public IResourceWriter DefineResource (string name, string description)
488 return DefineResource (name, description, ResourceAttributes.Public);
492 public void DefineUnmanagedResource (byte[] resource)
494 if (resource == null)
495 throw new ArgumentNullException ("resource");
497 throw new NotImplementedException ();
501 public void DefineUnmanagedResource (string resourceFileName)
503 if (resourceFileName == null)
504 throw new ArgumentNullException ("resourceFileName");
505 if (resourceFileName == String.Empty)
506 throw new ArgumentException ("resourceFileName");
507 if (!File.Exists (resourceFileName) || Directory.Exists (resourceFileName))
508 throw new FileNotFoundException ("File '" + resourceFileName + "' does not exists or is a directory.");
510 throw new NotImplementedException ();
514 public void SetSymCustomAttribute (string name, byte[] data)
516 throw new NotImplementedException ();
520 public void SetUserEntryPoint (MethodInfo entryPoint)
522 if (entryPoint == null)
523 throw new ArgumentNullException ("entryPoint");
524 if (entryPoint.DeclaringType.Module != this)
525 throw new InvalidOperationException ("entryPoint is not contained in this module");
526 throw new NotImplementedException ();
529 public MethodToken GetMethodToken (MethodInfo method)
532 throw new ArgumentNullException ("method");
533 if (method.DeclaringType.Module != this)
534 throw new InvalidOperationException ("The method is not in this module");
535 return new MethodToken (GetToken (method));
538 public MethodToken GetArrayMethodToken (Type arrayClass, string methodName, CallingConventions callingConvention, Type returnType, Type[] parameterTypes)
540 return GetMethodToken (GetArrayMethod (arrayClass, methodName, callingConvention, returnType, parameterTypes));
546 public MethodToken GetConstructorToken (ConstructorInfo con)
549 throw new ArgumentNullException ("con");
550 return new MethodToken (GetToken (con));
553 public FieldToken GetFieldToken (FieldInfo field)
556 throw new ArgumentNullException ("field");
557 if (field.DeclaringType.Module != this)
558 throw new InvalidOperationException ("The method is not in this module");
559 return new FieldToken (GetToken (field));
563 public SignatureToken GetSignatureToken (byte[] sigBytes, int sigLength)
565 throw new NotImplementedException ();
568 public SignatureToken GetSignatureToken (SignatureHelper sigHelper)
570 if (sigHelper == null)
571 throw new ArgumentNullException ("sigHelper");
572 return new SignatureToken (GetToken (sigHelper));
575 public StringToken GetStringConstant (string str)
578 throw new ArgumentNullException ("str");
579 return new StringToken (GetToken (str));
582 public TypeToken GetTypeToken (Type type)
585 throw new ArgumentNullException ("type");
587 throw new ArgumentException ("type can't be a byref type", "type");
588 if (!IsTransient () && (type.Module is ModuleBuilder) && ((ModuleBuilder)type.Module).IsTransient ())
589 throw new InvalidOperationException ("a non-transient module can't reference a transient module");
590 return new TypeToken (GetToken (type));
593 public TypeToken GetTypeToken (string type)
595 return GetTypeToken (GetType (name));
598 [MethodImplAttribute(MethodImplOptions.InternalCall)]
599 private static extern int getUSIndex (ModuleBuilder mb, string str);
601 [MethodImplAttribute(MethodImplOptions.InternalCall)]
602 private static extern int getToken (ModuleBuilder mb, object obj);
604 [MethodImplAttribute(MethodImplOptions.InternalCall)]
605 private static extern int getMethodToken (ModuleBuilder mb, MethodInfo method,
606 Type[] opt_param_types);
608 internal int GetToken (string str) {
609 if (us_string_cache.Contains (str))
610 return (int)us_string_cache [str];
611 int result = getUSIndex (this, str);
612 us_string_cache [str] = result;
616 internal int GetToken (MemberInfo member) {
617 return getToken (this, member);
620 internal int GetToken (MethodInfo method, Type[] opt_param_types) {
621 return getMethodToken (this, method, opt_param_types);
624 internal int GetToken (SignatureHelper helper) {
625 return getToken (this, helper);
628 internal TokenGenerator GetTokenGenerator () {
629 if (token_gen == null)
630 token_gen = new ModuleBuilderTokenGenerator (this);
634 [MethodImplAttribute(MethodImplOptions.InternalCall)]
635 private static extern void build_metadata (ModuleBuilder mb);
637 [MethodImplAttribute(MethodImplOptions.InternalCall)]
638 private extern void WriteToFile (IntPtr handle);
640 internal void Save ()
642 if (transient && !is_main)
646 for (int i = 0; i < num_types; ++i)
647 if (!types [i].is_created)
648 throw new NotSupportedException ("Type '" + types [i].FullName + "' was not completed.");
651 if ((global_type != null) && (global_type_created == null))
652 global_type_created = global_type.CreateType ();
654 if (resource_writers != null) {
655 for (int i = 0; i < resource_writers.Count; ++i) {
656 ResourceWriter writer = (ResourceWriter)resource_writers [i];
658 MemoryStream stream = (MemoryStream)writer.Stream;
659 resources [i].data = new byte [stream.Length];
660 stream.Seek (0, SeekOrigin.Begin);
661 stream.Read (resources [i].data, 0, (int)stream.Length);
665 build_metadata (this);
667 string fileName = fqname;
668 if (assemblyb.AssemblyDir != null)
669 fileName = Path.Combine (assemblyb.AssemblyDir, fileName);
671 using (FileStream file = new FileStream (fileName, FileMode.Create, FileAccess.Write))
672 WriteToFile (file.Handle);
675 // The constant 0x80000000 is internal to Mono, it means `make executable'
677 File.SetAttributes (fileName, (FileAttributes) (unchecked ((int) 0x80000000)));
679 if (types != null && symbolWriter != null) {
680 for (int i = 0; i < num_types; ++i)
681 types [i].GenerateDebugInfo (symbolWriter);
682 symbolWriter.Close ();
686 internal string FileName {
692 internal bool IsMain {
698 internal void CreateGlobalType () {
699 if (global_type == null)
700 global_type = new TypeBuilder (this, 0);
703 internal static Guid Mono_GetGuid (ModuleBuilder mb)
705 return new Guid (mb.guid);
708 void _ModuleBuilder.GetIDsOfNames ([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
710 throw new NotImplementedException ();
713 void _ModuleBuilder.GetTypeInfo (uint iTInfo, uint lcid, IntPtr ppTInfo)
715 throw new NotImplementedException ();
718 void _ModuleBuilder.GetTypeInfoCount (out uint pcTInfo)
720 throw new NotImplementedException ();
723 void _ModuleBuilder.Invoke (uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
725 throw new NotImplementedException ();
729 internal class ModuleBuilderTokenGenerator : TokenGenerator {
731 private ModuleBuilder mb;
733 public ModuleBuilderTokenGenerator (ModuleBuilder mb) {
737 public int GetToken (string str) {
738 return mb.GetToken (str);
741 public int GetToken (MemberInfo member) {
742 return mb.GetToken (member);
745 public int GetToken (MethodInfo method, Type[] opt_param_types) {
746 return mb.GetToken (method, opt_param_types);
749 public int GetToken (SignatureHelper helper) {
750 return mb.GetToken (helper);