2010-04-01 Rodrigo Kumpera <rkumpera@novell.com>
[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.Runtime.CompilerServices;
38 using System.Runtime.InteropServices;
39 using System.Diagnostics.SymbolStore;
40 using System.IO;
41 using System.Resources;
42 using System.Globalization;
43
44 namespace System.Reflection.Emit {
45         [ComVisible (true)]
46         [ComDefaultInterface (typeof (_ModuleBuilder))]
47         [ClassInterface (ClassInterfaceType.None)]
48         public class ModuleBuilder : Module, _ModuleBuilder {
49
50 #pragma warning disable 169, 414
51                 #region Sync with object-internals.h
52                 private UIntPtr dynamic_image; /* GC-tracked */
53                 private int num_types;
54                 private TypeBuilder[] types;
55                 private CustomAttributeBuilder[] cattrs;
56                 private byte[] guid;
57                 private int table_idx;
58                 internal AssemblyBuilder assemblyb;
59                 private MethodBuilder[] global_methods;
60                 private FieldBuilder[] global_fields;
61                 bool is_main;
62                 private MonoResource[] resources;
63                 #endregion
64 #pragma warning restore 169, 414
65                 
66                 private TypeBuilder global_type;
67                 private Type global_type_created;
68                 Hashtable name_cache;
69                 Hashtable us_string_cache = new Hashtable ();
70                 private int[] table_indexes;
71                 bool transient;
72                 ModuleBuilderTokenGenerator token_gen;
73                 Hashtable resource_writers;
74                 ISymbolWriter symbolWriter;
75
76                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
77                 private static extern void basic_init (ModuleBuilder ab);
78
79                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
80                 private static extern void set_wrappers_type (ModuleBuilder mb, Type ab);
81
82                 internal ModuleBuilder (AssemblyBuilder assb, string name, string fullyqname, bool emitSymbolInfo, bool transient) {
83                         this.name = this.scopename = name;
84                         this.fqname = fullyqname;
85                         this.assembly = this.assemblyb = assb;
86                         this.transient = transient;
87                         // to keep mcs fast we do not want CryptoConfig wo be involved to create the RNG
88                         guid = Guid.FastNewGuidArray ();
89                         // guid = Guid.NewGuid().ToByteArray ();
90                         table_idx = get_next_table_index (this, 0x00, true);
91                         name_cache = new Hashtable ();
92
93                         basic_init (this);
94
95                         CreateGlobalType ();
96
97                         if (assb.IsRun) {
98                                 TypeBuilder tb = new TypeBuilder (this, TypeAttributes.Abstract, 0xFFFFFF); /*last valid token*/
99                                 Type type = tb.CreateType ();
100                                 set_wrappers_type (this, type);
101                         }
102
103                         if (emitSymbolInfo) {
104 #if MOONLIGHT
105                                 symbolWriter = new Mono.CompilerServices.SymbolWriter.SymbolWriterImpl (this);
106 #else
107                                 Assembly asm = Assembly.LoadWithPartialName ("Mono.CompilerServices.SymbolWriter");
108                                 if (asm == null)
109                                         throw new ExecutionEngineException ("The assembly for default symbol writer cannot be loaded");
110
111                                 Type t = asm.GetType ("Mono.CompilerServices.SymbolWriter.SymbolWriterImpl");
112                                 if (t == null)
113                                         throw new ExecutionEngineException ("The type that implements the default symbol writer interface cannot be found");
114
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_cache.ContainsKey (name))
268                                 throw new ArgumentException ("Duplicate type name within an assembly.");
269                         TypeBuilder res = new TypeBuilder (this, name, attr, parent, interfaces, packingSize, typesize, null);
270                         AddType (res);
271
272                         name_cache.Add (name, res);
273                         
274                         return res;
275                 }
276
277                 internal void RegisterTypeName (TypeBuilder tb, string name)
278                 {
279                         name_cache.Add (name, tb);
280                 }
281                 
282                 internal TypeBuilder GetRegisteredType (string name)
283                 {
284                         return (TypeBuilder) name_cache [name];
285                 }
286
287                 [ComVisible (true)]
288                 public TypeBuilder DefineType (string name, TypeAttributes attr, Type parent, Type[] interfaces) {
289                         return DefineType (name, attr, parent, interfaces, PackingSize.Unspecified, TypeBuilder.UnspecifiedTypeSize);
290                 }
291
292                 public TypeBuilder DefineType (string name, TypeAttributes attr, Type parent, int typesize) {
293                         return DefineType (name, attr, parent, null, PackingSize.Unspecified, TypeBuilder.UnspecifiedTypeSize);
294                 }
295
296                 public TypeBuilder DefineType (string name, TypeAttributes attr, Type parent, PackingSize packsize) {
297                         return DefineType (name, attr, parent, null, packsize, TypeBuilder.UnspecifiedTypeSize);
298                 }
299
300                 public TypeBuilder DefineType (string name, TypeAttributes attr, Type parent, PackingSize packingSize, int typesize) {
301                         return DefineType (name, attr, parent, null, packingSize, typesize);
302                 }
303
304                 public MethodInfo GetArrayMethod( Type arrayClass, string methodName, CallingConventions callingConvention, Type returnType, Type[] parameterTypes) {
305                         return new MonoArrayMethod (arrayClass, methodName, callingConvention, returnType, parameterTypes);
306                 }
307
308                 public EnumBuilder DefineEnum( string name, TypeAttributes visibility, Type underlyingType) {
309                         if (name_cache.Contains (name))
310                                 throw new ArgumentException ("Duplicate type name within an assembly.");
311
312                         EnumBuilder eb = new EnumBuilder (this, name, visibility, underlyingType);
313                         TypeBuilder res = eb.GetTypeBuilder ();
314                         AddType (res);
315                         name_cache.Add (name, res);
316                         return eb;
317                 }
318
319                 [ComVisible (true)]
320                 public override Type GetType( string className) {
321                         return GetType (className, false, false);
322                 }
323                 
324                 [ComVisible (true)]
325                 public override Type GetType( string className, bool ignoreCase) {
326                         return GetType (className, false, ignoreCase);
327                 }
328
329                 private TypeBuilder search_in_array (TypeBuilder[] arr, int validElementsInArray, string className) {
330                         int i;
331                         for (i = 0; i < validElementsInArray; ++i) {
332                                 if (String.Compare (className, arr [i].FullName, true, CultureInfo.InvariantCulture) == 0) {
333                                         return arr [i];
334                                 }
335                         }
336                         return null;
337                 }
338
339                 private TypeBuilder search_nested_in_array (TypeBuilder[] arr, int validElementsInArray, string className) {
340                         int i;
341                         for (i = 0; i < validElementsInArray; ++i) {
342                                 if (String.Compare (className, arr [i].Name, true, CultureInfo.InvariantCulture) == 0)
343                                         return arr [i];
344                         }
345                         return null;
346                 }
347
348                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
349                 private static extern Type create_modified_type (TypeBuilder tb, string modifiers);
350
351                 static readonly char [] type_modifiers = {'&', '[', '*'};
352
353                 private TypeBuilder GetMaybeNested (TypeBuilder t, string className) {
354                         int subt;
355                         string pname, rname;
356
357                         subt = className.IndexOf ('+');
358                         if (subt < 0) {
359                                 if (t.subtypes != null)
360                                         return search_nested_in_array (t.subtypes, t.subtypes.Length, className);
361                                 return null;
362                         }
363                         if (t.subtypes != null) {
364                                 pname = className.Substring (0, subt);
365                                 rname = className.Substring (subt + 1);
366                                 TypeBuilder result = search_nested_in_array (t.subtypes, t.subtypes.Length, pname);
367                                 if (result != null)
368                                         return GetMaybeNested (result, rname);
369                         }
370                         return null;
371                 }
372
373                 [ComVisible (true)]
374                 public override Type GetType (string className, bool throwOnError, bool ignoreCase)
375                 {
376                         if (className == null)
377                                 throw new ArgumentNullException ("className");
378                         if (className.Length == 0)
379                                 throw new ArgumentException ("className");
380
381                         int subt;
382                         string orig = className;
383                         string modifiers;
384                         TypeBuilder result = null;
385
386                         if (types == null && throwOnError)
387                                 throw new TypeLoadException (className);
388
389                         subt = className.IndexOfAny (type_modifiers);
390                         if (subt >= 0) {
391                                 modifiers = className.Substring (subt);
392                                 className = className.Substring (0, subt);
393                         } else
394                                 modifiers = null;
395
396                         if (!ignoreCase) {
397                                 result =  name_cache [className] as TypeBuilder;
398                         } else {
399                                 subt = className.IndexOf ('+');
400                                 if (subt < 0) {
401                                         if (types != null)
402                                                 result = search_in_array (types, num_types,  className);
403                                 } else {
404                                         string pname, rname;
405                                         pname = className.Substring (0, subt);
406                                         rname = className.Substring (subt + 1);
407                                         result = search_in_array (types, num_types, pname);
408                                         if (result != null)
409                                                 result = GetMaybeNested (result, rname);
410                                 }
411                         }
412                         if ((result == null) && throwOnError)
413                                 throw new TypeLoadException (orig);
414                         if (result != null && (modifiers != null)) {
415                                 Type mt = create_modified_type (result, modifiers);
416                                 result = mt as TypeBuilder;
417                                 if (result == null)
418                                         return mt;
419                         }
420                         if (result != null && result.is_created)
421                                 return result.CreateType ();
422                         else
423                                 return result;
424                 }
425
426                 internal int get_next_table_index (object obj, int table, bool inc) {
427                         if (table_indexes == null) {
428                                 table_indexes = new int [64];
429                                 for (int i=0; i < 64; ++i)
430                                         table_indexes [i] = 1;
431                                 /* allow room for .<Module> in TypeDef table */
432                                 table_indexes [0x02] = 2;
433                         }
434                         // Console.WriteLine ("getindex for table "+table.ToString()+" got "+table_indexes [table].ToString());
435                         if (inc)
436                                 return table_indexes [table]++;
437                         return table_indexes [table];
438                 }
439
440                 public void SetCustomAttribute( CustomAttributeBuilder customBuilder) {
441                         if (cattrs != null) {
442                                 CustomAttributeBuilder[] new_array = new CustomAttributeBuilder [cattrs.Length + 1];
443                                 cattrs.CopyTo (new_array, 0);
444                                 new_array [cattrs.Length] = customBuilder;
445                                 cattrs = new_array;
446                         } else {
447                                 cattrs = new CustomAttributeBuilder [1];
448                                 cattrs [0] = customBuilder;
449                         }
450                 }
451
452                 [ComVisible (true)]
453                 public void SetCustomAttribute( ConstructorInfo con, byte[] binaryAttribute) {
454                         SetCustomAttribute (new CustomAttributeBuilder (con, binaryAttribute));
455                 }
456
457                 public ISymbolWriter GetSymWriter () {
458                         return symbolWriter;
459                 }
460
461                 public ISymbolDocumentWriter DefineDocument (string url, Guid language, Guid languageVendor, Guid documentType)
462                 {
463                         if (symbolWriter != null)
464                                 return symbolWriter.DefineDocument (url, language, languageVendor, documentType);
465                         else
466                                 return null;
467                 }
468
469                 public override Type [] GetTypes ()
470                 {
471                         if (types == null)
472                                 return Type.EmptyTypes;
473
474                         int n = num_types;
475                         Type [] copy = new Type [n];
476                         Array.Copy (types, copy, n);
477
478                         // MS replaces the typebuilders with their created types
479                         for (int i = 0; i < copy.Length; ++i)
480                                 if (types [i].is_created)
481                                         copy [i] = types [i].CreateType ();
482
483                         return copy;
484                 }
485
486                 public IResourceWriter DefineResource (string name, string description, ResourceAttributes attribute)
487                 {
488                         if (name == null)
489                                 throw new ArgumentNullException ("name");
490                         if (name == String.Empty)
491                                 throw new ArgumentException ("name cannot be empty");
492                         if (transient)
493                                 throw new InvalidOperationException ("The module is transient");
494                         if (!assemblyb.IsSave)
495                                 throw new InvalidOperationException ("The assembly is transient");
496                         ResourceWriter writer = new ResourceWriter (new MemoryStream ());
497                         if (resource_writers == null)
498                                 resource_writers = new Hashtable ();
499                         resource_writers [name] = writer;
500
501                         // The data is filled out later
502                         if (resources != null) {
503                                 MonoResource[] new_r = new MonoResource [resources.Length + 1];
504                                 System.Array.Copy(resources, new_r, resources.Length);
505                                 resources = new_r;
506                         } else {
507                                 resources = new MonoResource [1];
508                         }
509                         int p = resources.Length - 1;
510                         resources [p].name = name;
511                         resources [p].attrs = attribute;
512
513                         return writer;
514                 }
515
516                 public IResourceWriter DefineResource (string name, string description)
517                 {
518                         return DefineResource (name, description, ResourceAttributes.Public);
519                 }
520
521                 [MonoTODO]
522                 public void DefineUnmanagedResource (byte[] resource)
523                 {
524                         if (resource == null)
525                                 throw new ArgumentNullException ("resource");
526
527                         throw new NotImplementedException ();
528                 }
529
530                 [MonoTODO]
531                 public void DefineUnmanagedResource (string resourceFileName)
532                 {
533                         if (resourceFileName == null)
534                                 throw new ArgumentNullException ("resourceFileName");
535                         if (resourceFileName == String.Empty)
536                                 throw new ArgumentException ("resourceFileName");
537                         if (!File.Exists (resourceFileName) || Directory.Exists (resourceFileName))
538                                 throw new FileNotFoundException ("File '" + resourceFileName + "' does not exists or is a directory.");
539
540                         throw new NotImplementedException ();
541                 }
542
543                 public void DefineManifestResource (string name, Stream stream, ResourceAttributes attribute) {
544                         if (name == null)
545                                 throw new ArgumentNullException ("name");
546                         if (name == String.Empty)
547                                 throw new ArgumentException ("name cannot be empty");
548                         if (stream == null)
549                                 throw new ArgumentNullException ("stream");
550                         if (transient)
551                                 throw new InvalidOperationException ("The module is transient");
552                         if (!assemblyb.IsSave)
553                                 throw new InvalidOperationException ("The assembly is transient");
554
555                         if (resources != null) {
556                                 MonoResource[] new_r = new MonoResource [resources.Length + 1];
557                                 System.Array.Copy(resources, new_r, resources.Length);
558                                 resources = new_r;
559                         } else {
560                                 resources = new MonoResource [1];
561                         }
562                         int p = resources.Length - 1;
563                         resources [p].name = name;
564                         resources [p].attrs = attribute;
565                         resources [p].stream = stream;
566                 }
567
568                 [MonoTODO]
569                 public void SetSymCustomAttribute (string name, byte[] data)
570                 {
571                         throw new NotImplementedException ();
572                 }
573
574                 [MonoTODO]
575                 public void SetUserEntryPoint (MethodInfo entryPoint)
576                 {
577                         if (entryPoint == null)
578                                 throw new ArgumentNullException ("entryPoint");
579                         if (entryPoint.DeclaringType.Module != this)
580                                 throw new InvalidOperationException ("entryPoint is not contained in this module");
581                         throw new NotImplementedException ();
582                 }
583
584                 public MethodToken GetMethodToken (MethodInfo method)
585                 {
586                         if (method == null)
587                                 throw new ArgumentNullException ("method");
588                         if (method.DeclaringType.Module != this)
589                                 throw new InvalidOperationException ("The method is not in this module");
590                         return new MethodToken (GetToken (method));
591                 }
592
593                 public MethodToken GetArrayMethodToken (Type arrayClass, string methodName, CallingConventions callingConvention, Type returnType, Type[] parameterTypes)
594                 {
595                         return GetMethodToken (GetArrayMethod (arrayClass, methodName, callingConvention, returnType, parameterTypes));
596                 }
597
598                 [ComVisible (true)]
599                 public MethodToken GetConstructorToken (ConstructorInfo con)
600                 {
601                         if (con == null)
602                                 throw new ArgumentNullException ("con");
603                         return new MethodToken (GetToken (con));
604                 }
605
606                 public FieldToken GetFieldToken (FieldInfo field)
607                 {
608                         if (field == null)
609                                 throw new ArgumentNullException ("field");
610                         if (field.DeclaringType.Module != this)
611                                 throw new InvalidOperationException ("The method is not in this module");
612                         return new FieldToken (GetToken (field));
613                 }
614
615                 [MonoTODO]
616                 public SignatureToken GetSignatureToken (byte[] sigBytes, int sigLength)
617                 {
618                         throw new NotImplementedException ();
619                 }
620
621                 public SignatureToken GetSignatureToken (SignatureHelper sigHelper)
622                 {
623                         if (sigHelper == null)
624                                 throw new ArgumentNullException ("sigHelper");
625                         return new SignatureToken (GetToken (sigHelper));
626                 }
627
628                 public StringToken GetStringConstant (string str)
629                 {
630                         if (str == null)
631                                 throw new ArgumentNullException ("str");
632                         return new StringToken (GetToken (str));
633                 }
634
635                 public TypeToken GetTypeToken (Type type)
636                 {
637                         if (type == null)
638                                 throw new ArgumentNullException ("type");
639                         if (type.IsByRef)
640                                 throw new ArgumentException ("type can't be a byref type", "type");
641                         if (!IsTransient () && (type.Module is ModuleBuilder) && ((ModuleBuilder)type.Module).IsTransient ())
642                                 throw new InvalidOperationException ("a non-transient module can't reference a transient module");
643                         return new TypeToken (GetToken (type));
644                 }
645
646                 public TypeToken GetTypeToken (string name)
647                 {
648                         return GetTypeToken (GetType (name));
649                 }
650
651                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
652                 private static extern int getUSIndex (ModuleBuilder mb, string str);
653
654                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
655                 private static extern int getToken (ModuleBuilder mb, object obj);
656
657                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
658                 private static extern int getMethodToken (ModuleBuilder mb, MethodInfo method,
659                                                           Type[] opt_param_types);
660
661                 internal int GetToken (string str) {
662                         if (us_string_cache.Contains (str))
663                                 return (int)us_string_cache [str];
664                         int result = getUSIndex (this, str);
665                         us_string_cache [str] = result;
666                         return result;
667                 }
668
669                 internal int GetToken (MemberInfo member) {
670                         return getToken (this, member);
671                 }
672
673                 internal int GetToken (MethodInfo method, Type[] opt_param_types) {
674                         return getMethodToken (this, method, opt_param_types);
675                 }
676
677                 internal int GetToken (SignatureHelper helper) {
678                         return getToken (this, helper);
679                 }
680
681                 /*
682                  * Register the token->obj mapping with the runtime so the Module.Resolve... 
683                  * methods will work for obj.
684                  */
685                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
686                 internal extern void RegisterToken (object obj, int token);
687
688                 internal TokenGenerator GetTokenGenerator () {
689                         if (token_gen == null)
690                                 token_gen = new ModuleBuilderTokenGenerator (this);
691                         return token_gen;
692                 }
693
694                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
695                 private static extern void build_metadata (ModuleBuilder mb);
696
697                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
698                 private extern void WriteToFile (IntPtr handle);
699
700                 internal void Save ()
701                 {
702                         if (transient && !is_main)
703                                 return;
704
705                         if (types != null) {
706                                 for (int i = 0; i < num_types; ++i)
707                                         if (!types [i].is_created)
708                                                 throw new NotSupportedException ("Type '" + types [i].FullName + "' was not completed.");
709                         }
710
711                         if ((global_type != null) && (global_type_created == null))
712                                 global_type_created = global_type.CreateType ();
713
714                         if (resources != null) {
715                                 for (int i = 0; i < resources.Length; ++i) {
716                                         IResourceWriter rwriter;
717                                         if (resource_writers != null && (rwriter = resource_writers [resources [i].name] as IResourceWriter) != null) {
718                                                 ResourceWriter writer = (ResourceWriter)rwriter;
719                                                 writer.Generate ();
720                                                 MemoryStream mstream = (MemoryStream)writer.Stream;
721                                                 resources [i].data = new byte [mstream.Length];
722                                                 mstream.Seek (0, SeekOrigin.Begin);
723                                                 mstream.Read (resources [i].data, 0, (int)mstream.Length);
724                                                 continue;
725                                         }
726                                         Stream stream = resources [i].stream;
727
728                                         // According to MSDN docs, the stream is read during assembly save, not earlier
729                                         if (stream != null) {
730                                                 try {
731                                                         long len = stream.Length;
732                                                         resources [i].data = new byte [len];
733                                                         stream.Seek (0, SeekOrigin.Begin);
734                                                         stream.Read (resources [i].data, 0, (int)len);
735                                                 } catch {
736                                                         /* do something */
737                                                 }
738                                         }
739                                 }
740                         }
741
742                         build_metadata (this);
743
744                         string fileName = fqname;
745                         if (assemblyb.AssemblyDir != null)
746                                 fileName = Path.Combine (assemblyb.AssemblyDir, fileName);
747
748                         try {
749                                 // We mmap the file, so unlink the previous version since it may be in use
750                                 File.Delete (fileName);
751                         } catch {
752                                 // We can safely ignore
753                         }
754                         using (FileStream file = new FileStream (fileName, FileMode.Create, FileAccess.Write))
755                                 WriteToFile (file.Handle);
756                         
757                         //
758                         // The constant 0x80000000 is internal to Mono, it means `make executable'
759                         //
760                         File.SetAttributes (fileName, (FileAttributes) (unchecked ((int) 0x80000000)));
761                         
762                         if (types != null && symbolWriter != null) {
763                                 for (int i = 0; i < num_types; ++i)
764                                         types [i].GenerateDebugInfo (symbolWriter);
765                                 symbolWriter.Close ();
766                         }
767                 }
768
769                 internal string FileName {
770                         get {
771                                 return fqname;
772                         }
773                 }
774
775                 internal bool IsMain {
776                         set {
777                                 is_main = value;
778                         }
779                 }
780
781                 internal void CreateGlobalType () {
782                         if (global_type == null)
783                                 global_type = new TypeBuilder (this, 0, 1);
784                 }
785
786                 internal override Guid GetModuleVersionId ()
787                 {
788                         return new Guid (guid);
789                 }
790
791                 // Used by mcs, the symbol writer, and mdb through reflection
792                 internal static Guid Mono_GetGuid (ModuleBuilder mb)
793                 {
794                         return mb.GetModuleVersionId ();
795                 }
796
797                 void _ModuleBuilder.GetIDsOfNames ([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
798                 {
799                         throw new NotImplementedException ();
800                 }
801
802                 void _ModuleBuilder.GetTypeInfo (uint iTInfo, uint lcid, IntPtr ppTInfo)
803                 {
804                         throw new NotImplementedException ();
805                 }
806
807                 void _ModuleBuilder.GetTypeInfoCount (out uint pcTInfo)
808                 {
809                         throw new NotImplementedException ();
810                 }
811
812                 void _ModuleBuilder.Invoke (uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
813                 {
814                         throw new NotImplementedException ();
815                 }
816
817 #if NET_4_0
818                 public override Assembly Assembly {
819                         get { return assemblyb; }
820                 }
821
822                 public override string Name {
823                         get { return name; }
824                 }
825 #endif
826         }
827
828         internal class ModuleBuilderTokenGenerator : TokenGenerator {
829
830                 private ModuleBuilder mb;
831
832                 public ModuleBuilderTokenGenerator (ModuleBuilder mb) {
833                         this.mb = mb;
834                 }
835
836                 public int GetToken (string str) {
837                         return mb.GetToken (str);
838                 }
839
840                 public int GetToken (MemberInfo member) {
841                         return mb.GetToken (member);
842                 }
843
844                 public int GetToken (MethodInfo method, Type[] opt_param_types) {
845                         return mb.GetToken (method, opt_param_types);
846                 }
847
848                 public int GetToken (SignatureHelper helper) {
849                         return mb.GetToken (helper);
850                 }
851         }
852 }
853