2 // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
4 // Permission is hereby granted, free of charge, to any person obtaining
5 // a copy of this software and associated documentation files (the
6 // "Software"), to deal in the Software without restriction, including
7 // without limitation the rights to use, copy, modify, merge, publish,
8 // distribute, sublicense, and/or sell copies of the Software, and to
9 // permit persons to whom the Software is furnished to do so, subject to
10 // the following conditions:
12 // The above copyright notice and this permission notice shall be
13 // included in all copies or substantial portions of the Software.
15 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
25 // System.Reflection.Emit/ModuleBuilder.cs
28 // Paolo Molaro (lupus@ximian.com)
30 // (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;
70 // name_cache keys are display names
71 Dictionary<TypeName, TypeBuilder> name_cache;
72 Dictionary<string, int> us_string_cache;
73 private int[] table_indexes;
75 ModuleBuilderTokenGenerator token_gen;
76 Hashtable resource_writers;
77 ISymbolWriter symbolWriter;
79 [MethodImplAttribute(MethodImplOptions.InternalCall)]
80 private static extern void basic_init (ModuleBuilder ab);
82 [MethodImplAttribute(MethodImplOptions.InternalCall)]
83 private static extern void set_wrappers_type (ModuleBuilder mb, Type ab);
85 internal ModuleBuilder (AssemblyBuilder assb, string name, string fullyqname, bool emitSymbolInfo, bool transient) {
86 this.name = this.scopename = name;
87 this.fqname = fullyqname;
88 this.assembly = this.assemblyb = assb;
89 this.transient = transient;
90 // to keep mcs fast we do not want CryptoConfig wo be involved to create the RNG
91 guid = Guid.FastNewGuidArray ();
92 // guid = Guid.NewGuid().ToByteArray ();
93 table_idx = get_next_table_index (this, 0x00, true);
94 name_cache = new Dictionary<TypeName, TypeBuilder> ();
95 us_string_cache = new Dictionary<string, int> (512);
102 TypeBuilder tb = new TypeBuilder (this, TypeAttributes.Abstract, 0xFFFFFF); /*last valid token*/
103 Type type = tb.CreateType ();
104 set_wrappers_type (this, type);
107 if (emitSymbolInfo) {
108 Assembly asm = Assembly.LoadWithPartialName ("Mono.CompilerServices.SymbolWriter");
110 throw new TypeLoadException ("The assembly for default symbol writer cannot be loaded");
112 Type t = asm.GetType ("Mono.CompilerServices.SymbolWriter.SymbolWriterImpl", true);
113 symbolWriter = (ISymbolWriter) Activator.CreateInstance (t, new object[] { this });
114 string fileName = fqname;
115 if (assemblyb.AssemblyDir != null)
116 fileName = Path.Combine (assemblyb.AssemblyDir, fileName);
117 symbolWriter.Initialize (IntPtr.Zero, fileName, true);
121 public override string FullyQualifiedName {get { return fqname;}}
123 public bool IsTransient () {
127 public void CreateGlobalFunctions ()
129 if (global_type_created != null)
130 throw new InvalidOperationException ("global methods already created");
131 if (global_type != null)
132 global_type_created = global_type.CreateType ();
135 public FieldBuilder DefineInitializedData( string name, byte[] data, FieldAttributes attributes) {
137 throw new ArgumentNullException ("data");
139 FieldBuilder fb = DefineUninitializedData (name, data.Length,
140 attributes | FieldAttributes.HasFieldRVA);
141 fb.SetRVAData (data);
146 public FieldBuilder DefineUninitializedData (string name, int size, FieldAttributes attributes)
149 throw new ArgumentNullException ("name");
150 if (global_type_created != null)
151 throw new InvalidOperationException ("global fields already created");
152 if ((size <= 0) || (size > 0x3f0000))
153 throw new ArgumentException ("size", "Data size must be > 0 and < 0x3f0000");
157 string typeName = "$ArrayType$" + size;
158 Type datablobtype = GetType (typeName, false, false);
159 if (datablobtype == null) {
160 TypeBuilder tb = DefineType (typeName,
161 TypeAttributes.Public|TypeAttributes.ExplicitLayout|TypeAttributes.Sealed,
162 assemblyb.corlib_value_type, null, PackingSize.Size1, size);
166 FieldBuilder fb = global_type.DefineField (name, datablobtype, attributes|FieldAttributes.Static);
168 if (global_fields != null) {
169 FieldBuilder[] new_fields = new FieldBuilder [global_fields.Length+1];
170 System.Array.Copy (global_fields, new_fields, global_fields.Length);
171 new_fields [global_fields.Length] = fb;
172 global_fields = new_fields;
174 global_fields = new FieldBuilder [1];
175 global_fields [0] = fb;
180 private void addGlobalMethod (MethodBuilder mb) {
181 if (global_methods != null) {
182 MethodBuilder[] new_methods = new MethodBuilder [global_methods.Length+1];
183 System.Array.Copy (global_methods, new_methods, global_methods.Length);
184 new_methods [global_methods.Length] = mb;
185 global_methods = new_methods;
187 global_methods = new MethodBuilder [1];
188 global_methods [0] = mb;
192 public MethodBuilder DefineGlobalMethod (string name, MethodAttributes attributes, Type returnType, Type[] parameterTypes)
194 return DefineGlobalMethod (name, attributes, CallingConventions.Standard, returnType, parameterTypes);
197 public MethodBuilder DefineGlobalMethod (string name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes) {
198 return DefineGlobalMethod (name, attributes, callingConvention, returnType, null, null, parameterTypes, null, null);
201 public MethodBuilder DefineGlobalMethod (string name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] requiredReturnTypeCustomModifiers, Type[] optionalReturnTypeCustomModifiers, Type[] parameterTypes, Type[][] requiredParameterTypeCustomModifiers, Type[][] optionalParameterTypeCustomModifiers)
204 throw new ArgumentNullException ("name");
205 if ((attributes & MethodAttributes.Static) == 0)
206 throw new ArgumentException ("global methods must be static");
207 if (global_type_created != null)
208 throw new InvalidOperationException ("global methods already created");
210 MethodBuilder mb = global_type.DefineMethod (name, attributes, callingConvention, returnType, requiredReturnTypeCustomModifiers, optionalReturnTypeCustomModifiers, parameterTypes, requiredParameterTypeCustomModifiers, optionalParameterTypeCustomModifiers);
212 addGlobalMethod (mb);
216 public MethodBuilder DefinePInvokeMethod (string name, string dllName, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes, CallingConvention nativeCallConv, CharSet nativeCharSet) {
217 return DefinePInvokeMethod (name, dllName, name, attributes, callingConvention, returnType, parameterTypes, nativeCallConv, nativeCharSet);
220 public MethodBuilder DefinePInvokeMethod (string name, string dllName, string entryName, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes, CallingConvention nativeCallConv, CharSet nativeCharSet) {
222 throw new ArgumentNullException ("name");
223 if ((attributes & MethodAttributes.Static) == 0)
224 throw new ArgumentException ("global methods must be static");
225 if (global_type_created != null)
226 throw new InvalidOperationException ("global methods already created");
228 MethodBuilder mb = global_type.DefinePInvokeMethod (name, dllName, entryName, attributes, callingConvention, returnType, parameterTypes, nativeCallConv, nativeCharSet);
230 addGlobalMethod (mb);
234 public TypeBuilder DefineType (string name) {
235 return DefineType (name, 0);
238 public TypeBuilder DefineType (string name, TypeAttributes attr) {
239 if ((attr & TypeAttributes.Interface) != 0)
240 return DefineType (name, attr, null, null);
241 return DefineType (name, attr, typeof(object), null);
244 public TypeBuilder DefineType (string name, TypeAttributes attr, Type parent) {
245 return DefineType (name, attr, parent, null);
248 private void AddType (TypeBuilder tb)
251 if (types.Length == num_types) {
252 TypeBuilder[] new_types = new TypeBuilder [types.Length * 2];
253 System.Array.Copy (types, new_types, num_types);
257 types = new TypeBuilder [1];
259 types [num_types] = tb;
263 private TypeBuilder DefineType (string name, TypeAttributes attr, Type parent, Type[] interfaces, PackingSize packingSize, int typesize) {
265 throw new ArgumentNullException ("fullname");
266 TypeIdentifier ident = TypeIdentifiers.FromInternal (name);
267 if (name_cache.ContainsKey (ident))
268 throw new ArgumentException ("Duplicate type name within an assembly.");
269 TypeBuilder res = new TypeBuilder (this, name, attr, parent, interfaces, packingSize, typesize, null);
272 name_cache.Add (ident, res);
277 internal void RegisterTypeName (TypeBuilder tb, TypeName name)
279 name_cache.Add (name, tb);
282 internal TypeBuilder GetRegisteredType (TypeName name)
284 TypeBuilder result = null;
285 name_cache.TryGetValue (name, out result);
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, typesize);
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 TypeIdentifier ident = TypeIdentifiers.FromInternal (name);
312 if (name_cache.ContainsKey (ident))
313 throw new ArgumentException ("Duplicate type name within an assembly.");
315 EnumBuilder eb = new EnumBuilder (this, name, visibility, underlyingType);
316 TypeBuilder res = eb.GetTypeBuilder ();
318 name_cache.Add (ident, res);
323 public override Type GetType( string className) {
324 return GetType (className, false, false);
328 public override Type GetType( string className, bool ignoreCase) {
329 return GetType (className, false, ignoreCase);
332 private TypeBuilder search_in_array (TypeBuilder[] arr, int validElementsInArray, TypeName className) {
334 for (i = 0; i < validElementsInArray; ++i) {
335 if (String.Compare (className.DisplayName, arr [i].FullName, true, CultureInfo.InvariantCulture) == 0) {
342 private TypeBuilder search_nested_in_array (TypeBuilder[] arr, int validElementsInArray, TypeName className) {
344 for (i = 0; i < validElementsInArray; ++i) {
345 if (String.Compare (className.DisplayName, arr [i].Name, true, CultureInfo.InvariantCulture) == 0)
351 [MethodImplAttribute(MethodImplOptions.InternalCall)]
352 private static extern Type create_modified_type (TypeBuilder tb, string modifiers);
354 private TypeBuilder GetMaybeNested (TypeBuilder t, IEnumerable<TypeName> nested) {
355 TypeBuilder result = t;
357 foreach (TypeName pname in nested) {
358 if (result.subtypes == null)
360 result = search_nested_in_array(result.subtypes, result.subtypes.Length, pname);
368 public override Type GetType (string className, bool throwOnError, bool ignoreCase)
370 if (className == null)
371 throw new ArgumentNullException ("className");
372 if (className.Length == 0)
373 throw new ArgumentException ("className");
375 TypeBuilder result = null;
377 if (types == null && throwOnError)
378 throw new TypeLoadException (className);
380 TypeSpec ts = TypeSpec.Parse (className);
383 var displayNestedName = ts.TypeNameWithoutModifiers();
384 name_cache.TryGetValue (displayNestedName, out result);
387 result = search_in_array (types, num_types, ts.Name);
388 if (!ts.IsNested && result != null) {
389 result = GetMaybeNested (result, ts.Nested);
392 if ((result == null) && throwOnError)
393 throw new TypeLoadException (className);
394 if (result != null && (ts.HasModifiers || ts.IsByRef)) {
395 string modifiers = ts.ModifierString ();
396 Type mt = create_modified_type (result, modifiers);
397 result = mt as TypeBuilder;
401 if (result != null && result.is_created)
402 return result.CreateType ();
407 internal int get_next_table_index (object obj, int table, bool inc) {
408 if (table_indexes == null) {
409 table_indexes = new int [64];
410 for (int i=0; i < 64; ++i)
411 table_indexes [i] = 1;
412 /* allow room for .<Module> in TypeDef table */
413 table_indexes [0x02] = 2;
415 // Console.WriteLine ("getindex for table "+table.ToString()+" got "+table_indexes [table].ToString());
417 return table_indexes [table]++;
418 return table_indexes [table];
421 public void SetCustomAttribute( CustomAttributeBuilder customBuilder) {
422 if (cattrs != null) {
423 CustomAttributeBuilder[] new_array = new CustomAttributeBuilder [cattrs.Length + 1];
424 cattrs.CopyTo (new_array, 0);
425 new_array [cattrs.Length] = customBuilder;
428 cattrs = new CustomAttributeBuilder [1];
429 cattrs [0] = customBuilder;
434 public void SetCustomAttribute( ConstructorInfo con, byte[] binaryAttribute) {
435 SetCustomAttribute (new CustomAttributeBuilder (con, binaryAttribute));
438 public ISymbolWriter GetSymWriter () {
442 public ISymbolDocumentWriter DefineDocument (string url, Guid language, Guid languageVendor, Guid documentType)
444 if (symbolWriter != null)
445 return symbolWriter.DefineDocument (url, language, languageVendor, documentType);
450 public override Type [] GetTypes ()
453 return Type.EmptyTypes;
456 Type [] copy = new Type [n];
457 Array.Copy (types, copy, n);
459 // MS replaces the typebuilders with their created types
460 for (int i = 0; i < copy.Length; ++i)
461 if (types [i].is_created)
462 copy [i] = types [i].CreateType ();
467 public IResourceWriter DefineResource (string name, string description, ResourceAttributes attribute)
470 throw new ArgumentNullException ("name");
471 if (name == String.Empty)
472 throw new ArgumentException ("name cannot be empty");
474 throw new InvalidOperationException ("The module is transient");
475 if (!assemblyb.IsSave)
476 throw new InvalidOperationException ("The assembly is transient");
477 ResourceWriter writer = new ResourceWriter (new MemoryStream ());
478 if (resource_writers == null)
479 resource_writers = new Hashtable ();
480 resource_writers [name] = writer;
482 // The data is filled out later
483 if (resources != null) {
484 MonoResource[] new_r = new MonoResource [resources.Length + 1];
485 System.Array.Copy(resources, new_r, resources.Length);
488 resources = new MonoResource [1];
490 int p = resources.Length - 1;
491 resources [p].name = name;
492 resources [p].attrs = attribute;
497 public IResourceWriter DefineResource (string name, string description)
499 return DefineResource (name, description, ResourceAttributes.Public);
503 public void DefineUnmanagedResource (byte[] resource)
505 if (resource == null)
506 throw new ArgumentNullException ("resource");
508 throw new NotImplementedException ();
512 public void DefineUnmanagedResource (string resourceFileName)
514 if (resourceFileName == null)
515 throw new ArgumentNullException ("resourceFileName");
516 if (resourceFileName == String.Empty)
517 throw new ArgumentException ("resourceFileName");
518 if (!File.Exists (resourceFileName) || Directory.Exists (resourceFileName))
519 throw new FileNotFoundException ("File '" + resourceFileName + "' does not exist or is a directory.");
521 throw new NotImplementedException ();
524 public void DefineManifestResource (string name, Stream stream, ResourceAttributes attribute) {
526 throw new ArgumentNullException ("name");
527 if (name == String.Empty)
528 throw new ArgumentException ("name cannot be empty");
530 throw new ArgumentNullException ("stream");
532 throw new InvalidOperationException ("The module is transient");
533 if (!assemblyb.IsSave)
534 throw new InvalidOperationException ("The assembly is transient");
536 if (resources != null) {
537 MonoResource[] new_r = new MonoResource [resources.Length + 1];
538 System.Array.Copy(resources, new_r, resources.Length);
541 resources = new MonoResource [1];
543 int p = resources.Length - 1;
544 resources [p].name = name;
545 resources [p].attrs = attribute;
546 resources [p].stream = stream;
550 public void SetSymCustomAttribute (string name, byte[] data)
552 throw new NotImplementedException ();
556 public void SetUserEntryPoint (MethodInfo entryPoint)
558 if (entryPoint == null)
559 throw new ArgumentNullException ("entryPoint");
560 if (entryPoint.DeclaringType.Module != this)
561 throw new InvalidOperationException ("entryPoint is not contained in this module");
562 throw new NotImplementedException ();
565 public MethodToken GetMethodToken (MethodInfo method)
568 throw new ArgumentNullException ("method");
570 return new MethodToken (GetToken (method));
573 public MethodToken GetMethodToken (MethodInfo method, IEnumerable<Type> optionalParameterTypes)
576 throw new ArgumentNullException ("method");
578 return new MethodToken (GetToken (method, optionalParameterTypes));
581 public MethodToken GetArrayMethodToken (Type arrayClass, string methodName, CallingConventions callingConvention, Type returnType, Type[] parameterTypes)
583 return GetMethodToken (GetArrayMethod (arrayClass, methodName, callingConvention, returnType, parameterTypes));
587 public MethodToken GetConstructorToken (ConstructorInfo con)
590 throw new ArgumentNullException ("con");
592 return new MethodToken (GetToken (con));
595 public MethodToken GetConstructorToken (ConstructorInfo constructor, IEnumerable<Type> optionalParameterTypes)
597 if (constructor == null)
598 throw new ArgumentNullException ("constructor");
600 return new MethodToken (GetToken (constructor, optionalParameterTypes));
603 public FieldToken GetFieldToken (FieldInfo field)
606 throw new ArgumentNullException ("field");
608 return new FieldToken (GetToken (field));
612 public SignatureToken GetSignatureToken (byte[] sigBytes, int sigLength)
614 throw new NotImplementedException ();
617 public SignatureToken GetSignatureToken (SignatureHelper sigHelper)
619 if (sigHelper == null)
620 throw new ArgumentNullException ("sigHelper");
621 return new SignatureToken (GetToken (sigHelper));
624 public StringToken GetStringConstant (string str)
627 throw new ArgumentNullException ("str");
628 return new StringToken (GetToken (str));
631 public TypeToken GetTypeToken (Type type)
634 throw new ArgumentNullException ("type");
636 throw new ArgumentException ("type can't be a byref type", "type");
637 if (!IsTransient () && (type.Module is ModuleBuilder) && ((ModuleBuilder)type.Module).IsTransient ())
638 throw new InvalidOperationException ("a non-transient module can't reference a transient module");
639 return new TypeToken (GetToken (type));
642 public TypeToken GetTypeToken (string name)
644 return GetTypeToken (GetType (name));
647 [MethodImplAttribute(MethodImplOptions.InternalCall)]
648 private static extern int getUSIndex (ModuleBuilder mb, string str);
650 [MethodImplAttribute(MethodImplOptions.InternalCall)]
651 private static extern int getToken (ModuleBuilder mb, object obj, bool create_open_instance);
653 [MethodImplAttribute(MethodImplOptions.InternalCall)]
654 private static extern int getMethodToken (ModuleBuilder mb, MethodBase method,
655 Type[] opt_param_types);
657 internal int GetToken (string str)
660 if (!us_string_cache.TryGetValue (str, out result)) {
661 result = getUSIndex (this, str);
662 us_string_cache [str] = result;
668 internal int GetToken (MemberInfo member) {
669 return getToken (this, member, true);
672 internal int GetToken (MemberInfo member, bool create_open_instance) {
673 return getToken (this, member, create_open_instance);
676 internal int GetToken (MethodBase method, IEnumerable<Type> opt_param_types) {
677 if (opt_param_types == null)
678 return getToken (this, method, true);
680 var optParamTypes = new List<Type> (opt_param_types);
681 return getMethodToken (this, method, optParamTypes.ToArray ());
684 internal int GetToken (MethodBase 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);
700 * Returns MemberInfo registered with the given token.
702 [MethodImplAttribute(MethodImplOptions.InternalCall)]
703 internal extern object GetRegisteredToken (int token);
705 internal TokenGenerator GetTokenGenerator () {
706 if (token_gen == null)
707 token_gen = new ModuleBuilderTokenGenerator (this);
711 [MethodImplAttribute(MethodImplOptions.InternalCall)]
712 private static extern void build_metadata (ModuleBuilder mb);
714 [MethodImplAttribute(MethodImplOptions.InternalCall)]
715 private extern void WriteToFile (IntPtr handle);
717 internal void Save ()
719 if (transient && !is_main)
723 for (int i = 0; i < num_types; ++i)
724 if (!types [i].is_created)
725 throw new NotSupportedException ("Type '" + types [i].FullName + "' was not completed.");
728 if ((global_type != null) && (global_type_created == null))
729 global_type_created = global_type.CreateType ();
731 if (resources != null) {
732 for (int i = 0; i < resources.Length; ++i) {
733 IResourceWriter rwriter;
734 if (resource_writers != null && (rwriter = resource_writers [resources [i].name] as IResourceWriter) != null) {
735 ResourceWriter writer = (ResourceWriter)rwriter;
737 MemoryStream mstream = (MemoryStream)writer._output;
738 resources [i].data = new byte [mstream.Length];
739 mstream.Seek (0, SeekOrigin.Begin);
740 mstream.Read (resources [i].data, 0, (int)mstream.Length);
743 Stream stream = resources [i].stream;
745 // According to MSDN docs, the stream is read during assembly save, not earlier
746 if (stream != null) {
748 long len = stream.Length;
749 resources [i].data = new byte [len];
750 stream.Seek (0, SeekOrigin.Begin);
751 stream.Read (resources [i].data, 0, (int)len);
759 build_metadata (this);
761 string fileName = fqname;
762 if (assemblyb.AssemblyDir != null)
763 fileName = Path.Combine (assemblyb.AssemblyDir, fileName);
766 // We mmap the file, so unlink the previous version since it may be in use
767 File.Delete (fileName);
769 // We can safely ignore
771 using (FileStream file = new FileStream (fileName, FileMode.Create, FileAccess.Write))
772 WriteToFile (file.Handle);
775 // The constant 0x80000000 is internal to Mono, it means `make executable'
777 File.SetAttributes (fileName, (FileAttributes) (unchecked ((int) 0x80000000)));
779 if (types != null && symbolWriter != null) {
780 for (int i = 0; i < num_types; ++i)
781 types [i].GenerateDebugInfo (symbolWriter);
782 symbolWriter.Close ();
786 internal string FileName {
792 internal bool IsMain {
798 internal void CreateGlobalType () {
799 if (global_type == null)
800 global_type = new TypeBuilder (this, 0, 1);
803 internal override Guid GetModuleVersionId ()
805 return new Guid (guid);
808 // Used by mcs, the symbol writer, and mdb through reflection
809 internal static Guid Mono_GetGuid (ModuleBuilder mb)
811 return mb.GetModuleVersionId ();
814 void _ModuleBuilder.GetIDsOfNames ([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
816 throw new NotImplementedException ();
819 void _ModuleBuilder.GetTypeInfo (uint iTInfo, uint lcid, IntPtr ppTInfo)
821 throw new NotImplementedException ();
824 void _ModuleBuilder.GetTypeInfoCount (out uint pcTInfo)
826 throw new NotImplementedException ();
829 void _ModuleBuilder.Invoke (uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
831 throw new NotImplementedException ();
834 public override Assembly Assembly {
835 get { return assemblyb; }
838 public override string Name {
842 public override string ScopeName {
846 public override Guid ModuleVersionId {
848 return GetModuleVersionId ();
852 //XXX resource modules can't be defined with ModuleBuilder
853 public override bool IsResource ()
858 protected override MethodInfo GetMethodImpl (string name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers)
860 if (global_type_created == null)
863 return global_type_created.GetMethod (name);
864 return global_type_created.GetMethod (name, bindingAttr, binder, callConvention, types, modifiers);
867 public override FieldInfo ResolveField (int metadataToken, Type [] genericTypeArguments, Type [] genericMethodArguments) {
868 ResolveTokenError error;
870 IntPtr handle = ResolveFieldToken (_impl, metadataToken, ptrs_from_types (genericTypeArguments), ptrs_from_types (genericMethodArguments), out error);
871 if (handle == IntPtr.Zero)
872 throw resolve_token_exception (metadataToken, error, "Field");
874 return FieldInfo.GetFieldFromHandle (new RuntimeFieldHandle (handle));
877 public override MemberInfo ResolveMember (int metadataToken, Type [] genericTypeArguments, Type [] genericMethodArguments) {
879 ResolveTokenError error;
881 MemberInfo m = ResolveMemberToken (_impl, metadataToken, ptrs_from_types (genericTypeArguments), ptrs_from_types (genericMethodArguments), out error);
883 throw resolve_token_exception (metadataToken, error, "MemberInfo");
888 internal MemberInfo ResolveOrGetRegisteredToken (int metadataToken, Type [] genericTypeArguments, Type [] genericMethodArguments)
890 ResolveTokenError error;
891 MemberInfo m = ResolveMemberToken (_impl, metadataToken, ptrs_from_types (genericTypeArguments), ptrs_from_types (genericMethodArguments), out error);
895 m = GetRegisteredToken (metadataToken) as MemberInfo;
897 throw resolve_token_exception (metadataToken, error, "MemberInfo");
902 public override MethodBase ResolveMethod (int metadataToken, Type [] genericTypeArguments, Type [] genericMethodArguments) {
903 ResolveTokenError error;
905 IntPtr handle = ResolveMethodToken (_impl, metadataToken, ptrs_from_types (genericTypeArguments), ptrs_from_types (genericMethodArguments), out error);
906 if (handle == IntPtr.Zero)
907 throw resolve_token_exception (metadataToken, error, "MethodBase");
909 return MethodBase.GetMethodFromHandleNoGenericCheck (new RuntimeMethodHandle (handle));
912 public override string ResolveString (int metadataToken) {
913 ResolveTokenError error;
915 string s = ResolveStringToken (_impl, metadataToken, out error);
917 throw resolve_token_exception (metadataToken, error, "string");
922 public override byte[] ResolveSignature (int metadataToken) {
923 ResolveTokenError error;
925 byte[] res = ResolveSignature (_impl, metadataToken, out error);
927 throw resolve_token_exception (metadataToken, error, "signature");
932 public override Type ResolveType (int metadataToken, Type [] genericTypeArguments, Type [] genericMethodArguments) {
933 ResolveTokenError error;
935 IntPtr handle = ResolveTypeToken (_impl, metadataToken, ptrs_from_types (genericTypeArguments), ptrs_from_types (genericMethodArguments), out error);
936 if (handle == IntPtr.Zero)
937 throw resolve_token_exception (metadataToken, error, "Type");
939 return Type.GetTypeFromHandle (new RuntimeTypeHandle (handle));
942 public override bool Equals (object obj)
944 return base.Equals (obj);
947 public override int GetHashCode ()
949 return base.GetHashCode ();
952 public override bool IsDefined (Type attributeType, bool inherit)
954 return base.IsDefined (attributeType, inherit);
957 public override object[] GetCustomAttributes (bool inherit)
959 return base.GetCustomAttributes (inherit);
962 public override object[] GetCustomAttributes (Type attributeType, bool inherit)
964 return base.GetCustomAttributes (attributeType, inherit);
967 public override FieldInfo GetField (string name, BindingFlags bindingAttr)
969 return base.GetField (name, bindingAttr);
972 public override FieldInfo[] GetFields (BindingFlags bindingFlags)
974 return base.GetFields (bindingFlags);
977 public override MethodInfo[] GetMethods (BindingFlags bindingFlags)
979 return base.GetMethods (bindingFlags);
982 public override int MetadataToken {
984 return base.MetadataToken;
989 internal class ModuleBuilderTokenGenerator : TokenGenerator {
991 private ModuleBuilder mb;
993 public ModuleBuilderTokenGenerator (ModuleBuilder mb) {
997 public int GetToken (string str) {
998 return mb.GetToken (str);
1001 public int GetToken (MemberInfo member, bool create_open_instance) {
1002 return mb.GetToken (member, create_open_instance);
1005 public int GetToken (MethodBase method, Type[] opt_param_types) {
1006 return mb.GetToken (method, opt_param_types);
1009 public int GetToken (SignatureHelper helper) {
1010 return mb.GetToken (helper);