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