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