Update mcs/class/Commons.Xml.Relaxng/Commons.Xml.Relaxng/RelaxngPattern.cs
[mono.git] / mcs / class / corlib / System.Reflection.Emit / ModuleBuilder.cs
1
2 //
3 // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
4 //
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:
12 // 
13 // The above copyright notice and this permission notice shall be
14 // included in all copies or substantial portions of the Software.
15 // 
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.
23 //
24
25 //
26 // System.Reflection.Emit/ModuleBuilder.cs
27 //
28 // Author:
29 //   Paolo Molaro (lupus@ximian.com)
30 //
31 // (C) 2001 Ximian, Inc.  http://www.ximian.com
32 //
33
34 using System;
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;
41 using System.IO;
42 using System.Resources;
43 using System.Globalization;
44
45 namespace System.Reflection.Emit {
46         [ComVisible (true)]
47         [ComDefaultInterface (typeof (_ModuleBuilder))]
48         [ClassInterface (ClassInterfaceType.None)]
49         [StructLayout (LayoutKind.Sequential)]
50         public class ModuleBuilder : Module, _ModuleBuilder {
51
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;
58                 private byte[] guid;
59                 private int table_idx;
60                 internal AssemblyBuilder assemblyb;
61                 private MethodBuilder[] global_methods;
62                 private FieldBuilder[] global_fields;
63                 bool is_main;
64                 private MonoResource[] resources;
65                 #endregion
66 #pragma warning restore 169, 414
67                 
68                 private TypeBuilder global_type;
69                 private Type global_type_created;
70                 Hashtable name_cache;
71                 Dictionary<string, int> us_string_cache;
72                 private int[] table_indexes;
73                 bool transient;
74                 ModuleBuilderTokenGenerator token_gen;
75                 Hashtable resource_writers;
76                 ISymbolWriter symbolWriter;
77
78                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
79                 private static extern void basic_init (ModuleBuilder ab);
80
81                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
82                 private static extern void set_wrappers_type (ModuleBuilder mb, Type ab);
83
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);
95
96                         basic_init (this);
97
98                         CreateGlobalType ();
99
100                         if (assb.IsRun) {
101                                 TypeBuilder tb = new TypeBuilder (this, TypeAttributes.Abstract, 0xFFFFFF); /*last valid token*/
102                                 Type type = tb.CreateType ();
103                                 set_wrappers_type (this, type);
104                         }
105
106                         if (emitSymbolInfo) {
107 #if MOONLIGHT
108                                 symbolWriter = new Mono.CompilerServices.SymbolWriter.SymbolWriterImpl (this);
109 #else
110                                 Assembly asm = Assembly.LoadWithPartialName ("Mono.CompilerServices.SymbolWriter");
111                                 if (asm == null)
112                                         throw new TypeLoadException ("The assembly for default symbol writer cannot be loaded");
113
114                                 Type t = asm.GetType ("Mono.CompilerServices.SymbolWriter.SymbolWriterImpl", true);
115                                 symbolWriter = (ISymbolWriter) Activator.CreateInstance (t, new object[] { this });
116 #endif
117                                 string fileName = fqname;
118                                 if (assemblyb.AssemblyDir != null)
119                                         fileName = Path.Combine (assemblyb.AssemblyDir, fileName);
120                                 symbolWriter.Initialize (IntPtr.Zero, fileName, true);
121                         }
122                 }
123
124                 public override string FullyQualifiedName {get { return fqname;}}
125
126                 public bool IsTransient () {
127                         return transient;
128                 }
129
130                 public void CreateGlobalFunctions () 
131                 {
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 ();
136                 }
137
138                 public FieldBuilder DefineInitializedData( string name, byte[] data, FieldAttributes attributes) {
139                         if (data == null)
140                                 throw new ArgumentNullException ("data");
141
142                         FieldBuilder fb = DefineUninitializedData (name, data.Length, 
143                                                                                                            attributes | FieldAttributes.HasFieldRVA);
144                         fb.SetRVAData (data);
145
146                         return fb;
147                 }
148
149                 public FieldBuilder DefineUninitializedData (string name, int size, FieldAttributes attributes)
150                 {
151                         if (name == null)
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");
157
158                         CreateGlobalType ();
159
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);
166                                 tb.CreateType ();
167                                 datablobtype = tb;
168                         }
169                         FieldBuilder fb = global_type.DefineField (name, datablobtype, attributes|FieldAttributes.Static);
170
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;
176                         } else {
177                                 global_fields = new FieldBuilder [1];
178                                 global_fields [0] = fb;
179                         }
180                         return fb;
181                 }
182
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;
189                         } else {
190                                 global_methods = new MethodBuilder [1];
191                                 global_methods [0] = mb;
192                         }
193                 }
194
195                 public MethodBuilder DefineGlobalMethod (string name, MethodAttributes attributes, Type returnType, Type[] parameterTypes)
196                 {
197                         return DefineGlobalMethod (name, attributes, CallingConventions.Standard, returnType, parameterTypes);
198                 }
199
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);
202                 }
203
204                 public MethodBuilder DefineGlobalMethod (string name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] requiredReturnTypeCustomModifiers, Type[] optionalReturnTypeCustomModifiers, Type[] parameterTypes, Type[][] requiredParameterTypeCustomModifiers, Type[][] optionalParameterTypeCustomModifiers)
205                 {
206                         if (name == null)
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");
212                         CreateGlobalType ();
213                         MethodBuilder mb = global_type.DefineMethod (name, attributes, callingConvention, returnType, requiredReturnTypeCustomModifiers, optionalReturnTypeCustomModifiers, parameterTypes, requiredParameterTypeCustomModifiers, optionalParameterTypeCustomModifiers);
214
215                         addGlobalMethod (mb);
216                         return mb;
217                 }
218
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);
221                 }
222
223                 public MethodBuilder DefinePInvokeMethod (string name, string dllName, string entryName, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes, CallingConvention nativeCallConv, CharSet nativeCharSet) {
224                         if (name == null)
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");
230                         CreateGlobalType ();
231                         MethodBuilder mb = global_type.DefinePInvokeMethod (name, dllName, entryName, attributes, callingConvention, returnType, parameterTypes, nativeCallConv, nativeCharSet);
232
233                         addGlobalMethod (mb);
234                         return mb;
235                 }                       
236
237                 public TypeBuilder DefineType (string name) {
238                         return DefineType (name, 0);
239                 }
240
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);
245                 }
246
247                 public TypeBuilder DefineType (string name, TypeAttributes attr, Type parent) {
248                         return DefineType (name, attr, parent, null);
249                 }
250
251                 private void AddType (TypeBuilder tb)
252                 {
253                         if (types != null) {
254                                 if (types.Length == num_types) {
255                                         TypeBuilder[] new_types = new TypeBuilder [types.Length * 2];
256                                         System.Array.Copy (types, new_types, num_types);
257                                         types = new_types;
258                                 }
259                         } else {
260                                 types = new TypeBuilder [1];
261                         }
262                         types [num_types] = tb;
263                         num_types ++;
264                 }
265
266                 private TypeBuilder DefineType (string name, TypeAttributes attr, Type parent, Type[] interfaces, PackingSize packingSize, int typesize) {
267                         if (name == null)
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);
272                         AddType (res);
273
274                         name_cache.Add (name, res);
275                         
276                         return res;
277                 }
278
279                 internal void RegisterTypeName (TypeBuilder tb, string name)
280                 {
281                         name_cache.Add (name, tb);
282                 }
283                 
284                 internal TypeBuilder GetRegisteredType (string name)
285                 {
286                         return (TypeBuilder) name_cache [name];
287                 }
288
289                 [ComVisible (true)]
290                 public TypeBuilder DefineType (string name, TypeAttributes attr, Type parent, Type[] interfaces) {
291                         return DefineType (name, attr, parent, interfaces, PackingSize.Unspecified, TypeBuilder.UnspecifiedTypeSize);
292                 }
293
294                 public TypeBuilder DefineType (string name, TypeAttributes attr, Type parent, int typesize) {
295                         return DefineType (name, attr, parent, null, PackingSize.Unspecified, TypeBuilder.UnspecifiedTypeSize);
296                 }
297
298                 public TypeBuilder DefineType (string name, TypeAttributes attr, Type parent, PackingSize packsize) {
299                         return DefineType (name, attr, parent, null, packsize, TypeBuilder.UnspecifiedTypeSize);
300                 }
301
302                 public TypeBuilder DefineType (string name, TypeAttributes attr, Type parent, PackingSize packingSize, int typesize) {
303                         return DefineType (name, attr, parent, null, packingSize, typesize);
304                 }
305
306                 public MethodInfo GetArrayMethod( Type arrayClass, string methodName, CallingConventions callingConvention, Type returnType, Type[] parameterTypes) {
307                         return new MonoArrayMethod (arrayClass, methodName, callingConvention, returnType, parameterTypes);
308                 }
309
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.");
313
314                         EnumBuilder eb = new EnumBuilder (this, name, visibility, underlyingType);
315                         TypeBuilder res = eb.GetTypeBuilder ();
316                         AddType (res);
317                         name_cache.Add (name, res);
318                         return eb;
319                 }
320
321                 [ComVisible (true)]
322                 public override Type GetType( string className) {
323                         return GetType (className, false, false);
324                 }
325                 
326                 [ComVisible (true)]
327                 public override Type GetType( string className, bool ignoreCase) {
328                         return GetType (className, false, ignoreCase);
329                 }
330
331                 private TypeBuilder search_in_array (TypeBuilder[] arr, int validElementsInArray, string className) {
332                         int i;
333                         for (i = 0; i < validElementsInArray; ++i) {
334                                 if (String.Compare (className, arr [i].FullName, true, CultureInfo.InvariantCulture) == 0) {
335                                         return arr [i];
336                                 }
337                         }
338                         return null;
339                 }
340
341                 private TypeBuilder search_nested_in_array (TypeBuilder[] arr, int validElementsInArray, string className) {
342                         int i;
343                         for (i = 0; i < validElementsInArray; ++i) {
344                                 if (String.Compare (className, arr [i].Name, true, CultureInfo.InvariantCulture) == 0)
345                                         return arr [i];
346                         }
347                         return null;
348                 }
349
350                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
351                 private static extern Type create_modified_type (TypeBuilder tb, string modifiers);
352
353                 static readonly char [] type_modifiers = {'&', '[', '*'};
354
355                 private TypeBuilder GetMaybeNested (TypeBuilder t, string className) {
356                         int subt;
357                         string pname, rname;
358
359                         subt = className.IndexOf ('+');
360                         if (subt < 0) {
361                                 if (t.subtypes != null)
362                                         return search_nested_in_array (t.subtypes, t.subtypes.Length, className);
363                                 return null;
364                         }
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);
369                                 if (result != null)
370                                         return GetMaybeNested (result, rname);
371                         }
372                         return null;
373                 }
374
375                 [ComVisible (true)]
376                 public override Type GetType (string className, bool throwOnError, bool ignoreCase)
377                 {
378                         if (className == null)
379                                 throw new ArgumentNullException ("className");
380                         if (className.Length == 0)
381                                 throw new ArgumentException ("className");
382
383                         int subt;
384                         string orig = className;
385                         string modifiers;
386                         TypeBuilder result = null;
387
388                         if (types == null && throwOnError)
389                                 throw new TypeLoadException (className);
390
391                         subt = className.IndexOfAny (type_modifiers);
392                         if (subt >= 0) {
393                                 modifiers = className.Substring (subt);
394                                 className = className.Substring (0, subt);
395                         } else
396                                 modifiers = null;
397
398                         if (!ignoreCase) {
399                                 result =  name_cache [className] as TypeBuilder;
400                         } else {
401                                 subt = className.IndexOf ('+');
402                                 if (subt < 0) {
403                                         if (types != null)
404                                                 result = search_in_array (types, num_types,  className);
405                                 } else {
406                                         string pname, rname;
407                                         pname = className.Substring (0, subt);
408                                         rname = className.Substring (subt + 1);
409                                         result = search_in_array (types, num_types, pname);
410                                         if (result != null)
411                                                 result = GetMaybeNested (result, rname);
412                                 }
413                         }
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;
419                                 if (result == null)
420                                         return mt;
421                         }
422                         if (result != null && result.is_created)
423                                 return result.CreateType ();
424                         else
425                                 return result;
426                 }
427
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;
435                         }
436                         // Console.WriteLine ("getindex for table "+table.ToString()+" got "+table_indexes [table].ToString());
437                         if (inc)
438                                 return table_indexes [table]++;
439                         return table_indexes [table];
440                 }
441
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;
447                                 cattrs = new_array;
448                         } else {
449                                 cattrs = new CustomAttributeBuilder [1];
450                                 cattrs [0] = customBuilder;
451                         }
452                 }
453
454                 [ComVisible (true)]
455                 public void SetCustomAttribute( ConstructorInfo con, byte[] binaryAttribute) {
456                         SetCustomAttribute (new CustomAttributeBuilder (con, binaryAttribute));
457                 }
458
459                 public ISymbolWriter GetSymWriter () {
460                         return symbolWriter;
461                 }
462
463                 public ISymbolDocumentWriter DefineDocument (string url, Guid language, Guid languageVendor, Guid documentType)
464                 {
465                         if (symbolWriter != null)
466                                 return symbolWriter.DefineDocument (url, language, languageVendor, documentType);
467                         else
468                                 return null;
469                 }
470
471                 public override Type [] GetTypes ()
472                 {
473                         if (types == null)
474                                 return Type.EmptyTypes;
475
476                         int n = num_types;
477                         Type [] copy = new Type [n];
478                         Array.Copy (types, copy, n);
479
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 ();
484
485                         return copy;
486                 }
487
488                 public IResourceWriter DefineResource (string name, string description, ResourceAttributes attribute)
489                 {
490                         if (name == null)
491                                 throw new ArgumentNullException ("name");
492                         if (name == String.Empty)
493                                 throw new ArgumentException ("name cannot be empty");
494                         if (transient)
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;
502
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);
507                                 resources = new_r;
508                         } else {
509                                 resources = new MonoResource [1];
510                         }
511                         int p = resources.Length - 1;
512                         resources [p].name = name;
513                         resources [p].attrs = attribute;
514
515                         return writer;
516                 }
517
518                 public IResourceWriter DefineResource (string name, string description)
519                 {
520                         return DefineResource (name, description, ResourceAttributes.Public);
521                 }
522
523                 [MonoTODO]
524                 public void DefineUnmanagedResource (byte[] resource)
525                 {
526                         if (resource == null)
527                                 throw new ArgumentNullException ("resource");
528
529                         throw new NotImplementedException ();
530                 }
531
532                 [MonoTODO]
533                 public void DefineUnmanagedResource (string resourceFileName)
534                 {
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.");
541
542                         throw new NotImplementedException ();
543                 }
544
545                 public void DefineManifestResource (string name, Stream stream, ResourceAttributes attribute) {
546                         if (name == null)
547                                 throw new ArgumentNullException ("name");
548                         if (name == String.Empty)
549                                 throw new ArgumentException ("name cannot be empty");
550                         if (stream == null)
551                                 throw new ArgumentNullException ("stream");
552                         if (transient)
553                                 throw new InvalidOperationException ("The module is transient");
554                         if (!assemblyb.IsSave)
555                                 throw new InvalidOperationException ("The assembly is transient");
556
557                         if (resources != null) {
558                                 MonoResource[] new_r = new MonoResource [resources.Length + 1];
559                                 System.Array.Copy(resources, new_r, resources.Length);
560                                 resources = new_r;
561                         } else {
562                                 resources = new MonoResource [1];
563                         }
564                         int p = resources.Length - 1;
565                         resources [p].name = name;
566                         resources [p].attrs = attribute;
567                         resources [p].stream = stream;
568                 }
569
570                 [MonoTODO]
571                 public void SetSymCustomAttribute (string name, byte[] data)
572                 {
573                         throw new NotImplementedException ();
574                 }
575
576                 [MonoTODO]
577                 public void SetUserEntryPoint (MethodInfo entryPoint)
578                 {
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 ();
584                 }
585
586                 public MethodToken GetMethodToken (MethodInfo method)
587                 {
588                         if (method == null)
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));
593                 }
594
595                 public MethodToken GetArrayMethodToken (Type arrayClass, string methodName, CallingConventions callingConvention, Type returnType, Type[] parameterTypes)
596                 {
597                         return GetMethodToken (GetArrayMethod (arrayClass, methodName, callingConvention, returnType, parameterTypes));
598                 }
599
600                 [ComVisible (true)]
601                 public MethodToken GetConstructorToken (ConstructorInfo con)
602                 {
603                         if (con == null)
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));
608                 }
609
610                 public FieldToken GetFieldToken (FieldInfo field)
611                 {
612                         if (field == null)
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));
617                 }
618
619                 [MonoTODO]
620                 public SignatureToken GetSignatureToken (byte[] sigBytes, int sigLength)
621                 {
622                         throw new NotImplementedException ();
623                 }
624
625                 public SignatureToken GetSignatureToken (SignatureHelper sigHelper)
626                 {
627                         if (sigHelper == null)
628                                 throw new ArgumentNullException ("sigHelper");
629                         return new SignatureToken (GetToken (sigHelper));
630                 }
631
632                 public StringToken GetStringConstant (string str)
633                 {
634                         if (str == null)
635                                 throw new ArgumentNullException ("str");
636                         return new StringToken (GetToken (str));
637                 }
638
639                 public TypeToken GetTypeToken (Type type)
640                 {
641                         if (type == null)
642                                 throw new ArgumentNullException ("type");
643                         if (type.IsByRef)
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));
648                 }
649
650                 public TypeToken GetTypeToken (string name)
651                 {
652                         return GetTypeToken (GetType (name));
653                 }
654
655                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
656                 private static extern int getUSIndex (ModuleBuilder mb, string str);
657
658                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
659                 private static extern int getToken (ModuleBuilder mb, object obj, bool create_open_instance);
660
661                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
662                 private static extern int getMethodToken (ModuleBuilder mb, MethodInfo method,
663                                                           Type[] opt_param_types);
664
665                 internal int GetToken (string str)
666                 {
667                         int result;
668                         if (!us_string_cache.TryGetValue (str, out result)) {
669                                 result = getUSIndex (this, str);
670                                 us_string_cache [str] = result;
671                         }
672                         
673                         return result;
674                 }
675
676                 internal int GetToken (MemberInfo member) {
677                         return getToken (this, member, true);
678                 }
679
680                 internal int GetToken (MemberInfo member, bool create_open_instance) {
681                         return getToken (this, member, create_open_instance);
682                 }
683
684                 internal int GetToken (MethodInfo method, Type[] opt_param_types) {
685                         return getMethodToken (this, method, opt_param_types);
686                 }
687
688                 internal int GetToken (SignatureHelper helper) {
689                         return getToken (this, helper, true);
690                 }
691
692                 /*
693                  * Register the token->obj mapping with the runtime so the Module.Resolve... 
694                  * methods will work for obj.
695                  */
696                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
697                 internal extern void RegisterToken (object obj, int token);
698
699                 internal TokenGenerator GetTokenGenerator () {
700                         if (token_gen == null)
701                                 token_gen = new ModuleBuilderTokenGenerator (this);
702                         return token_gen;
703                 }
704
705                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
706                 private static extern void build_metadata (ModuleBuilder mb);
707
708                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
709                 private extern void WriteToFile (IntPtr handle);
710
711                 internal void Save ()
712                 {
713                         if (transient && !is_main)
714                                 return;
715
716                         if (types != null) {
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.");
720                         }
721
722                         if ((global_type != null) && (global_type_created == null))
723                                 global_type_created = global_type.CreateType ();
724
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;
730                                                 writer.Generate ();
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);
735                                                 continue;
736                                         }
737                                         Stream stream = resources [i].stream;
738
739                                         // According to MSDN docs, the stream is read during assembly save, not earlier
740                                         if (stream != null) {
741                                                 try {
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);
746                                                 } catch {
747                                                         /* do something */
748                                                 }
749                                         }
750                                 }
751                         }
752
753                         build_metadata (this);
754
755                         string fileName = fqname;
756                         if (assemblyb.AssemblyDir != null)
757                                 fileName = Path.Combine (assemblyb.AssemblyDir, fileName);
758
759                         try {
760                                 // We mmap the file, so unlink the previous version since it may be in use
761                                 File.Delete (fileName);
762                         } catch {
763                                 // We can safely ignore
764                         }
765                         using (FileStream file = new FileStream (fileName, FileMode.Create, FileAccess.Write))
766                                 WriteToFile (file.Handle);
767                         
768                         //
769                         // The constant 0x80000000 is internal to Mono, it means `make executable'
770                         //
771                         File.SetAttributes (fileName, (FileAttributes) (unchecked ((int) 0x80000000)));
772                         
773                         if (types != null && symbolWriter != null) {
774                                 for (int i = 0; i < num_types; ++i)
775                                         types [i].GenerateDebugInfo (symbolWriter);
776                                 symbolWriter.Close ();
777                         }
778                 }
779
780                 internal string FileName {
781                         get {
782                                 return fqname;
783                         }
784                 }
785
786                 internal bool IsMain {
787                         set {
788                                 is_main = value;
789                         }
790                 }
791
792                 internal void CreateGlobalType () {
793                         if (global_type == null)
794                                 global_type = new TypeBuilder (this, 0, 1);
795                 }
796
797                 internal override Guid GetModuleVersionId ()
798                 {
799                         return new Guid (guid);
800                 }
801
802                 // Used by mcs, the symbol writer, and mdb through reflection
803                 internal static Guid Mono_GetGuid (ModuleBuilder mb)
804                 {
805                         return mb.GetModuleVersionId ();
806                 }
807
808                 void _ModuleBuilder.GetIDsOfNames ([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
809                 {
810                         throw new NotImplementedException ();
811                 }
812
813                 void _ModuleBuilder.GetTypeInfo (uint iTInfo, uint lcid, IntPtr ppTInfo)
814                 {
815                         throw new NotImplementedException ();
816                 }
817
818                 void _ModuleBuilder.GetTypeInfoCount (out uint pcTInfo)
819                 {
820                         throw new NotImplementedException ();
821                 }
822
823                 void _ModuleBuilder.Invoke (uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
824                 {
825                         throw new NotImplementedException ();
826                 }
827
828 #if NET_4_0 || MOONLIGHT || MOBILE
829                 public override Assembly Assembly {
830                         get { return assemblyb; }
831                 }
832
833                 public override string Name {
834                         get { return name; }
835                 }
836
837                 public override string ScopeName {
838                         get { return name; }
839                 }
840
841                 public override Guid ModuleVersionId {
842                         get {
843                                 return GetModuleVersionId ();
844                         }
845                 }
846
847                 //XXX resource modules can't be defined with ModuleBuilder
848                 public override bool IsResource ()
849                 {
850                         return false;
851                 }
852
853                 protected override MethodInfo GetMethodImpl (string name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) 
854                 {
855                         if (global_type_created == null)
856                                 return null;
857                         if (types == null)
858                                 return global_type_created.GetMethod (name);
859                         return global_type_created.GetMethod (name, bindingAttr, binder, callConvention, types, modifiers);
860                 }
861
862                 public override FieldInfo ResolveField (int metadataToken, Type [] genericTypeArguments, Type [] genericMethodArguments) {
863                         ResolveTokenError error;
864
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");
868                         else
869                                 return FieldInfo.GetFieldFromHandle (new RuntimeFieldHandle (handle));
870                 }
871
872                 public override MemberInfo ResolveMember (int metadataToken, Type [] genericTypeArguments, Type [] genericMethodArguments) {
873
874                         ResolveTokenError error;
875
876                         MemberInfo m = ResolveMemberToken (_impl, metadataToken, ptrs_from_types (genericTypeArguments), ptrs_from_types (genericMethodArguments), out error);
877                         if (m == null)
878                                 throw resolve_token_exception (metadataToken, error, "MemberInfo");
879                         else
880                                 return m;
881                 }
882
883                 public override MethodBase ResolveMethod (int metadataToken, Type [] genericTypeArguments, Type [] genericMethodArguments) {
884                         ResolveTokenError error;
885
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");
889                         else
890                                 return MethodBase.GetMethodFromHandleNoGenericCheck (new RuntimeMethodHandle (handle));
891                 }
892
893                 public override string ResolveString (int metadataToken) {
894                         ResolveTokenError error;
895
896                         string s = ResolveStringToken (_impl, metadataToken, out error);
897                         if (s == null)
898                                 throw resolve_token_exception (metadataToken, error, "string");
899                         else
900                                 return s;
901                 }
902
903                 public override byte[] ResolveSignature (int metadataToken) {
904                         ResolveTokenError error;
905
906                     byte[] res = ResolveSignature (_impl, metadataToken, out error);
907                         if (res == null)
908                                 throw resolve_token_exception (metadataToken, error, "signature");
909                         else
910                                 return res;
911                 }
912
913                 public override Type ResolveType (int metadataToken, Type [] genericTypeArguments, Type [] genericMethodArguments) {
914                         ResolveTokenError error;
915
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");
919                         else
920                                 return Type.GetTypeFromHandle (new RuntimeTypeHandle (handle));
921                 }
922
923                 public override bool Equals (object obj)
924                 {
925                         return base.Equals (obj);
926                 }
927
928                 public override int GetHashCode ()
929                 {
930                         return base.GetHashCode ();
931                 }
932
933                 public override bool IsDefined (Type attributeType, bool inherit)
934                 {
935                         return base.IsDefined (attributeType, inherit);
936                 }
937
938                 public override object[] GetCustomAttributes (bool inherit)
939                 {
940                         return base.GetCustomAttributes (inherit);
941                 }
942
943                 public override object[] GetCustomAttributes (Type attributeType, bool inherit)
944                 {
945                         return base.GetCustomAttributes (attributeType, inherit);
946                 }
947
948                 public override FieldInfo GetField (string name, BindingFlags bindingAttr)
949                 {
950                         return base.GetField (name, bindingAttr);
951                 }
952
953                 public override FieldInfo[] GetFields (BindingFlags bindingFlags)
954                 {
955                         return base.GetFields (bindingFlags);
956                 }
957
958                 public override MethodInfo[] GetMethods (BindingFlags bindingFlags)
959                 {
960                         return base.GetMethods (bindingFlags);
961                 }
962
963                 public override int MetadataToken {
964                         get {
965                                 return base.MetadataToken;
966                         }
967                 }
968 #endif
969         }
970
971         internal class ModuleBuilderTokenGenerator : TokenGenerator {
972
973                 private ModuleBuilder mb;
974
975                 public ModuleBuilderTokenGenerator (ModuleBuilder mb) {
976                         this.mb = mb;
977                 }
978
979                 public int GetToken (string str) {
980                         return mb.GetToken (str);
981                 }
982
983                 public int GetToken (MemberInfo member, bool create_open_instance) {
984                         return mb.GetToken (member, create_open_instance);
985                 }
986
987                 public int GetToken (MethodInfo method, Type[] opt_param_types) {
988                         return mb.GetToken (method, opt_param_types);
989                 }
990
991                 public int GetToken (SignatureHelper helper) {
992                         return mb.GetToken (helper);
993                 }
994         }
995 }
996