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