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