2005-01-31 Zoltan Varga <vargaz@freemail.hu>
[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         public class ModuleBuilder : Module {
46                 #region Sync with reflection.h
47                 private IntPtr dynamic_image;
48                 private int num_types;
49                 private TypeBuilder[] types;
50                 private CustomAttributeBuilder[] cattrs;
51                 private byte[] guid;
52                 private int table_idx;
53                 internal AssemblyBuilder assemblyb;
54                 private MethodBuilder[] global_methods;
55                 private FieldBuilder[] global_fields;
56                 bool is_main;
57                 private MonoResource[] resources;
58                 #endregion
59                 private TypeBuilder global_type;
60                 private Type global_type_created;
61                 Hashtable name_cache;
62                 Hashtable us_string_cache = new Hashtable ();
63                 private int[] table_indexes;
64                 bool transient;
65                 ModuleBuilderTokenGenerator token_gen;
66                 ArrayList resource_writers = null;
67
68                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
69                 private static extern void basic_init (ModuleBuilder ab);
70
71                 internal ModuleBuilder (AssemblyBuilder assb, string name, string fullyqname, bool emitSymbolInfo, bool transient) {
72                         this.name = this.scopename = name;
73                         this.fqname = fullyqname;
74                         this.assembly = this.assemblyb = assb;
75                         this.transient = transient;
76                         // to keep mcs fast we do not want CryptoConfig wo be involved to create the RNG
77                         guid = Guid.FastNewGuidArray ();
78                         // guid = Guid.NewGuid().ToByteArray ();
79                         table_idx = get_next_table_index (this, 0x00, true);
80                         name_cache = new Hashtable ();
81
82                         basic_init (this);
83
84                         CreateGlobalType ();
85                 }
86
87                 public override string FullyQualifiedName {get { return fqname;}}
88
89                 public bool IsTransient () {
90                         return transient;
91                 }
92
93                 public void CreateGlobalFunctions () 
94                 {
95                         if (global_type_created != null)
96                                 throw new InvalidOperationException ("global methods already created");
97                         if (global_type != null)
98                                 global_type_created = global_type.CreateType ();
99                 }
100
101                 public FieldBuilder DefineInitializedData( string name, byte[] data, FieldAttributes attributes) {
102                         if (data == null)
103                                 throw new ArgumentNullException ("data");
104
105                         FieldBuilder fb = DefineUninitializedData (name, data.Length, 
106                                                                                                            attributes | FieldAttributes.HasFieldRVA);
107                         fb.SetRVAData (data);
108
109                         return fb;
110                 }
111
112                 public FieldBuilder DefineUninitializedData( string name, int size, FieldAttributes attributes) {
113                         if (name == null)
114                                 throw new ArgumentNullException ("name");
115                         if (global_type_created != null)
116                                 throw new InvalidOperationException ("global fields already created");
117                         if (global_type == null)
118                                 global_type = new TypeBuilder (this, 0);
119
120                         string typeName = "$ArrayType$" + size;
121                         Type datablobtype = GetType (typeName, false, false);
122                         if (datablobtype == null) {
123                                 TypeBuilder tb = DefineType (typeName, 
124                                     TypeAttributes.Public|TypeAttributes.ExplicitLayout|TypeAttributes.Sealed,
125                                         assemblyb.corlib_value_type, null, PackingSize.Size1, size);
126                                 tb.CreateType ();
127                                 datablobtype = tb;
128                         }
129                         FieldBuilder fb = global_type.DefineField (name, datablobtype, attributes|FieldAttributes.Static);
130
131                         if (global_fields != null) {
132                                 FieldBuilder[] new_fields = new FieldBuilder [global_fields.Length+1];
133                                 System.Array.Copy (global_fields, new_fields, global_fields.Length);
134                                 new_fields [global_fields.Length] = fb;
135                                 global_fields = new_fields;
136                         } else {
137                                 global_fields = new FieldBuilder [1];
138                                 global_fields [0] = fb;
139                         }
140                         return fb;
141                 }
142
143                 private void addGlobalMethod (MethodBuilder mb) {
144                         if (global_methods != null) {
145                                 MethodBuilder[] new_methods = new MethodBuilder [global_methods.Length+1];
146                                 System.Array.Copy (global_methods, new_methods, global_methods.Length);
147                                 new_methods [global_methods.Length] = mb;
148                                 global_methods = new_methods;
149                         } else {
150                                 global_methods = new MethodBuilder [1];
151                                 global_methods [0] = mb;
152                         }
153                 }
154
155                 public MethodBuilder DefineGlobalMethod (string name, MethodAttributes attributes, Type returnType, Type[] parameterTypes)
156                 {
157                         return DefineGlobalMethod (name, attributes, CallingConventions.Standard, returnType, parameterTypes);
158                 }
159
160                 public MethodBuilder DefineGlobalMethod (string name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes) {
161                         return DefineGlobalMethod (name, attributes, callingConvention, returnType, null, null, parameterTypes, null, null);
162                 }
163
164 #if NET_2_0 || BOOTSTRAP_NET_2_0
165                 public
166 #else
167                 internal
168 #endif
169                 MethodBuilder DefineGlobalMethod (string name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] requiredReturnTypeCustomModifiers, Type[] optionalReturnTypeCustomModifiers, Type[] parameterTypes, Type[][] requiredParameterTypeCustomModifiers, Type[][] optionalParameterTypeCustomModifiers)
170                 {
171                         if (name == null)
172                                 throw new ArgumentNullException ("name");
173                         if ((attributes & MethodAttributes.Static) == 0)
174                                 throw new ArgumentException ("global methods must be static");
175                         if (global_type_created != null)
176                                 throw new InvalidOperationException ("global methods already created");
177                         if (global_type == null)
178                                 global_type = new TypeBuilder (this, 0);
179                         MethodBuilder mb = global_type.DefineMethod (name, attributes, callingConvention, returnType, requiredReturnTypeCustomModifiers, optionalReturnTypeCustomModifiers, parameterTypes, requiredParameterTypeCustomModifiers, optionalParameterTypeCustomModifiers);
180
181                         addGlobalMethod (mb);
182                         return mb;
183                 }
184
185                 public MethodBuilder DefinePInvokeMethod (string name, string dllName, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes, CallingConvention nativeCallConv, CharSet nativeCharSet) {
186                         return DefinePInvokeMethod (name, dllName, name, attributes, callingConvention, returnType, parameterTypes, nativeCallConv, nativeCharSet);
187                 }
188
189                 public MethodBuilder DefinePInvokeMethod (string name, string dllName, string entryName, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes, CallingConvention nativeCallConv, CharSet nativeCharSet) {
190                         if (name == null)
191                                 throw new ArgumentNullException ("name");
192                         if ((attributes & MethodAttributes.Static) == 0)
193                                 throw new ArgumentException ("global methods must be static");
194                         if (global_type_created != null)
195                                 throw new InvalidOperationException ("global methods already created");
196                         if (global_type == null)
197                                 global_type = new TypeBuilder (this, 0);
198                         MethodBuilder mb = global_type.DefinePInvokeMethod (name, dllName, entryName, attributes, callingConvention, returnType, parameterTypes, nativeCallConv, nativeCharSet);
199
200                         addGlobalMethod (mb);
201                         return mb;
202                 }                       
203
204                 public TypeBuilder DefineType (string name) {
205                         return DefineType (name, 0);
206                 }
207
208                 public TypeBuilder DefineType (string name, TypeAttributes attr) {
209                         if ((attr & TypeAttributes.Interface) != 0)
210                                 return DefineType (name, attr, null, null);
211                         return DefineType (name, attr, typeof(object), null);
212                 }
213
214                 public TypeBuilder DefineType (string name, TypeAttributes attr, Type parent) {
215                         return DefineType (name, attr, parent, null);
216                 }
217
218                 private void AddType (TypeBuilder tb)
219                 {
220                         if (types != null) {
221                                 if (types.Length == num_types) {
222                                         TypeBuilder[] new_types = new TypeBuilder [types.Length * 2];
223                                         System.Array.Copy (types, new_types, num_types);
224                                         types = new_types;
225                                 }
226                         } else {
227                                 types = new TypeBuilder [1];
228                         }
229                         types [num_types] = tb;
230                         num_types ++;
231                 }
232
233                 private TypeBuilder DefineType (string name, TypeAttributes attr, Type parent, Type[] interfaces, PackingSize packsize, int typesize) {
234                         if (name_cache.Contains (name))
235                                 throw new ArgumentException ("Duplicate type name within an assembly.");
236
237                         TypeBuilder res = new TypeBuilder (this, name, attr, parent, interfaces, packsize, typesize, null);
238                         AddType (res);
239                         name_cache.Add (name, res);
240                         return res;
241                 }
242
243                 internal void RegisterTypeName (TypeBuilder tb, string name) {
244                         name_cache.Add (name, tb);
245                 }
246
247                 public TypeBuilder DefineType (string name, TypeAttributes attr, Type parent, Type[] interfaces) {
248                         return DefineType (name, attr, parent, interfaces, PackingSize.Unspecified, TypeBuilder.UnspecifiedTypeSize);
249                 }
250
251                 public TypeBuilder DefineType (string name, TypeAttributes attr, Type parent, int typesize) {
252                         return DefineType (name, attr, parent, null, PackingSize.Unspecified, TypeBuilder.UnspecifiedTypeSize);
253                 }
254
255                 public TypeBuilder DefineType (string name, TypeAttributes attr, Type parent, PackingSize packsize) {
256                         return DefineType (name, attr, parent, null, packsize, TypeBuilder.UnspecifiedTypeSize);
257                 }
258
259                 public TypeBuilder DefineType (string name, TypeAttributes attr, Type parent, PackingSize packsize, int typesize) {
260                         return DefineType (name, attr, parent, null, packsize, typesize);
261                 }
262
263                 public MethodInfo GetArrayMethod( Type arrayClass, string methodName, CallingConventions callingConvention, Type returnType, Type[] parameterTypes) {
264                         return new MonoArrayMethod (arrayClass, methodName, callingConvention, returnType, parameterTypes);
265                 }
266
267                 public EnumBuilder DefineEnum( string name, TypeAttributes visibility, Type underlyingType) {
268                         if (name_cache.Contains (name))
269                                 throw new ArgumentException ("Duplicate type name within an assembly.");
270
271                         EnumBuilder eb = new EnumBuilder (this, name, visibility, underlyingType);
272                         TypeBuilder res = eb.GetTypeBuilder ();
273                         AddType (res);
274                         name_cache.Add (name, res);
275                         return eb;
276                 }
277
278                 public override Type GetType( string className) {
279                         return GetType (className, false, false);
280                 }
281                 
282                 public override Type GetType( string className, bool ignoreCase) {
283                         return GetType (className, false, ignoreCase);
284                 }
285
286                 private TypeBuilder search_in_array (TypeBuilder[] arr, int validElementsInArray, string className) {
287                         int i;
288                         for (i = 0; i < validElementsInArray; ++i) {
289                                 if (String.Compare (className, arr [i].FullName, true, CultureInfo.InvariantCulture) == 0) {
290                                         return arr [i];
291                                 }
292                         }
293                         return null;
294                 }
295
296                 private TypeBuilder search_nested_in_array (TypeBuilder[] arr, int validElementsInArray, string className) {
297                         int i;
298                         for (i = 0; i < validElementsInArray; ++i) {
299                                 if (String.Compare (className, arr [i].Name, true, CultureInfo.InvariantCulture) == 0)
300                                         return arr [i];
301                         }
302                         return null;
303                 }
304
305                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
306                 private static extern Type create_modified_type (TypeBuilder tb, string modifiers);
307
308                 static readonly char [] type_modifiers = {'&', '[', '*'};
309
310                 private TypeBuilder GetMaybeNested (TypeBuilder t, string className) {
311                         int subt;
312                         string pname, rname;
313
314                         subt = className.IndexOf ('+');
315                         if (subt < 0) {
316                                 if (t.subtypes != null)
317                                         return search_nested_in_array (t.subtypes, t.subtypes.Length, className);
318                                 return null;
319                         }
320                         if (t.subtypes != null) {
321                                 pname = className.Substring (0, subt);
322                                 rname = className.Substring (subt + 1);
323                                 TypeBuilder result = search_nested_in_array (t.subtypes, t.subtypes.Length, pname);
324                                 if (result != null)
325                                         return GetMaybeNested (result, rname);
326                         }
327                         return null;
328                 }
329                 
330                 public override Type GetType (string className, bool throwOnError, bool ignoreCase) {
331                         int subt;
332                         string orig = className;
333                         string modifiers;
334                         TypeBuilder result = null;
335
336                         if (types == null && throwOnError)
337                                 throw new TypeLoadException (className);
338
339                         subt = className.IndexOfAny (type_modifiers);
340                         if (subt >= 0) {
341                                 modifiers = className.Substring (subt);
342                                 className = className.Substring (0, subt);
343                         } else
344                                 modifiers = null;
345
346                         if (!ignoreCase) {
347                                 result =  name_cache [className] as TypeBuilder;
348                         } else {
349                                 subt = className.IndexOf ('+');
350                                 if (subt < 0) {
351                                         if (types != null)
352                                                 result = search_in_array (types, num_types,  className);
353                                 } else {
354                                         string pname, rname;
355                                         pname = className.Substring (0, subt);
356                                         rname = className.Substring (subt + 1);
357                                         result = search_in_array (types, num_types, pname);
358                                         if (result != null)
359                                                 result = GetMaybeNested (result, rname);
360                                 }
361                         }
362                         if ((result == null) && throwOnError)
363                                 throw new TypeLoadException (orig);
364                         if (result != null && (modifiers != null))
365                                 return create_modified_type (result, modifiers);
366                         return result;
367                 }
368
369                 internal int get_next_table_index (object obj, int table, bool inc) {
370                         if (table_indexes == null) {
371                                 table_indexes = new int [64];
372                                 for (int i=0; i < 64; ++i)
373                                         table_indexes [i] = 1;
374                                 /* allow room for .<Module> in TypeDef table */
375                                 table_indexes [0x02] = 2;
376                         }
377                         // Console.WriteLine ("getindex for table "+table.ToString()+" got "+table_indexes [table].ToString());
378                         if (inc)
379                                 return table_indexes [table]++;
380                         return table_indexes [table];
381                 }
382
383                 public void SetCustomAttribute( CustomAttributeBuilder customBuilder) {
384                         if (cattrs != null) {
385                                 CustomAttributeBuilder[] new_array = new CustomAttributeBuilder [cattrs.Length + 1];
386                                 cattrs.CopyTo (new_array, 0);
387                                 new_array [cattrs.Length] = customBuilder;
388                                 cattrs = new_array;
389                         } else {
390                                 cattrs = new CustomAttributeBuilder [1];
391                                 cattrs [0] = customBuilder;
392                         }
393                 }
394                 public void SetCustomAttribute( ConstructorInfo con, byte[] binaryAttribute) {
395                         SetCustomAttribute (new CustomAttributeBuilder (con, binaryAttribute));
396                 }
397
398                 public ISymbolWriter GetSymWriter () {
399                         return null;
400                 }
401
402                 public ISymbolDocumentWriter DefineDocument (string url, Guid language, Guid languageVendor, Guid documentType) {
403                         return null;
404                 }
405
406                 public override Type [] GetTypes ()
407                 {
408                         if (types == null)
409                                 return new TypeBuilder [0];
410
411                         int n = num_types;
412                         TypeBuilder [] copy = new TypeBuilder [n];
413                         Array.Copy (types, copy, n);
414
415                         return copy;
416                 }
417
418                 public IResourceWriter DefineResource (string name, string description, ResourceAttributes attribute)
419                 {
420                         if (name == null)
421                                 throw new ArgumentNullException ("name");
422                         if (name == String.Empty)
423                                 throw new ArgumentException ("name cannot be empty");
424                         if (transient)
425                                 throw new InvalidOperationException ("The module is transient");
426                         if (!assemblyb.IsSave)
427                                 throw new InvalidOperationException ("The assembly is transient");
428                         ResourceWriter writer = new ResourceWriter (new MemoryStream ());
429                         if (resource_writers == null)
430                                 resource_writers = new ArrayList ();
431                         resource_writers.Add (writer);
432
433                         // The data is filled out later
434                         if (resources != null) {
435                                 MonoResource[] new_r = new MonoResource [resources.Length + 1];
436                                 System.Array.Copy(resources, new_r, resources.Length);
437                                 resources = new_r;
438                         } else {
439                                 resources = new MonoResource [1];
440                         }
441                         int p = resources.Length - 1;
442                         resources [p].name = name;
443                         resources [p].attrs = attribute;
444
445                         return writer;
446                 }
447
448                 public IResourceWriter DefineResource (string name, string description)
449                 {
450                         return DefineResource (name, description, ResourceAttributes.Public);
451                 }
452
453                 [MonoTODO]
454                 public void DefineUnmanagedResource (byte[] resource)
455                 {
456                         if (resource == null)
457                                 throw new ArgumentNullException ("resource");
458
459                         throw new NotImplementedException ();
460                 }
461
462                 [MonoTODO]
463                 public void DefineUnmanagedResource (string resourceFileName)
464                 {
465                         if (resourceFileName == null)
466                                 throw new ArgumentNullException ("resourceFileName");
467                         if (resourceFileName == String.Empty)
468                                 throw new ArgumentException ("resourceFileName");
469                         if (!File.Exists (resourceFileName) || Directory.Exists (resourceFileName))
470                                 throw new FileNotFoundException ("File '" + resourceFileName + "' does not exists or is a directory.");
471
472                         throw new NotImplementedException ();
473                 }
474
475                 [MonoTODO]
476                 public void SetSymCustomAttribute (string name, byte[] data)
477                 {
478                         throw new NotImplementedException ();
479                 }
480
481                 [MonoTODO]
482                 public void SetUserEntryPoint (MethodInfo entryPoint)
483                 {
484                         if (entryPoint == null)
485                                 throw new ArgumentNullException ("entryPoint");
486                         if (entryPoint.DeclaringType.Module != this)
487                                 throw new InvalidOperationException ("entryPoint is not contained in this module");
488                         throw new NotImplementedException ();
489                 }
490
491                 public MethodToken GetMethodToken (MethodInfo method)
492                 {
493                         if (method == null)
494                                 throw new ArgumentNullException ("method");
495                         if (method.DeclaringType.Module != this)
496                                 throw new InvalidOperationException ("The method is not in this module");
497                         return new MethodToken (GetToken (method));
498                 }
499
500                 public MethodToken GetArrayMethodToken (Type arrayClass, string methodName, CallingConventions callingConvention, Type returnType, Type[] parameterTypes)
501                 {
502                         return GetMethodToken (GetArrayMethod (arrayClass, methodName, callingConvention, returnType, parameterTypes));
503                 }
504
505
506                 public MethodToken GetConstructorToken (ConstructorInfo con)
507                 {
508                         if (con == null)
509                                 throw new ArgumentNullException ("con");
510                         return new MethodToken (GetToken (con));
511                 }
512
513                 public FieldToken GetFieldToken (FieldInfo field)
514                 {
515                         if (field == null)
516                                 throw new ArgumentNullException ("field");
517                         if (field.DeclaringType.Module != this)
518                                 throw new InvalidOperationException ("The method is not in this module");
519                         return new FieldToken (GetToken (field));
520                 }
521
522                 [MonoTODO]
523                 public SignatureToken GetSignatureToken (byte[] sigBytes, int sigLength)
524                 {
525                         throw new NotImplementedException ();
526                 }
527
528                 public SignatureToken GetSignatureToken (SignatureHelper sigHelper)
529                 {
530                         if (sigHelper == null)
531                                 throw new ArgumentNullException ("sigHelper");
532                         return new SignatureToken (GetToken (sigHelper));
533                 }
534
535                 public StringToken GetStringConstant (string str)
536                 {
537                         if (str == null)
538                                 throw new ArgumentNullException ("str");
539                         return new StringToken (GetToken (str));
540                 }
541
542                 public TypeToken GetTypeToken (Type type)
543                 {
544                         if (type == null)
545                                 throw new ArgumentNullException ("type");
546                         if (type.IsByRef)
547                                 throw new ArgumentException ("type can't be a byref type", "type");
548                         if (!IsTransient () && (type.Module is ModuleBuilder) && ((ModuleBuilder)type.Module).IsTransient ())
549                                 throw new InvalidOperationException ("a non-transient module can't reference a transient module");
550                         return new TypeToken (GetToken (type));
551                 }
552
553                 public TypeToken GetTypeToken (string type)
554                 {
555                         return GetTypeToken (GetType (name));
556                 }
557
558                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
559                 private static extern int getUSIndex (ModuleBuilder mb, string str);
560
561                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
562                 private static extern int getToken (ModuleBuilder mb, object obj);
563
564                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
565                 private static extern int getMethodToken (ModuleBuilder mb, MethodInfo method,
566                                                           Type[] opt_param_types);
567
568                 internal int GetToken (string str) {
569                         if (us_string_cache.Contains (str))
570                                 return (int)us_string_cache [str];
571                         int result = getUSIndex (this, str);
572                         us_string_cache [str] = result;
573                         return result;
574                 }
575
576                 internal int GetToken (MemberInfo member) {
577                         return getToken (this, member);
578                 }
579
580                 internal int GetToken (MethodInfo method, Type[] opt_param_types) {
581                         return getMethodToken (this, method, opt_param_types);
582                 }
583
584                 internal int GetToken (SignatureHelper helper) {
585                         return getToken (this, helper);
586                 }
587
588                 internal TokenGenerator GetTokenGenerator () {
589                         if (token_gen == null)
590                                 token_gen = new ModuleBuilderTokenGenerator (this);
591                         return token_gen;
592                 }
593
594                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
595                 private static extern void build_metadata (ModuleBuilder mb);
596
597                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
598                 private extern void WriteToFile (IntPtr handle);
599
600                 internal void Save ()
601                 {
602                         if (transient && !is_main)
603                                 return;
604
605                         if (types != null) {
606                                 for (int i = 0; i < num_types; ++i)
607                                         if (!types [i].is_created)
608                                                 throw new NotSupportedException ("Type '" + types [i].FullName + "' was not completed.");
609                         }
610
611                         if ((global_type != null) && (global_type_created == null))
612                                 global_type_created = global_type.CreateType ();
613
614                         if (resource_writers != null) {
615                                 for (int i = 0; i < resource_writers.Count; ++i) {
616                                         ResourceWriter writer = (ResourceWriter)resource_writers [i];
617                                         writer.Generate ();
618                                         MemoryStream stream = (MemoryStream)writer.Stream;
619                                         resources [i].data = new byte [stream.Length];
620                                         stream.Seek (0, SeekOrigin.Begin);
621                                         stream.Read (resources [i].data, 0, (int)stream.Length);
622                                 }                                       
623                         }
624
625                         build_metadata (this);
626
627                         string fileName = fqname;
628                         if (assemblyb.AssemblyDir != null)
629                                 fileName = Path.Combine (assemblyb.AssemblyDir, fileName);
630                         
631                         using (FileStream file = new FileStream (fileName, FileMode.Create, FileAccess.Write))
632                                 WriteToFile (file.Handle);
633                         
634                         //
635                         // The constant 0x80000000 is internal to Mono, it means `make executable'
636                         //
637                         File.SetAttributes (fileName, (FileAttributes) (unchecked ((int) 0x80000000)));
638                 }
639
640                 internal string FileName {
641                         get {
642                                 return fqname;
643                         }
644                 }
645
646                 internal bool IsMain {
647                         set {
648                                 is_main = value;
649                         }
650                 }
651
652                 internal void CreateGlobalType () {
653                         if (global_type == null)
654                                 global_type = new TypeBuilder (this, 0);
655                 }
656
657                 internal static Guid Mono_GetGuid (ModuleBuilder mb)
658                 {
659                         return new Guid (mb.guid);
660                 }
661         }
662
663         internal class ModuleBuilderTokenGenerator : TokenGenerator {
664
665                 private ModuleBuilder mb;
666
667                 public ModuleBuilderTokenGenerator (ModuleBuilder mb) {
668                         this.mb = mb;
669                 }
670
671                 public int GetToken (string str) {
672                         return mb.GetToken (str);
673                 }
674
675                 public int GetToken (MemberInfo member) {
676                         return mb.GetToken (member);
677                 }
678
679                 public int GetToken (MethodInfo method, Type[] opt_param_types) {
680                         return mb.GetToken (method, opt_param_types);
681                 }
682
683                 public int GetToken (SignatureHelper helper) {
684                         return mb.GetToken (helper);
685                 }
686         }
687 }