c2fd09ebc7f0b7ccb9eae373012d101d7db86847
[mono.git] / mcs / class / corlib / System.Reflection.Emit / ModuleBuilder.cs
1 //
2 // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
3 //
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:
11 // 
12 // The above copyright notice and this permission notice shall be
13 // included in all copies or substantial portions of the Software.
14 // 
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.
22 //
23
24 //
25 // System.Reflection.Emit/ModuleBuilder.cs
26 //
27 // Author:
28 //   Paolo Molaro (lupus@ximian.com)
29 //
30 // (C) 2001 Ximian, Inc.  http://www.ximian.com
31 //
32
33 #if !FULL_AOT_RUNTIME
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                                 Assembly asm = Assembly.LoadWithPartialName ("Mono.CompilerServices.SymbolWriter");
108                                 if (asm == null)
109                                         throw new TypeLoadException ("The assembly for default symbol writer cannot be loaded");
110
111                                 Type t = asm.GetType ("Mono.CompilerServices.SymbolWriter.SymbolWriterImpl", true);
112                                 symbolWriter = (ISymbolWriter) Activator.CreateInstance (t, new object[] { this });
113                                 string fileName = fqname;
114                                 if (assemblyb.AssemblyDir != null)
115                                         fileName = Path.Combine (assemblyb.AssemblyDir, fileName);
116                                 symbolWriter.Initialize (IntPtr.Zero, fileName, true);
117                         }
118                 }
119
120                 public override string FullyQualifiedName {get { return fqname;}}
121
122                 public bool IsTransient () {
123                         return transient;
124                 }
125
126                 public void CreateGlobalFunctions () 
127                 {
128                         if (global_type_created != null)
129                                 throw new InvalidOperationException ("global methods already created");
130                         if (global_type != null)
131                                 global_type_created = global_type.CreateType ();
132                 }
133
134                 public FieldBuilder DefineInitializedData( string name, byte[] data, FieldAttributes attributes) {
135                         if (data == null)
136                                 throw new ArgumentNullException ("data");
137
138                         FieldBuilder fb = DefineUninitializedData (name, data.Length, 
139                                                                                                            attributes | FieldAttributes.HasFieldRVA);
140                         fb.SetRVAData (data);
141
142                         return fb;
143                 }
144
145                 public FieldBuilder DefineUninitializedData (string name, int size, FieldAttributes attributes)
146                 {
147                         if (name == null)
148                                 throw new ArgumentNullException ("name");
149                         if (global_type_created != null)
150                                 throw new InvalidOperationException ("global fields already created");
151                         if ((size <= 0) || (size > 0x3f0000))
152                                 throw new ArgumentException ("size", "Data size must be > 0 and < 0x3f0000");
153
154                         CreateGlobalType ();
155
156                         string typeName = "$ArrayType$" + size;
157                         Type datablobtype = GetType (typeName, false, false);
158                         if (datablobtype == null) {
159                                 TypeBuilder tb = DefineType (typeName, 
160                                     TypeAttributes.Public|TypeAttributes.ExplicitLayout|TypeAttributes.Sealed,
161                                         assemblyb.corlib_value_type, null, PackingSize.Size1, size);
162                                 tb.CreateType ();
163                                 datablobtype = tb;
164                         }
165                         FieldBuilder fb = global_type.DefineField (name, datablobtype, attributes|FieldAttributes.Static);
166
167                         if (global_fields != null) {
168                                 FieldBuilder[] new_fields = new FieldBuilder [global_fields.Length+1];
169                                 System.Array.Copy (global_fields, new_fields, global_fields.Length);
170                                 new_fields [global_fields.Length] = fb;
171                                 global_fields = new_fields;
172                         } else {
173                                 global_fields = new FieldBuilder [1];
174                                 global_fields [0] = fb;
175                         }
176                         return fb;
177                 }
178
179                 private void addGlobalMethod (MethodBuilder mb) {
180                         if (global_methods != null) {
181                                 MethodBuilder[] new_methods = new MethodBuilder [global_methods.Length+1];
182                                 System.Array.Copy (global_methods, new_methods, global_methods.Length);
183                                 new_methods [global_methods.Length] = mb;
184                                 global_methods = new_methods;
185                         } else {
186                                 global_methods = new MethodBuilder [1];
187                                 global_methods [0] = mb;
188                         }
189                 }
190
191                 public MethodBuilder DefineGlobalMethod (string name, MethodAttributes attributes, Type returnType, Type[] parameterTypes)
192                 {
193                         return DefineGlobalMethod (name, attributes, CallingConventions.Standard, returnType, parameterTypes);
194                 }
195
196                 public MethodBuilder DefineGlobalMethod (string name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes) {
197                         return DefineGlobalMethod (name, attributes, callingConvention, returnType, null, null, parameterTypes, null, null);
198                 }
199
200                 public MethodBuilder DefineGlobalMethod (string name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] requiredReturnTypeCustomModifiers, Type[] optionalReturnTypeCustomModifiers, Type[] parameterTypes, Type[][] requiredParameterTypeCustomModifiers, Type[][] optionalParameterTypeCustomModifiers)
201                 {
202                         if (name == null)
203                                 throw new ArgumentNullException ("name");
204                         if ((attributes & MethodAttributes.Static) == 0)
205                                 throw new ArgumentException ("global methods must be static");
206                         if (global_type_created != null)
207                                 throw new InvalidOperationException ("global methods already created");
208                         CreateGlobalType ();
209                         MethodBuilder mb = global_type.DefineMethod (name, attributes, callingConvention, returnType, requiredReturnTypeCustomModifiers, optionalReturnTypeCustomModifiers, parameterTypes, requiredParameterTypeCustomModifiers, optionalParameterTypeCustomModifiers);
210
211                         addGlobalMethod (mb);
212                         return mb;
213                 }
214
215                 public MethodBuilder DefinePInvokeMethod (string name, string dllName, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes, CallingConvention nativeCallConv, CharSet nativeCharSet) {
216                         return DefinePInvokeMethod (name, dllName, name, attributes, callingConvention, returnType, parameterTypes, nativeCallConv, nativeCharSet);
217                 }
218
219                 public MethodBuilder DefinePInvokeMethod (string name, string dllName, string entryName, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes, CallingConvention nativeCallConv, CharSet nativeCharSet) {
220                         if (name == null)
221                                 throw new ArgumentNullException ("name");
222                         if ((attributes & MethodAttributes.Static) == 0)
223                                 throw new ArgumentException ("global methods must be static");
224                         if (global_type_created != null)
225                                 throw new InvalidOperationException ("global methods already created");
226                         CreateGlobalType ();
227                         MethodBuilder mb = global_type.DefinePInvokeMethod (name, dllName, entryName, attributes, callingConvention, returnType, parameterTypes, nativeCallConv, nativeCharSet);
228
229                         addGlobalMethod (mb);
230                         return mb;
231                 }                       
232
233                 public TypeBuilder DefineType (string name) {
234                         return DefineType (name, 0);
235                 }
236
237                 public TypeBuilder DefineType (string name, TypeAttributes attr) {
238                         if ((attr & TypeAttributes.Interface) != 0)
239                                 return DefineType (name, attr, null, null);
240                         return DefineType (name, attr, typeof(object), null);
241                 }
242
243                 public TypeBuilder DefineType (string name, TypeAttributes attr, Type parent) {
244                         return DefineType (name, attr, parent, null);
245                 }
246
247                 private void AddType (TypeBuilder tb)
248                 {
249                         if (types != null) {
250                                 if (types.Length == num_types) {
251                                         TypeBuilder[] new_types = new TypeBuilder [types.Length * 2];
252                                         System.Array.Copy (types, new_types, num_types);
253                                         types = new_types;
254                                 }
255                         } else {
256                                 types = new TypeBuilder [1];
257                         }
258                         types [num_types] = tb;
259                         num_types ++;
260                 }
261
262                 private TypeBuilder DefineType (string name, TypeAttributes attr, Type parent, Type[] interfaces, PackingSize packingSize, int typesize) {
263                         if (name == null)
264                                 throw new ArgumentNullException ("fullname");
265                         if (name_cache.ContainsKey (name))
266                                 throw new ArgumentException ("Duplicate type name within an assembly.");
267                         TypeBuilder res = new TypeBuilder (this, name, attr, parent, interfaces, packingSize, typesize, null);
268                         AddType (res);
269
270                         name_cache.Add (name, res);
271                         
272                         return res;
273                 }
274
275                 internal void RegisterTypeName (TypeBuilder tb, string name)
276                 {
277                         name_cache.Add (name, tb);
278                 }
279                 
280                 internal TypeBuilder GetRegisteredType (string name)
281                 {
282                         return (TypeBuilder) name_cache [name];
283                 }
284
285                 [ComVisible (true)]
286                 public TypeBuilder DefineType (string name, TypeAttributes attr, Type parent, Type[] interfaces) {
287                         return DefineType (name, attr, parent, interfaces, PackingSize.Unspecified, TypeBuilder.UnspecifiedTypeSize);
288                 }
289
290                 public TypeBuilder DefineType (string name, TypeAttributes attr, Type parent, int typesize) {
291                         return DefineType (name, attr, parent, null, PackingSize.Unspecified, typesize);
292                 }
293
294                 public TypeBuilder DefineType (string name, TypeAttributes attr, Type parent, PackingSize packsize) {
295                         return DefineType (name, attr, parent, null, packsize, TypeBuilder.UnspecifiedTypeSize);
296                 }
297
298                 public TypeBuilder DefineType (string name, TypeAttributes attr, Type parent, PackingSize packingSize, int typesize) {
299                         return DefineType (name, attr, parent, null, packingSize, typesize);
300                 }
301
302                 public MethodInfo GetArrayMethod( Type arrayClass, string methodName, CallingConventions callingConvention, Type returnType, Type[] parameterTypes) {
303                         return new MonoArrayMethod (arrayClass, methodName, callingConvention, returnType, parameterTypes);
304                 }
305
306                 public EnumBuilder DefineEnum( string name, TypeAttributes visibility, Type underlyingType) {
307                         if (name_cache.Contains (name))
308                                 throw new ArgumentException ("Duplicate type name within an assembly.");
309
310                         EnumBuilder eb = new EnumBuilder (this, name, visibility, underlyingType);
311                         TypeBuilder res = eb.GetTypeBuilder ();
312                         AddType (res);
313                         name_cache.Add (name, res);
314                         return eb;
315                 }
316
317                 [ComVisible (true)]
318                 public override Type GetType( string className) {
319                         return GetType (className, false, false);
320                 }
321                 
322                 [ComVisible (true)]
323                 public override Type GetType( string className, bool ignoreCase) {
324                         return GetType (className, false, ignoreCase);
325                 }
326
327                 private TypeBuilder search_in_array (TypeBuilder[] arr, int validElementsInArray, string className) {
328                         int i;
329                         for (i = 0; i < validElementsInArray; ++i) {
330                                 if (String.Compare (className, arr [i].FullName, true, CultureInfo.InvariantCulture) == 0) {
331                                         return arr [i];
332                                 }
333                         }
334                         return null;
335                 }
336
337                 private TypeBuilder search_nested_in_array (TypeBuilder[] arr, int validElementsInArray, string className) {
338                         int i;
339                         for (i = 0; i < validElementsInArray; ++i) {
340                                 if (String.Compare (className, arr [i].Name, true, CultureInfo.InvariantCulture) == 0)
341                                         return arr [i];
342                         }
343                         return null;
344                 }
345
346                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
347                 private static extern Type create_modified_type (TypeBuilder tb, string modifiers);
348
349                 static readonly char [] type_modifiers = {'&', '[', '*'};
350
351                 private TypeBuilder GetMaybeNested (TypeBuilder t, string className) {
352                         int subt;
353                         string pname, rname;
354
355                         subt = className.IndexOf ('+');
356                         if (subt < 0) {
357                                 if (t.subtypes != null)
358                                         return search_nested_in_array (t.subtypes, t.subtypes.Length, className);
359                                 return null;
360                         }
361                         if (t.subtypes != null) {
362                                 pname = className.Substring (0, subt);
363                                 rname = className.Substring (subt + 1);
364                                 TypeBuilder result = search_nested_in_array (t.subtypes, t.subtypes.Length, pname);
365                                 if (result != null)
366                                         return GetMaybeNested (result, rname);
367                         }
368                         return null;
369                 }
370
371                 [ComVisible (true)]
372                 public override Type GetType (string className, bool throwOnError, bool ignoreCase)
373                 {
374                         if (className == null)
375                                 throw new ArgumentNullException ("className");
376                         if (className.Length == 0)
377                                 throw new ArgumentException ("className");
378
379                         int subt;
380                         string orig = className;
381                         string modifiers;
382                         TypeBuilder result = null;
383
384                         if (types == null && throwOnError)
385                                 throw new TypeLoadException (className);
386
387                         subt = className.IndexOfAny (type_modifiers);
388                         if (subt >= 0) {
389                                 modifiers = className.Substring (subt);
390                                 className = className.Substring (0, subt);
391                         } else
392                                 modifiers = null;
393
394                         if (!ignoreCase) {
395                                 result =  name_cache [className] as TypeBuilder;
396                         } else {
397                                 subt = className.IndexOf ('+');
398                                 if (subt < 0) {
399                                         if (types != null)
400                                                 result = search_in_array (types, num_types,  className);
401                                 } else {
402                                         string pname, rname;
403                                         pname = className.Substring (0, subt);
404                                         rname = className.Substring (subt + 1);
405                                         result = search_in_array (types, num_types, pname);
406                                         if (result != null)
407                                                 result = GetMaybeNested (result, rname);
408                                 }
409                         }
410                         if ((result == null) && throwOnError)
411                                 throw new TypeLoadException (orig);
412                         if (result != null && (modifiers != null)) {
413                                 Type mt = create_modified_type (result, modifiers);
414                                 result = mt as TypeBuilder;
415                                 if (result == null)
416                                         return mt;
417                         }
418                         if (result != null && result.is_created)
419                                 return result.CreateType ();
420                         else
421                                 return result;
422                 }
423
424                 internal int get_next_table_index (object obj, int table, bool inc) {
425                         if (table_indexes == null) {
426                                 table_indexes = new int [64];
427                                 for (int i=0; i < 64; ++i)
428                                         table_indexes [i] = 1;
429                                 /* allow room for .<Module> in TypeDef table */
430                                 table_indexes [0x02] = 2;
431                         }
432                         // Console.WriteLine ("getindex for table "+table.ToString()+" got "+table_indexes [table].ToString());
433                         if (inc)
434                                 return table_indexes [table]++;
435                         return table_indexes [table];
436                 }
437
438                 public void SetCustomAttribute( CustomAttributeBuilder customBuilder) {
439                         if (cattrs != null) {
440                                 CustomAttributeBuilder[] new_array = new CustomAttributeBuilder [cattrs.Length + 1];
441                                 cattrs.CopyTo (new_array, 0);
442                                 new_array [cattrs.Length] = customBuilder;
443                                 cattrs = new_array;
444                         } else {
445                                 cattrs = new CustomAttributeBuilder [1];
446                                 cattrs [0] = customBuilder;
447                         }
448                 }
449
450                 [ComVisible (true)]
451                 public void SetCustomAttribute( ConstructorInfo con, byte[] binaryAttribute) {
452                         SetCustomAttribute (new CustomAttributeBuilder (con, binaryAttribute));
453                 }
454
455                 public ISymbolWriter GetSymWriter () {
456                         return symbolWriter;
457                 }
458
459                 public ISymbolDocumentWriter DefineDocument (string url, Guid language, Guid languageVendor, Guid documentType)
460                 {
461                         if (symbolWriter != null)
462                                 return symbolWriter.DefineDocument (url, language, languageVendor, documentType);
463                         else
464                                 return null;
465                 }
466
467                 public override Type [] GetTypes ()
468                 {
469                         if (types == null)
470                                 return Type.EmptyTypes;
471
472                         int n = num_types;
473                         Type [] copy = new Type [n];
474                         Array.Copy (types, copy, n);
475
476                         // MS replaces the typebuilders with their created types
477                         for (int i = 0; i < copy.Length; ++i)
478                                 if (types [i].is_created)
479                                         copy [i] = types [i].CreateType ();
480
481                         return copy;
482                 }
483
484                 public IResourceWriter DefineResource (string name, string description, ResourceAttributes attribute)
485                 {
486                         if (name == null)
487                                 throw new ArgumentNullException ("name");
488                         if (name == String.Empty)
489                                 throw new ArgumentException ("name cannot be empty");
490                         if (transient)
491                                 throw new InvalidOperationException ("The module is transient");
492                         if (!assemblyb.IsSave)
493                                 throw new InvalidOperationException ("The assembly is transient");
494                         ResourceWriter writer = new ResourceWriter (new MemoryStream ());
495                         if (resource_writers == null)
496                                 resource_writers = new Hashtable ();
497                         resource_writers [name] = writer;
498
499                         // The data is filled out later
500                         if (resources != null) {
501                                 MonoResource[] new_r = new MonoResource [resources.Length + 1];
502                                 System.Array.Copy(resources, new_r, resources.Length);
503                                 resources = new_r;
504                         } else {
505                                 resources = new MonoResource [1];
506                         }
507                         int p = resources.Length - 1;
508                         resources [p].name = name;
509                         resources [p].attrs = attribute;
510
511                         return writer;
512                 }
513
514                 public IResourceWriter DefineResource (string name, string description)
515                 {
516                         return DefineResource (name, description, ResourceAttributes.Public);
517                 }
518
519                 [MonoTODO]
520                 public void DefineUnmanagedResource (byte[] resource)
521                 {
522                         if (resource == null)
523                                 throw new ArgumentNullException ("resource");
524
525                         throw new NotImplementedException ();
526                 }
527
528                 [MonoTODO]
529                 public void DefineUnmanagedResource (string resourceFileName)
530                 {
531                         if (resourceFileName == null)
532                                 throw new ArgumentNullException ("resourceFileName");
533                         if (resourceFileName == String.Empty)
534                                 throw new ArgumentException ("resourceFileName");
535                         if (!File.Exists (resourceFileName) || Directory.Exists (resourceFileName))
536                                 throw new FileNotFoundException ("File '" + resourceFileName + "' does not exist or is a directory.");
537
538                         throw new NotImplementedException ();
539                 }
540
541                 public void DefineManifestResource (string name, Stream stream, ResourceAttributes attribute) {
542                         if (name == null)
543                                 throw new ArgumentNullException ("name");
544                         if (name == String.Empty)
545                                 throw new ArgumentException ("name cannot be empty");
546                         if (stream == null)
547                                 throw new ArgumentNullException ("stream");
548                         if (transient)
549                                 throw new InvalidOperationException ("The module is transient");
550                         if (!assemblyb.IsSave)
551                                 throw new InvalidOperationException ("The assembly is transient");
552
553                         if (resources != null) {
554                                 MonoResource[] new_r = new MonoResource [resources.Length + 1];
555                                 System.Array.Copy(resources, new_r, resources.Length);
556                                 resources = new_r;
557                         } else {
558                                 resources = new MonoResource [1];
559                         }
560                         int p = resources.Length - 1;
561                         resources [p].name = name;
562                         resources [p].attrs = attribute;
563                         resources [p].stream = stream;
564                 }
565
566                 [MonoTODO]
567                 public void SetSymCustomAttribute (string name, byte[] data)
568                 {
569                         throw new NotImplementedException ();
570                 }
571
572                 [MonoTODO]
573                 public void SetUserEntryPoint (MethodInfo entryPoint)
574                 {
575                         if (entryPoint == null)
576                                 throw new ArgumentNullException ("entryPoint");
577                         if (entryPoint.DeclaringType.Module != this)
578                                 throw new InvalidOperationException ("entryPoint is not contained in this module");
579                         throw new NotImplementedException ();
580                 }
581
582                 public MethodToken GetMethodToken (MethodInfo method)
583                 {
584                         if (method == null)
585                                 throw new ArgumentNullException ("method");
586
587                         return new MethodToken (GetToken (method));
588                 }
589                 
590                 public MethodToken GetMethodToken (MethodInfo method, IEnumerable<Type> optionalParameterTypes)
591                 {
592                         if (method == null)
593                                 throw new ArgumentNullException ("method");
594
595                         return new MethodToken (GetToken (method, optionalParameterTypes));
596                 }
597
598                 public MethodToken GetArrayMethodToken (Type arrayClass, string methodName, CallingConventions callingConvention, Type returnType, Type[] parameterTypes)
599                 {
600                         return GetMethodToken (GetArrayMethod (arrayClass, methodName, callingConvention, returnType, parameterTypes));
601                 }
602
603                 [ComVisible (true)]
604                 public MethodToken GetConstructorToken (ConstructorInfo con)
605                 {
606                         if (con == null)
607                                 throw new ArgumentNullException ("con");
608
609                         return new MethodToken (GetToken (con));
610                 }
611                 
612                 public MethodToken GetConstructorToken (ConstructorInfo constructor, IEnumerable<Type> optionalParameterTypes)
613                 {
614                         if (constructor == null)
615                                 throw new ArgumentNullException ("constructor");
616
617                         return new MethodToken (GetToken (constructor, optionalParameterTypes));
618                 }
619
620                 public FieldToken GetFieldToken (FieldInfo field)
621                 {
622                         if (field == null)
623                                 throw new ArgumentNullException ("field");
624
625                         return new FieldToken (GetToken (field));
626                 }
627
628                 [MonoTODO]
629                 public SignatureToken GetSignatureToken (byte[] sigBytes, int sigLength)
630                 {
631                         throw new NotImplementedException ();
632                 }
633
634                 public SignatureToken GetSignatureToken (SignatureHelper sigHelper)
635                 {
636                         if (sigHelper == null)
637                                 throw new ArgumentNullException ("sigHelper");
638                         return new SignatureToken (GetToken (sigHelper));
639                 }
640
641                 public StringToken GetStringConstant (string str)
642                 {
643                         if (str == null)
644                                 throw new ArgumentNullException ("str");
645                         return new StringToken (GetToken (str));
646                 }
647
648                 public TypeToken GetTypeToken (Type type)
649                 {
650                         if (type == null)
651                                 throw new ArgumentNullException ("type");
652                         if (type.IsByRef)
653                                 throw new ArgumentException ("type can't be a byref type", "type");
654                         if (!IsTransient () && (type.Module is ModuleBuilder) && ((ModuleBuilder)type.Module).IsTransient ())
655                                 throw new InvalidOperationException ("a non-transient module can't reference a transient module");
656                         return new TypeToken (GetToken (type));
657                 }
658
659                 public TypeToken GetTypeToken (string name)
660                 {
661                         return GetTypeToken (GetType (name));
662                 }
663
664                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
665                 private static extern int getUSIndex (ModuleBuilder mb, string str);
666
667                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
668                 private static extern int getToken (ModuleBuilder mb, object obj, bool create_open_instance);
669
670                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
671                 private static extern int getMethodToken (ModuleBuilder mb, MethodBase method,
672                                                           Type[] opt_param_types);
673
674                 internal int GetToken (string str)
675                 {
676                         int result;
677                         if (!us_string_cache.TryGetValue (str, out result)) {
678                                 result = getUSIndex (this, str);
679                                 us_string_cache [str] = result;
680                         }
681                         
682                         return result;
683                 }
684
685                 internal int GetToken (MemberInfo member) {
686                         return getToken (this, member, true);
687                 }
688
689                 internal int GetToken (MemberInfo member, bool create_open_instance) {
690                         return getToken (this, member, create_open_instance);
691                 }
692
693                 internal int GetToken (MethodBase method, IEnumerable<Type> opt_param_types) {
694                         if (opt_param_types == null)
695                                 return getToken (this, method, true);
696
697                         var optParamTypes = new List<Type> (opt_param_types);
698                         return  getMethodToken (this, method, optParamTypes.ToArray ());
699                 }
700                 
701                 internal int GetToken (MethodBase method, Type[] opt_param_types) {
702                         return getMethodToken (this, method, opt_param_types);
703                 }
704
705                 internal int GetToken (SignatureHelper helper) {
706                         return getToken (this, helper, true);
707                 }
708
709                 /*
710                  * Register the token->obj mapping with the runtime so the Module.Resolve... 
711                  * methods will work for obj.
712                  */
713                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
714                 internal extern void RegisterToken (object obj, int token);
715
716                 /*
717                  * Returns MemberInfo registered with the given token.
718                  */
719                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
720                 internal extern object GetRegisteredToken (int token);
721
722                 internal TokenGenerator GetTokenGenerator () {
723                         if (token_gen == null)
724                                 token_gen = new ModuleBuilderTokenGenerator (this);
725                         return token_gen;
726                 }
727
728                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
729                 private static extern void build_metadata (ModuleBuilder mb);
730
731                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
732                 private extern void WriteToFile (IntPtr handle);
733
734                 internal void Save ()
735                 {
736                         if (transient && !is_main)
737                                 return;
738
739                         if (types != null) {
740                                 for (int i = 0; i < num_types; ++i)
741                                         if (!types [i].is_created)
742                                                 throw new NotSupportedException ("Type '" + types [i].FullName + "' was not completed.");
743                         }
744
745                         if ((global_type != null) && (global_type_created == null))
746                                 global_type_created = global_type.CreateType ();
747
748                         if (resources != null) {
749                                 for (int i = 0; i < resources.Length; ++i) {
750                                         IResourceWriter rwriter;
751                                         if (resource_writers != null && (rwriter = resource_writers [resources [i].name] as IResourceWriter) != null) {
752                                                 ResourceWriter writer = (ResourceWriter)rwriter;
753                                                 writer.Generate ();
754                                                 MemoryStream mstream = (MemoryStream)writer._output;
755                                                 resources [i].data = new byte [mstream.Length];
756                                                 mstream.Seek (0, SeekOrigin.Begin);
757                                                 mstream.Read (resources [i].data, 0, (int)mstream.Length);
758                                                 continue;
759                                         }
760                                         Stream stream = resources [i].stream;
761
762                                         // According to MSDN docs, the stream is read during assembly save, not earlier
763                                         if (stream != null) {
764                                                 try {
765                                                         long len = stream.Length;
766                                                         resources [i].data = new byte [len];
767                                                         stream.Seek (0, SeekOrigin.Begin);
768                                                         stream.Read (resources [i].data, 0, (int)len);
769                                                 } catch {
770                                                         /* do something */
771                                                 }
772                                         }
773                                 }
774                         }
775
776                         build_metadata (this);
777
778                         string fileName = fqname;
779                         if (assemblyb.AssemblyDir != null)
780                                 fileName = Path.Combine (assemblyb.AssemblyDir, fileName);
781
782                         try {
783                                 // We mmap the file, so unlink the previous version since it may be in use
784                                 File.Delete (fileName);
785                         } catch {
786                                 // We can safely ignore
787                         }
788                         using (FileStream file = new FileStream (fileName, FileMode.Create, FileAccess.Write))
789                                 WriteToFile (file.Handle);
790                         
791                         //
792                         // The constant 0x80000000 is internal to Mono, it means `make executable'
793                         //
794                         File.SetAttributes (fileName, (FileAttributes) (unchecked ((int) 0x80000000)));
795                         
796                         if (types != null && symbolWriter != null) {
797                                 for (int i = 0; i < num_types; ++i)
798                                         types [i].GenerateDebugInfo (symbolWriter);
799                                 symbolWriter.Close ();
800                         }
801                 }
802
803                 internal string FileName {
804                         get {
805                                 return fqname;
806                         }
807                 }
808
809                 internal bool IsMain {
810                         set {
811                                 is_main = value;
812                         }
813                 }
814
815                 internal void CreateGlobalType () {
816                         if (global_type == null)
817                                 global_type = new TypeBuilder (this, 0, 1);
818                 }
819
820                 internal override Guid GetModuleVersionId ()
821                 {
822                         return new Guid (guid);
823                 }
824
825                 // Used by mcs, the symbol writer, and mdb through reflection
826                 internal static Guid Mono_GetGuid (ModuleBuilder mb)
827                 {
828                         return mb.GetModuleVersionId ();
829                 }
830
831                 void _ModuleBuilder.GetIDsOfNames ([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
832                 {
833                         throw new NotImplementedException ();
834                 }
835
836                 void _ModuleBuilder.GetTypeInfo (uint iTInfo, uint lcid, IntPtr ppTInfo)
837                 {
838                         throw new NotImplementedException ();
839                 }
840
841                 void _ModuleBuilder.GetTypeInfoCount (out uint pcTInfo)
842                 {
843                         throw new NotImplementedException ();
844                 }
845
846                 void _ModuleBuilder.Invoke (uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
847                 {
848                         throw new NotImplementedException ();
849                 }
850
851                 public override Assembly Assembly {
852                         get { return assemblyb; }
853                 }
854
855                 public override string Name {
856                         get { return name; }
857                 }
858
859                 public override string ScopeName {
860                         get { return name; }
861                 }
862
863                 public override Guid ModuleVersionId {
864                         get {
865                                 return GetModuleVersionId ();
866                         }
867                 }
868
869                 //XXX resource modules can't be defined with ModuleBuilder
870                 public override bool IsResource ()
871                 {
872                         return false;
873                 }
874
875                 protected override MethodInfo GetMethodImpl (string name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) 
876                 {
877                         if (global_type_created == null)
878                                 return null;
879                         if (types == null)
880                                 return global_type_created.GetMethod (name);
881                         return global_type_created.GetMethod (name, bindingAttr, binder, callConvention, types, modifiers);
882                 }
883
884                 public override FieldInfo ResolveField (int metadataToken, Type [] genericTypeArguments, Type [] genericMethodArguments) {
885                         ResolveTokenError error;
886
887                         IntPtr handle = ResolveFieldToken (_impl, metadataToken, ptrs_from_types (genericTypeArguments), ptrs_from_types (genericMethodArguments), out error);
888                         if (handle == IntPtr.Zero)
889                                 throw resolve_token_exception (metadataToken, error, "Field");
890                         else
891                                 return FieldInfo.GetFieldFromHandle (new RuntimeFieldHandle (handle));
892                 }
893
894                 public override MemberInfo ResolveMember (int metadataToken, Type [] genericTypeArguments, Type [] genericMethodArguments) {
895
896                         ResolveTokenError error;
897
898                         MemberInfo m = ResolveMemberToken (_impl, metadataToken, ptrs_from_types (genericTypeArguments), ptrs_from_types (genericMethodArguments), out error);
899                         if (m == null)
900                                 throw resolve_token_exception (metadataToken, error, "MemberInfo");
901                         else
902                                 return m;
903                 }
904
905                 public override MethodBase ResolveMethod (int metadataToken, Type [] genericTypeArguments, Type [] genericMethodArguments) {
906                         ResolveTokenError error;
907
908                         IntPtr handle = ResolveMethodToken (_impl, metadataToken, ptrs_from_types (genericTypeArguments), ptrs_from_types (genericMethodArguments), out error);
909                         if (handle == IntPtr.Zero)
910                                 throw resolve_token_exception (metadataToken, error, "MethodBase");
911                         else
912                                 return MethodBase.GetMethodFromHandleNoGenericCheck (new RuntimeMethodHandle (handle));
913                 }
914
915                 public override string ResolveString (int metadataToken) {
916                         ResolveTokenError error;
917
918                         string s = ResolveStringToken (_impl, metadataToken, out error);
919                         if (s == null)
920                                 throw resolve_token_exception (metadataToken, error, "string");
921                         else
922                                 return s;
923                 }
924
925                 public override byte[] ResolveSignature (int metadataToken) {
926                         ResolveTokenError error;
927
928                     byte[] res = ResolveSignature (_impl, metadataToken, out error);
929                         if (res == null)
930                                 throw resolve_token_exception (metadataToken, error, "signature");
931                         else
932                                 return res;
933                 }
934
935                 public override Type ResolveType (int metadataToken, Type [] genericTypeArguments, Type [] genericMethodArguments) {
936                         ResolveTokenError error;
937
938                         IntPtr handle = ResolveTypeToken (_impl, metadataToken, ptrs_from_types (genericTypeArguments), ptrs_from_types (genericMethodArguments), out error);
939                         if (handle == IntPtr.Zero)
940                                 throw resolve_token_exception (metadataToken, error, "Type");
941                         else
942                                 return Type.GetTypeFromHandle (new RuntimeTypeHandle (handle));
943                 }
944
945                 public override bool Equals (object obj)
946                 {
947                         return base.Equals (obj);
948                 }
949
950                 public override int GetHashCode ()
951                 {
952                         return base.GetHashCode ();
953                 }
954
955                 public override bool IsDefined (Type attributeType, bool inherit)
956                 {
957                         return base.IsDefined (attributeType, inherit);
958                 }
959
960                 public override object[] GetCustomAttributes (bool inherit)
961                 {
962                         return base.GetCustomAttributes (inherit);
963                 }
964
965                 public override object[] GetCustomAttributes (Type attributeType, bool inherit)
966                 {
967                         return base.GetCustomAttributes (attributeType, inherit);
968                 }
969
970                 public override FieldInfo GetField (string name, BindingFlags bindingAttr)
971                 {
972                         return base.GetField (name, bindingAttr);
973                 }
974
975                 public override FieldInfo[] GetFields (BindingFlags bindingFlags)
976                 {
977                         return base.GetFields (bindingFlags);
978                 }
979
980                 public override MethodInfo[] GetMethods (BindingFlags bindingFlags)
981                 {
982                         return base.GetMethods (bindingFlags);
983                 }
984
985                 public override int MetadataToken {
986                         get {
987                                 return base.MetadataToken;
988                         }
989                 }
990         }
991
992         internal class ModuleBuilderTokenGenerator : TokenGenerator {
993
994                 private ModuleBuilder mb;
995
996                 public ModuleBuilderTokenGenerator (ModuleBuilder mb) {
997                         this.mb = mb;
998                 }
999
1000                 public int GetToken (string str) {
1001                         return mb.GetToken (str);
1002                 }
1003
1004                 public int GetToken (MemberInfo member, bool create_open_instance) {
1005                         return mb.GetToken (member, create_open_instance);
1006                 }
1007
1008                 public int GetToken (MethodBase method, Type[] opt_param_types) {
1009                         return mb.GetToken (method, opt_param_types);
1010                 }
1011
1012                 public int GetToken (SignatureHelper helper) {
1013                         return mb.GetToken (helper);
1014                 }
1015         }
1016 }
1017
1018 #endif