Implemented Servlet session management. Servlet hosting moved to Mainsoft.Web package
[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 IntPtr dynamic_image;
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                         if (name == null)
132                                 throw new ArgumentNullException ("name");
133                         if (global_type_created != null)
134                                 throw new InvalidOperationException ("global fields already created");
135                         if (global_type == null)
136                                 global_type = new TypeBuilder (this, 0);
137
138                         string typeName = "$ArrayType$" + size;
139                         Type datablobtype = GetType (typeName, false, false);
140                         if (datablobtype == null) {
141                                 TypeBuilder tb = DefineType (typeName, 
142                                     TypeAttributes.Public|TypeAttributes.ExplicitLayout|TypeAttributes.Sealed,
143                                         assemblyb.corlib_value_type, null, PackingSize.Size1, size);
144                                 tb.CreateType ();
145                                 datablobtype = tb;
146                         }
147                         FieldBuilder fb = global_type.DefineField (name, datablobtype, attributes|FieldAttributes.Static);
148
149                         if (global_fields != null) {
150                                 FieldBuilder[] new_fields = new FieldBuilder [global_fields.Length+1];
151                                 System.Array.Copy (global_fields, new_fields, global_fields.Length);
152                                 new_fields [global_fields.Length] = fb;
153                                 global_fields = new_fields;
154                         } else {
155                                 global_fields = new FieldBuilder [1];
156                                 global_fields [0] = fb;
157                         }
158                         return fb;
159                 }
160
161                 private void addGlobalMethod (MethodBuilder mb) {
162                         if (global_methods != null) {
163                                 MethodBuilder[] new_methods = new MethodBuilder [global_methods.Length+1];
164                                 System.Array.Copy (global_methods, new_methods, global_methods.Length);
165                                 new_methods [global_methods.Length] = mb;
166                                 global_methods = new_methods;
167                         } else {
168                                 global_methods = new MethodBuilder [1];
169                                 global_methods [0] = mb;
170                         }
171                 }
172
173                 public MethodBuilder DefineGlobalMethod (string name, MethodAttributes attributes, Type returnType, Type[] parameterTypes)
174                 {
175                         return DefineGlobalMethod (name, attributes, CallingConventions.Standard, returnType, parameterTypes);
176                 }
177
178                 public MethodBuilder DefineGlobalMethod (string name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes) {
179                         return DefineGlobalMethod (name, attributes, callingConvention, returnType, null, null, parameterTypes, null, null);
180                 }
181
182 #if NET_2_0 || BOOTSTRAP_NET_2_0
183                 public
184 #else
185                 internal
186 #endif
187                 MethodBuilder DefineGlobalMethod (string name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] requiredReturnTypeCustomModifiers, Type[] optionalReturnTypeCustomModifiers, Type[] parameterTypes, Type[][] requiredParameterTypeCustomModifiers, Type[][] optionalParameterTypeCustomModifiers)
188                 {
189                         if (name == null)
190                                 throw new ArgumentNullException ("name");
191                         if ((attributes & MethodAttributes.Static) == 0)
192                                 throw new ArgumentException ("global methods must be static");
193                         if (global_type_created != null)
194                                 throw new InvalidOperationException ("global methods already created");
195                         if (global_type == null)
196                                 global_type = new TypeBuilder (this, 0);
197                         MethodBuilder mb = global_type.DefineMethod (name, attributes, callingConvention, returnType, requiredReturnTypeCustomModifiers, optionalReturnTypeCustomModifiers, parameterTypes, requiredParameterTypeCustomModifiers, optionalParameterTypeCustomModifiers);
198
199                         addGlobalMethod (mb);
200                         return mb;
201                 }
202
203                 public MethodBuilder DefinePInvokeMethod (string name, string dllName, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes, CallingConvention nativeCallConv, CharSet nativeCharSet) {
204                         return DefinePInvokeMethod (name, dllName, name, attributes, callingConvention, returnType, parameterTypes, nativeCallConv, nativeCharSet);
205                 }
206
207                 public MethodBuilder DefinePInvokeMethod (string name, string dllName, string entryName, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes, CallingConvention nativeCallConv, CharSet nativeCharSet) {
208                         if (name == null)
209                                 throw new ArgumentNullException ("name");
210                         if ((attributes & MethodAttributes.Static) == 0)
211                                 throw new ArgumentException ("global methods must be static");
212                         if (global_type_created != null)
213                                 throw new InvalidOperationException ("global methods already created");
214                         if (global_type == null)
215                                 global_type = new TypeBuilder (this, 0);
216                         MethodBuilder mb = global_type.DefinePInvokeMethod (name, dllName, entryName, attributes, callingConvention, returnType, parameterTypes, nativeCallConv, nativeCharSet);
217
218                         addGlobalMethod (mb);
219                         return mb;
220                 }                       
221
222                 public TypeBuilder DefineType (string name) {
223                         return DefineType (name, 0);
224                 }
225
226                 public TypeBuilder DefineType (string name, TypeAttributes attr) {
227                         if ((attr & TypeAttributes.Interface) != 0)
228                                 return DefineType (name, attr, null, null);
229                         return DefineType (name, attr, typeof(object), null);
230                 }
231
232                 public TypeBuilder DefineType (string name, TypeAttributes attr, Type parent) {
233                         return DefineType (name, attr, parent, null);
234                 }
235
236                 private void AddType (TypeBuilder tb)
237                 {
238                         if (types != null) {
239                                 if (types.Length == num_types) {
240                                         TypeBuilder[] new_types = new TypeBuilder [types.Length * 2];
241                                         System.Array.Copy (types, new_types, num_types);
242                                         types = new_types;
243                                 }
244                         } else {
245                                 types = new TypeBuilder [1];
246                         }
247                         types [num_types] = tb;
248                         num_types ++;
249                 }
250
251                 private TypeBuilder DefineType (string name, TypeAttributes attr, Type parent, Type[] interfaces, PackingSize packsize, int typesize) {
252                         if (name_cache.Contains (name))
253                                 throw new ArgumentException ("Duplicate type name within an assembly.");
254
255                         TypeBuilder res = new TypeBuilder (this, name, attr, parent, interfaces, packsize, typesize, null);
256                         AddType (res);
257                         name_cache.Add (name, res);
258                         return res;
259                 }
260
261                 internal void RegisterTypeName (TypeBuilder tb, string name) {
262                         name_cache.Add (name, tb);
263                 }
264
265 #if NET_2_0
266                 [ComVisible (true)]
267 #endif
268                 public TypeBuilder DefineType (string name, TypeAttributes attr, Type parent, Type[] interfaces) {
269                         return DefineType (name, attr, parent, interfaces, PackingSize.Unspecified, TypeBuilder.UnspecifiedTypeSize);
270                 }
271
272                 public TypeBuilder DefineType (string name, TypeAttributes attr, Type parent, int typesize) {
273                         return DefineType (name, attr, parent, null, PackingSize.Unspecified, TypeBuilder.UnspecifiedTypeSize);
274                 }
275
276                 public TypeBuilder DefineType (string name, TypeAttributes attr, Type parent, PackingSize packsize) {
277                         return DefineType (name, attr, parent, null, packsize, TypeBuilder.UnspecifiedTypeSize);
278                 }
279
280                 public TypeBuilder DefineType (string name, TypeAttributes attr, Type parent, PackingSize packsize, int typesize) {
281                         return DefineType (name, attr, parent, null, packsize, typesize);
282                 }
283
284                 public MethodInfo GetArrayMethod( Type arrayClass, string methodName, CallingConventions callingConvention, Type returnType, Type[] parameterTypes) {
285                         return new MonoArrayMethod (arrayClass, methodName, callingConvention, returnType, parameterTypes);
286                 }
287
288                 public EnumBuilder DefineEnum( string name, TypeAttributes visibility, Type underlyingType) {
289                         if (name_cache.Contains (name))
290                                 throw new ArgumentException ("Duplicate type name within an assembly.");
291
292                         EnumBuilder eb = new EnumBuilder (this, name, visibility, underlyingType);
293                         TypeBuilder res = eb.GetTypeBuilder ();
294                         AddType (res);
295                         name_cache.Add (name, res);
296                         return eb;
297                 }
298
299 #if NET_2_0
300                 [ComVisible (true)]
301 #endif
302                 public override Type GetType( string className) {
303                         return GetType (className, false, false);
304                 }
305                 
306 #if NET_2_0
307                 [ComVisible (true)]
308 #endif
309                 public override Type GetType( string className, bool ignoreCase) {
310                         return GetType (className, false, ignoreCase);
311                 }
312
313                 private TypeBuilder search_in_array (TypeBuilder[] arr, int validElementsInArray, string className) {
314                         int i;
315                         for (i = 0; i < validElementsInArray; ++i) {
316                                 if (String.Compare (className, arr [i].FullName, true, CultureInfo.InvariantCulture) == 0) {
317                                         return arr [i];
318                                 }
319                         }
320                         return null;
321                 }
322
323                 private TypeBuilder search_nested_in_array (TypeBuilder[] arr, int validElementsInArray, string className) {
324                         int i;
325                         for (i = 0; i < validElementsInArray; ++i) {
326                                 if (String.Compare (className, arr [i].Name, true, CultureInfo.InvariantCulture) == 0)
327                                         return arr [i];
328                         }
329                         return null;
330                 }
331
332                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
333                 private static extern Type create_modified_type (TypeBuilder tb, string modifiers);
334
335                 static readonly char [] type_modifiers = {'&', '[', '*'};
336
337                 private TypeBuilder GetMaybeNested (TypeBuilder t, string className) {
338                         int subt;
339                         string pname, rname;
340
341                         subt = className.IndexOf ('+');
342                         if (subt < 0) {
343                                 if (t.subtypes != null)
344                                         return search_nested_in_array (t.subtypes, t.subtypes.Length, className);
345                                 return null;
346                         }
347                         if (t.subtypes != null) {
348                                 pname = className.Substring (0, subt);
349                                 rname = className.Substring (subt + 1);
350                                 TypeBuilder result = search_nested_in_array (t.subtypes, t.subtypes.Length, pname);
351                                 if (result != null)
352                                         return GetMaybeNested (result, rname);
353                         }
354                         return null;
355                 }
356
357 #if NET_2_0
358                 [ComVisible (true)]
359 #endif          
360                 public override Type GetType (string className, bool throwOnError, bool ignoreCase) {
361                         int subt;
362                         string orig = className;
363                         string modifiers;
364                         TypeBuilder result = null;
365
366                         if (types == null && throwOnError)
367                                 throw new TypeLoadException (className);
368
369                         subt = className.IndexOfAny (type_modifiers);
370                         if (subt >= 0) {
371                                 modifiers = className.Substring (subt);
372                                 className = className.Substring (0, subt);
373                         } else
374                                 modifiers = null;
375
376                         if (!ignoreCase) {
377                                 result =  name_cache [className] as TypeBuilder;
378                         } else {
379                                 subt = className.IndexOf ('+');
380                                 if (subt < 0) {
381                                         if (types != null)
382                                                 result = search_in_array (types, num_types,  className);
383                                 } else {
384                                         string pname, rname;
385                                         pname = className.Substring (0, subt);
386                                         rname = className.Substring (subt + 1);
387                                         result = search_in_array (types, num_types, pname);
388                                         if (result != null)
389                                                 result = GetMaybeNested (result, rname);
390                                 }
391                         }
392                         if ((result == null) && throwOnError)
393                                 throw new TypeLoadException (orig);
394                         if (result != null && (modifiers != null))
395                                 return create_modified_type (result, modifiers);
396                         return result;
397                 }
398
399                 internal int get_next_table_index (object obj, int table, bool inc) {
400                         if (table_indexes == null) {
401                                 table_indexes = new int [64];
402                                 for (int i=0; i < 64; ++i)
403                                         table_indexes [i] = 1;
404                                 /* allow room for .<Module> in TypeDef table */
405                                 table_indexes [0x02] = 2;
406                         }
407                         // Console.WriteLine ("getindex for table "+table.ToString()+" got "+table_indexes [table].ToString());
408                         if (inc)
409                                 return table_indexes [table]++;
410                         return table_indexes [table];
411                 }
412
413                 public void SetCustomAttribute( CustomAttributeBuilder customBuilder) {
414                         if (cattrs != null) {
415                                 CustomAttributeBuilder[] new_array = new CustomAttributeBuilder [cattrs.Length + 1];
416                                 cattrs.CopyTo (new_array, 0);
417                                 new_array [cattrs.Length] = customBuilder;
418                                 cattrs = new_array;
419                         } else {
420                                 cattrs = new CustomAttributeBuilder [1];
421                                 cattrs [0] = customBuilder;
422                         }
423                 }
424
425 #if NET_2_0
426                 [ComVisible (true)]
427 #endif
428                 public void SetCustomAttribute( ConstructorInfo con, byte[] binaryAttribute) {
429                         SetCustomAttribute (new CustomAttributeBuilder (con, binaryAttribute));
430                 }
431
432                 public ISymbolWriter GetSymWriter () {
433                         return symbolWriter;
434                 }
435
436                 public ISymbolDocumentWriter DefineDocument (string url, Guid language, Guid languageVendor, Guid documentType)
437                 {
438                         if (symbolWriter != null)
439                                 return symbolWriter.DefineDocument (url, language, languageVendor, documentType);
440                         else
441                                 return null;
442                 }
443
444                 public override Type [] GetTypes ()
445                 {
446                         if (types == null)
447                                 return new TypeBuilder [0];
448
449                         int n = num_types;
450                         TypeBuilder [] copy = new TypeBuilder [n];
451                         Array.Copy (types, copy, n);
452
453                         return copy;
454                 }
455
456                 public IResourceWriter DefineResource (string name, string description, ResourceAttributes attribute)
457                 {
458                         if (name == null)
459                                 throw new ArgumentNullException ("name");
460                         if (name == String.Empty)
461                                 throw new ArgumentException ("name cannot be empty");
462                         if (transient)
463                                 throw new InvalidOperationException ("The module is transient");
464                         if (!assemblyb.IsSave)
465                                 throw new InvalidOperationException ("The assembly is transient");
466                         ResourceWriter writer = new ResourceWriter (new MemoryStream ());
467                         if (resource_writers == null)
468                                 resource_writers = new Hashtable ();
469                         resource_writers [name] = writer;
470
471                         // The data is filled out later
472                         if (resources != null) {
473                                 MonoResource[] new_r = new MonoResource [resources.Length + 1];
474                                 System.Array.Copy(resources, new_r, resources.Length);
475                                 resources = new_r;
476                         } else {
477                                 resources = new MonoResource [1];
478                         }
479                         int p = resources.Length - 1;
480                         resources [p].name = name;
481                         resources [p].attrs = attribute;
482
483                         return writer;
484                 }
485
486                 public IResourceWriter DefineResource (string name, string description)
487                 {
488                         return DefineResource (name, description, ResourceAttributes.Public);
489                 }
490
491                 [MonoTODO]
492                 public void DefineUnmanagedResource (byte[] resource)
493                 {
494                         if (resource == null)
495                                 throw new ArgumentNullException ("resource");
496
497                         throw new NotImplementedException ();
498                 }
499
500                 [MonoTODO]
501                 public void DefineUnmanagedResource (string resourceFileName)
502                 {
503                         if (resourceFileName == null)
504                                 throw new ArgumentNullException ("resourceFileName");
505                         if (resourceFileName == String.Empty)
506                                 throw new ArgumentException ("resourceFileName");
507                         if (!File.Exists (resourceFileName) || Directory.Exists (resourceFileName))
508                                 throw new FileNotFoundException ("File '" + resourceFileName + "' does not exists or is a directory.");
509
510                         throw new NotImplementedException ();
511                 }
512
513 #if NET_2_0
514                 public void DefineManifestResource (string name, Stream stream, ResourceAttributes attribute) {
515                         if (name == null)
516                                 throw new ArgumentNullException ("name");
517                         if (name == String.Empty)
518                                 throw new ArgumentException ("name cannot be empty");
519                         if (stream == null)
520                                 throw new ArgumentNullException ("stream");
521                         if (transient)
522                                 throw new InvalidOperationException ("The module is transient");
523                         if (!assemblyb.IsSave)
524                                 throw new InvalidOperationException ("The assembly is transient");
525
526                         if (resources != null) {
527                                 MonoResource[] new_r = new MonoResource [resources.Length + 1];
528                                 System.Array.Copy(resources, new_r, resources.Length);
529                                 resources = new_r;
530                         } else {
531                                 resources = new MonoResource [1];
532                         }
533                         int p = resources.Length - 1;
534                         resources [p].name = name;
535                         resources [p].attrs = attribute;
536                         resources [p].stream = stream;
537                 }
538 #endif
539
540                 [MonoTODO]
541                 public void SetSymCustomAttribute (string name, byte[] data)
542                 {
543                         throw new NotImplementedException ();
544                 }
545
546                 [MonoTODO]
547                 public void SetUserEntryPoint (MethodInfo entryPoint)
548                 {
549                         if (entryPoint == null)
550                                 throw new ArgumentNullException ("entryPoint");
551                         if (entryPoint.DeclaringType.Module != this)
552                                 throw new InvalidOperationException ("entryPoint is not contained in this module");
553                         throw new NotImplementedException ();
554                 }
555
556                 public MethodToken GetMethodToken (MethodInfo method)
557                 {
558                         if (method == null)
559                                 throw new ArgumentNullException ("method");
560                         if (method.DeclaringType.Module != this)
561                                 throw new InvalidOperationException ("The method is not in this module");
562                         return new MethodToken (GetToken (method));
563                 }
564
565                 public MethodToken GetArrayMethodToken (Type arrayClass, string methodName, CallingConventions callingConvention, Type returnType, Type[] parameterTypes)
566                 {
567                         return GetMethodToken (GetArrayMethod (arrayClass, methodName, callingConvention, returnType, parameterTypes));
568                 }
569
570 #if NET_2_0
571                 [ComVisible (true)]
572 #endif
573                 public MethodToken GetConstructorToken (ConstructorInfo con)
574                 {
575                         if (con == null)
576                                 throw new ArgumentNullException ("con");
577                         return new MethodToken (GetToken (con));
578                 }
579
580                 public FieldToken GetFieldToken (FieldInfo field)
581                 {
582                         if (field == null)
583                                 throw new ArgumentNullException ("field");
584                         if (field.DeclaringType.Module != this)
585                                 throw new InvalidOperationException ("The method is not in this module");
586                         return new FieldToken (GetToken (field));
587                 }
588
589                 [MonoTODO]
590                 public SignatureToken GetSignatureToken (byte[] sigBytes, int sigLength)
591                 {
592                         throw new NotImplementedException ();
593                 }
594
595                 public SignatureToken GetSignatureToken (SignatureHelper sigHelper)
596                 {
597                         if (sigHelper == null)
598                                 throw new ArgumentNullException ("sigHelper");
599                         return new SignatureToken (GetToken (sigHelper));
600                 }
601
602                 public StringToken GetStringConstant (string str)
603                 {
604                         if (str == null)
605                                 throw new ArgumentNullException ("str");
606                         return new StringToken (GetToken (str));
607                 }
608
609                 public TypeToken GetTypeToken (Type type)
610                 {
611                         if (type == null)
612                                 throw new ArgumentNullException ("type");
613                         if (type.IsByRef)
614                                 throw new ArgumentException ("type can't be a byref type", "type");
615                         if (!IsTransient () && (type.Module is ModuleBuilder) && ((ModuleBuilder)type.Module).IsTransient ())
616                                 throw new InvalidOperationException ("a non-transient module can't reference a transient module");
617                         return new TypeToken (GetToken (type));
618                 }
619
620                 public TypeToken GetTypeToken (string type)
621                 {
622                         return GetTypeToken (GetType (name));
623                 }
624
625                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
626                 private static extern int getUSIndex (ModuleBuilder mb, string str);
627
628                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
629                 private static extern int getToken (ModuleBuilder mb, object obj);
630
631                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
632                 private static extern int getMethodToken (ModuleBuilder mb, MethodInfo method,
633                                                           Type[] opt_param_types);
634
635                 internal int GetToken (string str) {
636                         if (us_string_cache.Contains (str))
637                                 return (int)us_string_cache [str];
638                         int result = getUSIndex (this, str);
639                         us_string_cache [str] = result;
640                         return result;
641                 }
642
643                 internal int GetToken (MemberInfo member) {
644                         return getToken (this, member);
645                 }
646
647                 internal int GetToken (MethodInfo method, Type[] opt_param_types) {
648                         return getMethodToken (this, method, opt_param_types);
649                 }
650
651                 internal int GetToken (SignatureHelper helper) {
652                         return getToken (this, helper);
653                 }
654
655                 internal TokenGenerator GetTokenGenerator () {
656                         if (token_gen == null)
657                                 token_gen = new ModuleBuilderTokenGenerator (this);
658                         return token_gen;
659                 }
660
661                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
662                 private static extern void build_metadata (ModuleBuilder mb);
663
664                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
665                 private extern void WriteToFile (IntPtr handle);
666
667                 internal void Save ()
668                 {
669                         if (transient && !is_main)
670                                 return;
671
672                         if (types != null) {
673                                 for (int i = 0; i < num_types; ++i)
674                                         if (!types [i].is_created)
675                                                 throw new NotSupportedException ("Type '" + types [i].FullName + "' was not completed.");
676                         }
677
678                         if ((global_type != null) && (global_type_created == null))
679                                 global_type_created = global_type.CreateType ();
680
681                         if (resources != null) {
682                                 for (int i = 0; i < resources.Length; ++i) {
683                                         IResourceWriter rwriter;
684                                         if (resource_writers != null && (rwriter = resource_writers [resources [i].name] as IResourceWriter) != null) {
685                                                 ResourceWriter writer = (ResourceWriter)rwriter;
686                                                 writer.Generate ();
687                                                 MemoryStream mstream = (MemoryStream)writer.Stream;
688                                                 resources [i].data = new byte [mstream.Length];
689                                                 mstream.Seek (0, SeekOrigin.Begin);
690                                                 mstream.Read (resources [i].data, 0, (int)mstream.Length);
691                                                 continue;
692                                         }
693                                         Stream stream = resources [i].stream;
694
695                                         // According to MSDN docs, the stream is read during assembly save, not earlier
696                                         if (stream != null) {
697                                                 try {
698                                                         long len = stream.Length;
699                                                         resources [i].data = new byte [len];
700                                                         stream.Seek (0, SeekOrigin.Begin);
701                                                         stream.Read (resources [i].data, 0, (int)len);
702                                                 } catch {
703                                                         /* do something */
704                                                 }
705                                         }
706                                 }
707                         }
708
709                         build_metadata (this);
710
711                         string fileName = fqname;
712                         if (assemblyb.AssemblyDir != null)
713                                 fileName = Path.Combine (assemblyb.AssemblyDir, fileName);
714
715                         try {
716                                 // We mmap the file, so unlink the previous version since it may be in use
717                                 File.Delete (fileName);
718                         } catch {
719                                 // We can safely ignore
720                         }
721                         using (FileStream file = new FileStream (fileName, FileMode.Create, FileAccess.Write))
722                                 WriteToFile (file.Handle);
723                         
724                         //
725                         // The constant 0x80000000 is internal to Mono, it means `make executable'
726                         //
727                         File.SetAttributes (fileName, (FileAttributes) (unchecked ((int) 0x80000000)));
728                         
729                         if (types != null && symbolWriter != null) {
730                                 for (int i = 0; i < num_types; ++i)
731                                         types [i].GenerateDebugInfo (symbolWriter);
732                                 symbolWriter.Close ();
733                         }
734                 }
735
736                 internal string FileName {
737                         get {
738                                 return fqname;
739                         }
740                 }
741
742                 internal bool IsMain {
743                         set {
744                                 is_main = value;
745                         }
746                 }
747
748                 internal void CreateGlobalType () {
749                         if (global_type == null)
750                                 global_type = new TypeBuilder (this, 0);
751                 }
752
753                 internal static Guid Mono_GetGuid (ModuleBuilder mb)
754                 {
755                         return new Guid (mb.guid);
756                 }
757
758                 void _ModuleBuilder.GetIDsOfNames ([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
759                 {
760                         throw new NotImplementedException ();
761                 }
762
763                 void _ModuleBuilder.GetTypeInfo (uint iTInfo, uint lcid, IntPtr ppTInfo)
764                 {
765                         throw new NotImplementedException ();
766                 }
767
768                 void _ModuleBuilder.GetTypeInfoCount (out uint pcTInfo)
769                 {
770                         throw new NotImplementedException ();
771                 }
772
773                 void _ModuleBuilder.Invoke (uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
774                 {
775                         throw new NotImplementedException ();
776                 }
777         }
778
779         internal class ModuleBuilderTokenGenerator : TokenGenerator {
780
781                 private ModuleBuilder mb;
782
783                 public ModuleBuilderTokenGenerator (ModuleBuilder mb) {
784                         this.mb = mb;
785                 }
786
787                 public int GetToken (string str) {
788                         return mb.GetToken (str);
789                 }
790
791                 public int GetToken (MemberInfo member) {
792                         return mb.GetToken (member);
793                 }
794
795                 public int GetToken (MethodInfo method, Type[] opt_param_types) {
796                         return mb.GetToken (method, opt_param_types);
797                 }
798
799                 public int GetToken (SignatureHelper helper) {
800                         return mb.GetToken (helper);
801                 }
802         }
803 }
804