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.Collections.Generic;
38 using System.Runtime.CompilerServices;
39 using System.Runtime.InteropServices;
40 using System.Diagnostics.SymbolStore;
42 using System.Resources;
43 using System.Globalization;
45 namespace System.Reflection.Emit {
47 [ComDefaultInterface (typeof (_ModuleBuilder))]
48 [ClassInterface (ClassInterfaceType.None)]
49 [StructLayout (LayoutKind.Sequential)]
50 public class ModuleBuilder : Module, _ModuleBuilder {
52 #pragma warning disable 169, 414
53 #region Sync with object-internals.h
54 private UIntPtr dynamic_image; /* GC-tracked */
55 private int num_types;
56 private TypeBuilder[] types;
57 private CustomAttributeBuilder[] cattrs;
59 private int table_idx;
60 internal AssemblyBuilder assemblyb;
61 private MethodBuilder[] global_methods;
62 private FieldBuilder[] global_fields;
64 private MonoResource[] resources;
66 #pragma warning restore 169, 414
68 private TypeBuilder global_type;
69 private Type global_type_created;
71 Dictionary<string, int> us_string_cache;
72 private int[] table_indexes;
74 ModuleBuilderTokenGenerator token_gen;
75 Hashtable resource_writers;
76 ISymbolWriter symbolWriter;
78 [MethodImplAttribute(MethodImplOptions.InternalCall)]
79 private static extern void basic_init (ModuleBuilder ab);
81 [MethodImplAttribute(MethodImplOptions.InternalCall)]
82 private static extern void set_wrappers_type (ModuleBuilder mb, Type ab);
84 internal ModuleBuilder (AssemblyBuilder assb, string name, string fullyqname, bool emitSymbolInfo, bool transient) {
85 this.name = this.scopename = name;
86 this.fqname = fullyqname;
87 this.assembly = this.assemblyb = assb;
88 this.transient = transient;
89 // to keep mcs fast we do not want CryptoConfig wo be involved to create the RNG
90 guid = Guid.FastNewGuidArray ();
91 // guid = Guid.NewGuid().ToByteArray ();
92 table_idx = get_next_table_index (this, 0x00, true);
93 name_cache = new Hashtable ();
94 us_string_cache = new Dictionary<string, int> (512);
101 TypeBuilder tb = new TypeBuilder (this, TypeAttributes.Abstract, 0xFFFFFF); /*last valid token*/
102 Type type = tb.CreateType ();
103 set_wrappers_type (this, type);
106 if (emitSymbolInfo) {
108 symbolWriter = new Mono.CompilerServices.SymbolWriter.SymbolWriterImpl (this);
110 Assembly asm = Assembly.LoadWithPartialName ("Mono.CompilerServices.SymbolWriter");
112 throw new TypeLoadException ("The assembly for default symbol writer cannot be loaded");
114 Type t = asm.GetType ("Mono.CompilerServices.SymbolWriter.SymbolWriterImpl", true);
115 symbolWriter = (ISymbolWriter) Activator.CreateInstance (t, new object[] { this });
117 string fileName = fqname;
118 if (assemblyb.AssemblyDir != null)
119 fileName = Path.Combine (assemblyb.AssemblyDir, fileName);
120 symbolWriter.Initialize (IntPtr.Zero, fileName, true);
124 public override string FullyQualifiedName {get { return fqname;}}
126 public bool IsTransient () {
130 public void CreateGlobalFunctions ()
132 if (global_type_created != null)
133 throw new InvalidOperationException ("global methods already created");
134 if (global_type != null)
135 global_type_created = global_type.CreateType ();
138 public FieldBuilder DefineInitializedData( string name, byte[] data, FieldAttributes attributes) {
140 throw new ArgumentNullException ("data");
142 FieldBuilder fb = DefineUninitializedData (name, data.Length,
143 attributes | FieldAttributes.HasFieldRVA);
144 fb.SetRVAData (data);
149 public FieldBuilder DefineUninitializedData (string name, int size, FieldAttributes attributes)
152 throw new ArgumentNullException ("name");
153 if (global_type_created != null)
154 throw new InvalidOperationException ("global fields already created");
155 if ((size <= 0) || (size > 0x3f0000))
156 throw new ArgumentException ("size", "Data size must be > 0 and < 0x3f0000");
160 string typeName = "$ArrayType$" + size;
161 Type datablobtype = GetType (typeName, false, false);
162 if (datablobtype == null) {
163 TypeBuilder tb = DefineType (typeName,
164 TypeAttributes.Public|TypeAttributes.ExplicitLayout|TypeAttributes.Sealed,
165 assemblyb.corlib_value_type, null, PackingSize.Size1, size);
169 FieldBuilder fb = global_type.DefineField (name, datablobtype, attributes|FieldAttributes.Static);
171 if (global_fields != null) {
172 FieldBuilder[] new_fields = new FieldBuilder [global_fields.Length+1];
173 System.Array.Copy (global_fields, new_fields, global_fields.Length);
174 new_fields [global_fields.Length] = fb;
175 global_fields = new_fields;
177 global_fields = new FieldBuilder [1];
178 global_fields [0] = fb;
183 private void addGlobalMethod (MethodBuilder mb) {
184 if (global_methods != null) {
185 MethodBuilder[] new_methods = new MethodBuilder [global_methods.Length+1];
186 System.Array.Copy (global_methods, new_methods, global_methods.Length);
187 new_methods [global_methods.Length] = mb;
188 global_methods = new_methods;
190 global_methods = new MethodBuilder [1];
191 global_methods [0] = mb;
195 public MethodBuilder DefineGlobalMethod (string name, MethodAttributes attributes, Type returnType, Type[] parameterTypes)
197 return DefineGlobalMethod (name, attributes, CallingConventions.Standard, returnType, parameterTypes);
200 public MethodBuilder DefineGlobalMethod (string name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes) {
201 return DefineGlobalMethod (name, attributes, callingConvention, returnType, null, null, parameterTypes, null, null);
204 public MethodBuilder DefineGlobalMethod (string name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] requiredReturnTypeCustomModifiers, Type[] optionalReturnTypeCustomModifiers, Type[] parameterTypes, Type[][] requiredParameterTypeCustomModifiers, Type[][] optionalParameterTypeCustomModifiers)
207 throw new ArgumentNullException ("name");
208 if ((attributes & MethodAttributes.Static) == 0)
209 throw new ArgumentException ("global methods must be static");
210 if (global_type_created != null)
211 throw new InvalidOperationException ("global methods already created");
213 MethodBuilder mb = global_type.DefineMethod (name, attributes, callingConvention, returnType, requiredReturnTypeCustomModifiers, optionalReturnTypeCustomModifiers, parameterTypes, requiredParameterTypeCustomModifiers, optionalParameterTypeCustomModifiers);
215 addGlobalMethod (mb);
219 public MethodBuilder DefinePInvokeMethod (string name, string dllName, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes, CallingConvention nativeCallConv, CharSet nativeCharSet) {
220 return DefinePInvokeMethod (name, dllName, name, attributes, callingConvention, returnType, parameterTypes, nativeCallConv, nativeCharSet);
223 public MethodBuilder DefinePInvokeMethod (string name, string dllName, string entryName, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes, CallingConvention nativeCallConv, CharSet nativeCharSet) {
225 throw new ArgumentNullException ("name");
226 if ((attributes & MethodAttributes.Static) == 0)
227 throw new ArgumentException ("global methods must be static");
228 if (global_type_created != null)
229 throw new InvalidOperationException ("global methods already created");
231 MethodBuilder mb = global_type.DefinePInvokeMethod (name, dllName, entryName, attributes, callingConvention, returnType, parameterTypes, nativeCallConv, nativeCharSet);
233 addGlobalMethod (mb);
237 public TypeBuilder DefineType (string name) {
238 return DefineType (name, 0);
241 public TypeBuilder DefineType (string name, TypeAttributes attr) {
242 if ((attr & TypeAttributes.Interface) != 0)
243 return DefineType (name, attr, null, null);
244 return DefineType (name, attr, typeof(object), null);
247 public TypeBuilder DefineType (string name, TypeAttributes attr, Type parent) {
248 return DefineType (name, attr, parent, null);
251 private void AddType (TypeBuilder tb)
254 if (types.Length == num_types) {
255 TypeBuilder[] new_types = new TypeBuilder [types.Length * 2];
256 System.Array.Copy (types, new_types, num_types);
260 types = new TypeBuilder [1];
262 types [num_types] = tb;
266 private TypeBuilder DefineType (string name, TypeAttributes attr, Type parent, Type[] interfaces, PackingSize packingSize, int typesize) {
268 throw new ArgumentNullException ("fullname");
269 if (name_cache.ContainsKey (name))
270 throw new ArgumentException ("Duplicate type name within an assembly.");
271 TypeBuilder res = new TypeBuilder (this, name, attr, parent, interfaces, packingSize, typesize, null);
274 name_cache.Add (name, res);
279 internal void RegisterTypeName (TypeBuilder tb, string name)
281 name_cache.Add (name, tb);
284 internal TypeBuilder GetRegisteredType (string name)
286 return (TypeBuilder) name_cache [name];
290 public TypeBuilder DefineType (string name, TypeAttributes attr, Type parent, Type[] interfaces) {
291 return DefineType (name, attr, parent, interfaces, PackingSize.Unspecified, TypeBuilder.UnspecifiedTypeSize);
294 public TypeBuilder DefineType (string name, TypeAttributes attr, Type parent, int typesize) {
295 return DefineType (name, attr, parent, null, PackingSize.Unspecified, TypeBuilder.UnspecifiedTypeSize);
298 public TypeBuilder DefineType (string name, TypeAttributes attr, Type parent, PackingSize packsize) {
299 return DefineType (name, attr, parent, null, packsize, TypeBuilder.UnspecifiedTypeSize);
302 public TypeBuilder DefineType (string name, TypeAttributes attr, Type parent, PackingSize packingSize, int typesize) {
303 return DefineType (name, attr, parent, null, packingSize, typesize);
306 public MethodInfo GetArrayMethod( Type arrayClass, string methodName, CallingConventions callingConvention, Type returnType, Type[] parameterTypes) {
307 return new MonoArrayMethod (arrayClass, methodName, callingConvention, returnType, parameterTypes);
310 public EnumBuilder DefineEnum( string name, TypeAttributes visibility, Type underlyingType) {
311 if (name_cache.Contains (name))
312 throw new ArgumentException ("Duplicate type name within an assembly.");
314 EnumBuilder eb = new EnumBuilder (this, name, visibility, underlyingType);
315 TypeBuilder res = eb.GetTypeBuilder ();
317 name_cache.Add (name, res);
322 public override Type GetType( string className) {
323 return GetType (className, false, false);
327 public override Type GetType( string className, bool ignoreCase) {
328 return GetType (className, false, ignoreCase);
331 private TypeBuilder search_in_array (TypeBuilder[] arr, int validElementsInArray, string className) {
333 for (i = 0; i < validElementsInArray; ++i) {
334 if (String.Compare (className, arr [i].FullName, true, CultureInfo.InvariantCulture) == 0) {
341 private TypeBuilder search_nested_in_array (TypeBuilder[] arr, int validElementsInArray, string className) {
343 for (i = 0; i < validElementsInArray; ++i) {
344 if (String.Compare (className, arr [i].Name, true, CultureInfo.InvariantCulture) == 0)
350 [MethodImplAttribute(MethodImplOptions.InternalCall)]
351 private static extern Type create_modified_type (TypeBuilder tb, string modifiers);
353 static readonly char [] type_modifiers = {'&', '[', '*'};
355 private TypeBuilder GetMaybeNested (TypeBuilder t, string className) {
359 subt = className.IndexOf ('+');
361 if (t.subtypes != null)
362 return search_nested_in_array (t.subtypes, t.subtypes.Length, className);
365 if (t.subtypes != null) {
366 pname = className.Substring (0, subt);
367 rname = className.Substring (subt + 1);
368 TypeBuilder result = search_nested_in_array (t.subtypes, t.subtypes.Length, pname);
370 return GetMaybeNested (result, rname);
376 public override Type GetType (string className, bool throwOnError, bool ignoreCase)
378 if (className == null)
379 throw new ArgumentNullException ("className");
380 if (className.Length == 0)
381 throw new ArgumentException ("className");
384 string orig = className;
386 TypeBuilder result = null;
388 if (types == null && throwOnError)
389 throw new TypeLoadException (className);
391 subt = className.IndexOfAny (type_modifiers);
393 modifiers = className.Substring (subt);
394 className = className.Substring (0, subt);
399 result = name_cache [className] as TypeBuilder;
401 subt = className.IndexOf ('+');
404 result = search_in_array (types, num_types, className);
407 pname = className.Substring (0, subt);
408 rname = className.Substring (subt + 1);
409 result = search_in_array (types, num_types, pname);
411 result = GetMaybeNested (result, rname);
414 if ((result == null) && throwOnError)
415 throw new TypeLoadException (orig);
416 if (result != null && (modifiers != null)) {
417 Type mt = create_modified_type (result, modifiers);
418 result = mt as TypeBuilder;
422 if (result != null && result.is_created)
423 return result.CreateType ();
428 internal int get_next_table_index (object obj, int table, bool inc) {
429 if (table_indexes == null) {
430 table_indexes = new int [64];
431 for (int i=0; i < 64; ++i)
432 table_indexes [i] = 1;
433 /* allow room for .<Module> in TypeDef table */
434 table_indexes [0x02] = 2;
436 // Console.WriteLine ("getindex for table "+table.ToString()+" got "+table_indexes [table].ToString());
438 return table_indexes [table]++;
439 return table_indexes [table];
442 public void SetCustomAttribute( CustomAttributeBuilder customBuilder) {
443 if (cattrs != null) {
444 CustomAttributeBuilder[] new_array = new CustomAttributeBuilder [cattrs.Length + 1];
445 cattrs.CopyTo (new_array, 0);
446 new_array [cattrs.Length] = customBuilder;
449 cattrs = new CustomAttributeBuilder [1];
450 cattrs [0] = customBuilder;
455 public void SetCustomAttribute( ConstructorInfo con, byte[] binaryAttribute) {
456 SetCustomAttribute (new CustomAttributeBuilder (con, binaryAttribute));
459 public ISymbolWriter GetSymWriter () {
463 public ISymbolDocumentWriter DefineDocument (string url, Guid language, Guid languageVendor, Guid documentType)
465 if (symbolWriter != null)
466 return symbolWriter.DefineDocument (url, language, languageVendor, documentType);
471 public override Type [] GetTypes ()
474 return Type.EmptyTypes;
477 Type [] copy = new Type [n];
478 Array.Copy (types, copy, n);
480 // MS replaces the typebuilders with their created types
481 for (int i = 0; i < copy.Length; ++i)
482 if (types [i].is_created)
483 copy [i] = types [i].CreateType ();
488 public IResourceWriter DefineResource (string name, string description, ResourceAttributes attribute)
491 throw new ArgumentNullException ("name");
492 if (name == String.Empty)
493 throw new ArgumentException ("name cannot be empty");
495 throw new InvalidOperationException ("The module is transient");
496 if (!assemblyb.IsSave)
497 throw new InvalidOperationException ("The assembly is transient");
498 ResourceWriter writer = new ResourceWriter (new MemoryStream ());
499 if (resource_writers == null)
500 resource_writers = new Hashtable ();
501 resource_writers [name] = writer;
503 // The data is filled out later
504 if (resources != null) {
505 MonoResource[] new_r = new MonoResource [resources.Length + 1];
506 System.Array.Copy(resources, new_r, resources.Length);
509 resources = new MonoResource [1];
511 int p = resources.Length - 1;
512 resources [p].name = name;
513 resources [p].attrs = attribute;
518 public IResourceWriter DefineResource (string name, string description)
520 return DefineResource (name, description, ResourceAttributes.Public);
524 public void DefineUnmanagedResource (byte[] resource)
526 if (resource == null)
527 throw new ArgumentNullException ("resource");
529 throw new NotImplementedException ();
533 public void DefineUnmanagedResource (string resourceFileName)
535 if (resourceFileName == null)
536 throw new ArgumentNullException ("resourceFileName");
537 if (resourceFileName == String.Empty)
538 throw new ArgumentException ("resourceFileName");
539 if (!File.Exists (resourceFileName) || Directory.Exists (resourceFileName))
540 throw new FileNotFoundException ("File '" + resourceFileName + "' does not exists or is a directory.");
542 throw new NotImplementedException ();
545 public void DefineManifestResource (string name, Stream stream, ResourceAttributes attribute) {
547 throw new ArgumentNullException ("name");
548 if (name == String.Empty)
549 throw new ArgumentException ("name cannot be empty");
551 throw new ArgumentNullException ("stream");
553 throw new InvalidOperationException ("The module is transient");
554 if (!assemblyb.IsSave)
555 throw new InvalidOperationException ("The assembly is transient");
557 if (resources != null) {
558 MonoResource[] new_r = new MonoResource [resources.Length + 1];
559 System.Array.Copy(resources, new_r, resources.Length);
562 resources = new MonoResource [1];
564 int p = resources.Length - 1;
565 resources [p].name = name;
566 resources [p].attrs = attribute;
567 resources [p].stream = stream;
571 public void SetSymCustomAttribute (string name, byte[] data)
573 throw new NotImplementedException ();
577 public void SetUserEntryPoint (MethodInfo entryPoint)
579 if (entryPoint == null)
580 throw new ArgumentNullException ("entryPoint");
581 if (entryPoint.DeclaringType.Module != this)
582 throw new InvalidOperationException ("entryPoint is not contained in this module");
583 throw new NotImplementedException ();
586 public MethodToken GetMethodToken (MethodInfo method)
589 throw new ArgumentNullException ("method");
590 if (method.DeclaringType.Module != this)
591 throw new InvalidOperationException ("The method is not in this module");
592 return new MethodToken (GetToken (method));
595 public MethodToken GetArrayMethodToken (Type arrayClass, string methodName, CallingConventions callingConvention, Type returnType, Type[] parameterTypes)
597 return GetMethodToken (GetArrayMethod (arrayClass, methodName, callingConvention, returnType, parameterTypes));
601 public MethodToken GetConstructorToken (ConstructorInfo con)
604 throw new ArgumentNullException ("con");
605 if (con.DeclaringType.Module != this)
606 throw new InvalidOperationException ("The constructor is not in this module");
607 return new MethodToken (GetToken (con));
610 public FieldToken GetFieldToken (FieldInfo field)
613 throw new ArgumentNullException ("field");
614 if (field.DeclaringType.Module != this)
615 throw new InvalidOperationException ("The method is not in this module");
616 return new FieldToken (GetToken (field));
620 public SignatureToken GetSignatureToken (byte[] sigBytes, int sigLength)
622 throw new NotImplementedException ();
625 public SignatureToken GetSignatureToken (SignatureHelper sigHelper)
627 if (sigHelper == null)
628 throw new ArgumentNullException ("sigHelper");
629 return new SignatureToken (GetToken (sigHelper));
632 public StringToken GetStringConstant (string str)
635 throw new ArgumentNullException ("str");
636 return new StringToken (GetToken (str));
639 public TypeToken GetTypeToken (Type type)
642 throw new ArgumentNullException ("type");
644 throw new ArgumentException ("type can't be a byref type", "type");
645 if (!IsTransient () && (type.Module is ModuleBuilder) && ((ModuleBuilder)type.Module).IsTransient ())
646 throw new InvalidOperationException ("a non-transient module can't reference a transient module");
647 return new TypeToken (GetToken (type));
650 public TypeToken GetTypeToken (string name)
652 return GetTypeToken (GetType (name));
655 [MethodImplAttribute(MethodImplOptions.InternalCall)]
656 private static extern int getUSIndex (ModuleBuilder mb, string str);
658 [MethodImplAttribute(MethodImplOptions.InternalCall)]
659 private static extern int getToken (ModuleBuilder mb, object obj, bool create_open_instance);
661 [MethodImplAttribute(MethodImplOptions.InternalCall)]
662 private static extern int getMethodToken (ModuleBuilder mb, MethodInfo method,
663 Type[] opt_param_types);
665 internal int GetToken (string str)
668 if (!us_string_cache.TryGetValue (str, out result)) {
669 result = getUSIndex (this, str);
670 us_string_cache [str] = result;
676 internal int GetToken (MemberInfo member) {
677 return getToken (this, member, true);
680 internal int GetToken (MemberInfo member, bool create_open_instance) {
681 return getToken (this, member, create_open_instance);
684 internal int GetToken (MethodInfo method, Type[] opt_param_types) {
685 return getMethodToken (this, method, opt_param_types);
688 internal int GetToken (SignatureHelper helper) {
689 return getToken (this, helper, true);
693 * Register the token->obj mapping with the runtime so the Module.Resolve...
694 * methods will work for obj.
696 [MethodImplAttribute(MethodImplOptions.InternalCall)]
697 internal extern void RegisterToken (object obj, int token);
699 internal TokenGenerator GetTokenGenerator () {
700 if (token_gen == null)
701 token_gen = new ModuleBuilderTokenGenerator (this);
705 [MethodImplAttribute(MethodImplOptions.InternalCall)]
706 private static extern void build_metadata (ModuleBuilder mb);
708 [MethodImplAttribute(MethodImplOptions.InternalCall)]
709 private extern void WriteToFile (IntPtr handle);
711 internal void Save ()
713 if (transient && !is_main)
717 for (int i = 0; i < num_types; ++i)
718 if (!types [i].is_created)
719 throw new NotSupportedException ("Type '" + types [i].FullName + "' was not completed.");
722 if ((global_type != null) && (global_type_created == null))
723 global_type_created = global_type.CreateType ();
725 if (resources != null) {
726 for (int i = 0; i < resources.Length; ++i) {
727 IResourceWriter rwriter;
728 if (resource_writers != null && (rwriter = resource_writers [resources [i].name] as IResourceWriter) != null) {
729 ResourceWriter writer = (ResourceWriter)rwriter;
731 MemoryStream mstream = (MemoryStream)writer.Stream;
732 resources [i].data = new byte [mstream.Length];
733 mstream.Seek (0, SeekOrigin.Begin);
734 mstream.Read (resources [i].data, 0, (int)mstream.Length);
737 Stream stream = resources [i].stream;
739 // According to MSDN docs, the stream is read during assembly save, not earlier
740 if (stream != null) {
742 long len = stream.Length;
743 resources [i].data = new byte [len];
744 stream.Seek (0, SeekOrigin.Begin);
745 stream.Read (resources [i].data, 0, (int)len);
753 build_metadata (this);
755 string fileName = fqname;
756 if (assemblyb.AssemblyDir != null)
757 fileName = Path.Combine (assemblyb.AssemblyDir, fileName);
760 // We mmap the file, so unlink the previous version since it may be in use
761 File.Delete (fileName);
763 // We can safely ignore
765 using (FileStream file = new FileStream (fileName, FileMode.Create, FileAccess.Write))
766 WriteToFile (file.Handle);
769 // The constant 0x80000000 is internal to Mono, it means `make executable'
771 File.SetAttributes (fileName, (FileAttributes) (unchecked ((int) 0x80000000)));
773 if (types != null && symbolWriter != null) {
774 for (int i = 0; i < num_types; ++i)
775 types [i].GenerateDebugInfo (symbolWriter);
776 symbolWriter.Close ();
780 internal string FileName {
786 internal bool IsMain {
792 internal void CreateGlobalType () {
793 if (global_type == null)
794 global_type = new TypeBuilder (this, 0, 1);
797 internal override Guid GetModuleVersionId ()
799 return new Guid (guid);
802 // Used by mcs, the symbol writer, and mdb through reflection
803 internal static Guid Mono_GetGuid (ModuleBuilder mb)
805 return mb.GetModuleVersionId ();
808 void _ModuleBuilder.GetIDsOfNames ([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
810 throw new NotImplementedException ();
813 void _ModuleBuilder.GetTypeInfo (uint iTInfo, uint lcid, IntPtr ppTInfo)
815 throw new NotImplementedException ();
818 void _ModuleBuilder.GetTypeInfoCount (out uint pcTInfo)
820 throw new NotImplementedException ();
823 void _ModuleBuilder.Invoke (uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
825 throw new NotImplementedException ();
828 #if NET_4_0 || MOONLIGHT || MOBILE
829 public override Assembly Assembly {
830 get { return assemblyb; }
833 public override string Name {
837 public override string ScopeName {
841 public override Guid ModuleVersionId {
843 return GetModuleVersionId ();
847 //XXX resource modules can't be defined with ModuleBuilder
848 public override bool IsResource ()
853 protected override MethodInfo GetMethodImpl (string name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers)
855 if (global_type_created == null)
858 return global_type_created.GetMethod (name);
859 return global_type_created.GetMethod (name, bindingAttr, binder, callConvention, types, modifiers);
862 public override FieldInfo ResolveField (int metadataToken, Type [] genericTypeArguments, Type [] genericMethodArguments) {
863 ResolveTokenError error;
865 IntPtr handle = ResolveFieldToken (_impl, metadataToken, ptrs_from_types (genericTypeArguments), ptrs_from_types (genericMethodArguments), out error);
866 if (handle == IntPtr.Zero)
867 throw resolve_token_exception (metadataToken, error, "Field");
869 return FieldInfo.GetFieldFromHandle (new RuntimeFieldHandle (handle));
872 public override MemberInfo ResolveMember (int metadataToken, Type [] genericTypeArguments, Type [] genericMethodArguments) {
874 ResolveTokenError error;
876 MemberInfo m = ResolveMemberToken (_impl, metadataToken, ptrs_from_types (genericTypeArguments), ptrs_from_types (genericMethodArguments), out error);
878 throw resolve_token_exception (metadataToken, error, "MemberInfo");
883 public override MethodBase ResolveMethod (int metadataToken, Type [] genericTypeArguments, Type [] genericMethodArguments) {
884 ResolveTokenError error;
886 IntPtr handle = ResolveMethodToken (_impl, metadataToken, ptrs_from_types (genericTypeArguments), ptrs_from_types (genericMethodArguments), out error);
887 if (handle == IntPtr.Zero)
888 throw resolve_token_exception (metadataToken, error, "MethodBase");
890 return MethodBase.GetMethodFromHandleNoGenericCheck (new RuntimeMethodHandle (handle));
893 public override string ResolveString (int metadataToken) {
894 ResolveTokenError error;
896 string s = ResolveStringToken (_impl, metadataToken, out error);
898 throw resolve_token_exception (metadataToken, error, "string");
903 public override byte[] ResolveSignature (int metadataToken) {
904 ResolveTokenError error;
906 byte[] res = ResolveSignature (_impl, metadataToken, out error);
908 throw resolve_token_exception (metadataToken, error, "signature");
913 public override Type ResolveType (int metadataToken, Type [] genericTypeArguments, Type [] genericMethodArguments) {
914 ResolveTokenError error;
916 IntPtr handle = ResolveTypeToken (_impl, metadataToken, ptrs_from_types (genericTypeArguments), ptrs_from_types (genericMethodArguments), out error);
917 if (handle == IntPtr.Zero)
918 throw resolve_token_exception (metadataToken, error, "Type");
920 return Type.GetTypeFromHandle (new RuntimeTypeHandle (handle));
923 public override bool Equals (object obj)
925 return base.Equals (obj);
928 public override int GetHashCode ()
930 return base.GetHashCode ();
933 public override bool IsDefined (Type attributeType, bool inherit)
935 return base.IsDefined (attributeType, inherit);
938 public override object[] GetCustomAttributes (bool inherit)
940 return base.GetCustomAttributes (inherit);
943 public override object[] GetCustomAttributes (Type attributeType, bool inherit)
945 return base.GetCustomAttributes (attributeType, inherit);
948 public override FieldInfo GetField (string name, BindingFlags bindingAttr)
950 return base.GetField (name, bindingAttr);
953 public override FieldInfo[] GetFields (BindingFlags bindingFlags)
955 return base.GetFields (bindingFlags);
958 public override MethodInfo[] GetMethods (BindingFlags bindingFlags)
960 return base.GetMethods (bindingFlags);
963 public override int MetadataToken {
965 return base.MetadataToken;
971 internal class ModuleBuilderTokenGenerator : TokenGenerator {
973 private ModuleBuilder mb;
975 public ModuleBuilderTokenGenerator (ModuleBuilder mb) {
979 public int GetToken (string str) {
980 return mb.GetToken (str);
983 public int GetToken (MemberInfo member, bool create_open_instance) {
984 return mb.GetToken (member, create_open_instance);
987 public int GetToken (MethodInfo method, Type[] opt_param_types) {
988 return mb.GetToken (method, opt_param_types);
991 public int GetToken (SignatureHelper helper) {
992 return mb.GetToken (helper);