abc01249b8c7b9006f74bd357d8297e75dedb59b
[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                         return DefineType (name, attr, typeof(object), null);
210                 }
211
212                 public TypeBuilder DefineType (string name, TypeAttributes attr, Type parent) {
213                         return DefineType (name, attr, parent, null);
214                 }
215
216                 private TypeBuilder DefineType (string name, TypeAttributes attr, Type parent, Type[] interfaces, PackingSize packsize, int typesize) {
217                         if (name_cache.Contains (name))
218                                 throw new ArgumentException ("Duplicate type name within an assembly.");
219
220                         TypeBuilder res = new TypeBuilder (this, name, attr, parent, interfaces, packsize, typesize, null);
221                         if (types != null) {
222                                 if (types.Length == num_types) {
223                                         TypeBuilder[] new_types = new TypeBuilder [types.Length * 2];
224                                         System.Array.Copy (types, new_types, num_types);
225                                         types = new_types;
226                                 }
227                         } else {
228                                 types = new TypeBuilder [1];
229                         }
230                         types [num_types] = res;
231                         num_types ++;
232                         name_cache.Add (name, res);
233                         return res;
234                 }
235
236                 internal void RegisterTypeName (TypeBuilder tb, string name) {
237                         name_cache.Add (name, tb);
238                 }
239
240                 public TypeBuilder DefineType (string name, TypeAttributes attr, Type parent, Type[] interfaces) {
241                         return DefineType (name, attr, parent, interfaces, PackingSize.Unspecified, TypeBuilder.UnspecifiedTypeSize);
242                 }
243
244                 public TypeBuilder DefineType (string name, TypeAttributes attr, Type parent, int typesize) {
245                         return DefineType (name, attr, parent, null, PackingSize.Unspecified, TypeBuilder.UnspecifiedTypeSize);
246                 }
247
248                 public TypeBuilder DefineType (string name, TypeAttributes attr, Type parent, PackingSize packsize) {
249                         return DefineType (name, attr, parent, null, packsize, TypeBuilder.UnspecifiedTypeSize);
250                 }
251
252                 public TypeBuilder DefineType (string name, TypeAttributes attr, Type parent, PackingSize packsize, int typesize) {
253                         return DefineType (name, attr, parent, null, packsize, typesize);
254                 }
255
256                 public MethodInfo GetArrayMethod( Type arrayClass, string methodName, CallingConventions callingConvention, Type returnType, Type[] parameterTypes) {
257                         return new MonoArrayMethod (arrayClass, methodName, callingConvention, returnType, parameterTypes);
258                 }
259
260                 public EnumBuilder DefineEnum( string name, TypeAttributes visibility, Type underlyingType) {
261                         EnumBuilder eb = new EnumBuilder (this, name, visibility, underlyingType);
262                         return eb;
263                 }
264
265                 public override Type GetType( string className) {
266                         return GetType (className, false, false);
267                 }
268                 
269                 public override Type GetType( string className, bool ignoreCase) {
270                         return GetType (className, false, ignoreCase);
271                 }
272
273                 private TypeBuilder search_in_array (TypeBuilder[] arr, int validElementsInArray, string className) {
274                         int i;
275                         for (i = 0; i < validElementsInArray; ++i) {
276                                 if (String.Compare (className, arr [i].FullName, true, CultureInfo.InvariantCulture) == 0) {
277                                         return arr [i];
278                                 }
279                         }
280                         return null;
281                 }
282
283                 private TypeBuilder search_nested_in_array (TypeBuilder[] arr, int validElementsInArray, string className) {
284                         int i;
285                         for (i = 0; i < validElementsInArray; ++i) {
286                                 if (String.Compare (className, arr [i].Name, true, CultureInfo.InvariantCulture) == 0)
287                                         return arr [i];
288                         }
289                         return null;
290                 }
291
292                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
293                 private static extern Type create_modified_type (TypeBuilder tb, string modifiers);
294
295                 static readonly char [] type_modifiers = {'&', '[', '*'};
296
297                 private TypeBuilder GetMaybeNested (TypeBuilder t, string className) {
298                         int subt;
299                         string pname, rname;
300
301                         subt = className.IndexOf ('+');
302                         if (subt < 0) {
303                                 if (t.subtypes != null)
304                                         return search_nested_in_array (t.subtypes, t.subtypes.Length, className);
305                                 return null;
306                         }
307                         if (t.subtypes != null) {
308                                 pname = className.Substring (0, subt);
309                                 rname = className.Substring (subt + 1);
310                                 TypeBuilder result = search_nested_in_array (t.subtypes, t.subtypes.Length, pname);
311                                 if (result != null)
312                                         return GetMaybeNested (result, rname);
313                         }
314                         return null;
315                 }
316                 
317                 public override Type GetType (string className, bool throwOnError, bool ignoreCase) {
318                         int subt;
319                         string orig = className;
320                         string modifiers;
321                         TypeBuilder result = null;
322
323                         if (types == null && throwOnError)
324                                 throw new TypeLoadException (className);
325
326                         subt = className.IndexOfAny (type_modifiers);
327                         if (subt >= 0) {
328                                 modifiers = className.Substring (subt);
329                                 className = className.Substring (0, subt);
330                         } else
331                                 modifiers = null;
332
333                         if (!ignoreCase) {
334                                 result =  name_cache [className] as TypeBuilder;
335                         } else {
336                                 subt = className.IndexOf ('+');
337                                 if (subt < 0) {
338                                         if (types != null)
339                                                 result = search_in_array (types, num_types,  className);
340                                 } else {
341                                         string pname, rname;
342                                         pname = className.Substring (0, subt);
343                                         rname = className.Substring (subt + 1);
344                                         result = search_in_array (types, num_types, pname);
345                                         if (result != null)
346                                                 result = GetMaybeNested (result, rname);
347                                 }
348                         }
349                         if ((result == null) && throwOnError)
350                                 throw new TypeLoadException (orig);
351                         if (result != null && (modifiers != null))
352                                 return create_modified_type (result, modifiers);
353                         return result;
354                 }
355
356                 internal int get_next_table_index (object obj, int table, bool inc) {
357                         if (table_indexes == null) {
358                                 table_indexes = new int [64];
359                                 for (int i=0; i < 64; ++i)
360                                         table_indexes [i] = 1;
361                                 /* allow room for .<Module> in TypeDef table */
362                                 table_indexes [0x02] = 2;
363                         }
364                         // Console.WriteLine ("getindex for table "+table.ToString()+" got "+table_indexes [table].ToString());
365                         if (inc)
366                                 return table_indexes [table]++;
367                         return table_indexes [table];
368                 }
369
370                 public void SetCustomAttribute( CustomAttributeBuilder customBuilder) {
371                         if (cattrs != null) {
372                                 CustomAttributeBuilder[] new_array = new CustomAttributeBuilder [cattrs.Length + 1];
373                                 cattrs.CopyTo (new_array, 0);
374                                 new_array [cattrs.Length] = customBuilder;
375                                 cattrs = new_array;
376                         } else {
377                                 cattrs = new CustomAttributeBuilder [1];
378                                 cattrs [0] = customBuilder;
379                         }
380                 }
381                 public void SetCustomAttribute( ConstructorInfo con, byte[] binaryAttribute) {
382                         SetCustomAttribute (new CustomAttributeBuilder (con, binaryAttribute));
383                 }
384
385                 public ISymbolWriter GetSymWriter () {
386                         return null;
387                 }
388
389                 public ISymbolDocumentWriter DefineDocument (string url, Guid language, Guid languageVendor, Guid documentType) {
390                         return null;
391                 }
392
393                 public override Type [] GetTypes ()
394                 {
395                         if (types == null)
396                                 return new TypeBuilder [0];
397
398                         int n = num_types;
399                         TypeBuilder [] copy = new TypeBuilder [n];
400                         Array.Copy (types, copy, n);
401
402                         return copy;
403                 }
404
405                 public IResourceWriter DefineResource (string name, string description, ResourceAttributes attribute)
406                 {
407                         if (name == null)
408                                 throw new ArgumentNullException ("name");
409                         if (name == String.Empty)
410                                 throw new ArgumentException ("name cannot be empty");
411                         if (transient)
412                                 throw new InvalidOperationException ("The module is transient");
413                         if (!assemblyb.IsSave)
414                                 throw new InvalidOperationException ("The assembly is transient");
415                         ResourceWriter writer = new ResourceWriter (new MemoryStream ());
416                         if (resource_writers == null)
417                                 resource_writers = new ArrayList ();
418                         resource_writers.Add (writer);
419
420                         // The data is filled out later
421                         if (resources != null) {
422                                 MonoResource[] new_r = new MonoResource [resources.Length + 1];
423                                 System.Array.Copy(resources, new_r, resources.Length);
424                                 resources = new_r;
425                         } else {
426                                 resources = new MonoResource [1];
427                         }
428                         int p = resources.Length - 1;
429                         resources [p].name = name;
430                         resources [p].attrs = attribute;
431
432                         return writer;
433                 }
434
435                 public IResourceWriter DefineResource (string name, string description)
436                 {
437                         return DefineResource (name, description, ResourceAttributes.Public);
438                 }
439
440                 [MonoTODO]
441                 public void DefineUnmanagedResource (byte[] resource)
442                 {
443                         if (resource == null)
444                                 throw new ArgumentNullException ("resource");
445
446                         throw new NotImplementedException ();
447                 }
448
449                 [MonoTODO]
450                 public void DefineUnmanagedResource (string resourceFileName)
451                 {
452                         if (resourceFileName == null)
453                                 throw new ArgumentNullException ("resourceFileName");
454                         if (resourceFileName == String.Empty)
455                                 throw new ArgumentException ("resourceFileName");
456                         if (!File.Exists (resourceFileName) || Directory.Exists (resourceFileName))
457                                 throw new FileNotFoundException ("File '" + resourceFileName + "' does not exists or is a directory.");
458
459                         throw new NotImplementedException ();
460                 }
461
462                 [MonoTODO]
463                 public void SetSymCustomAttribute (string name, byte[] data)
464                 {
465                         throw new NotImplementedException ();
466                 }
467
468                 [MonoTODO]
469                 public void SetUserEntryPoint (MethodInfo entryPoint)
470                 {
471                         if (entryPoint == null)
472                                 throw new ArgumentNullException ("entryPoint");
473                         if (entryPoint.DeclaringType.Module != this)
474                                 throw new InvalidOperationException ("entryPoint is not contained in this module");
475                         throw new NotImplementedException ();
476                 }
477
478                 public MethodToken GetMethodToken (MethodInfo method)
479                 {
480                         if (method == null)
481                                 throw new ArgumentNullException ("method");
482                         if (method.DeclaringType.Module != this)
483                                 throw new InvalidOperationException ("The method is not in this module");
484                         return new MethodToken (GetToken (method));
485                 }
486
487                 public MethodToken GetArrayMethodToken (Type arrayClass, string methodName, CallingConventions callingConvention, Type returnType, Type[] parameterTypes)
488                 {
489                         return GetMethodToken (GetArrayMethod (arrayClass, methodName, callingConvention, returnType, parameterTypes));
490                 }
491
492
493                 public MethodToken GetConstructorToken (ConstructorInfo con)
494                 {
495                         if (con == null)
496                                 throw new ArgumentNullException ("con");
497                         return new MethodToken (GetToken (con));
498                 }
499
500                 public FieldToken GetFieldToken (FieldInfo field)
501                 {
502                         if (field == null)
503                                 throw new ArgumentNullException ("field");
504                         if (field.DeclaringType.Module != this)
505                                 throw new InvalidOperationException ("The method is not in this module");
506                         return new FieldToken (GetToken (field));
507                 }
508
509                 [MonoTODO]
510                 public SignatureToken GetSignatureToken (byte[] sigBytes, int sigLength)
511                 {
512                         throw new NotImplementedException ();
513                 }
514
515                 public SignatureToken GetSignatureToken (SignatureHelper sigHelper)
516                 {
517                         if (sigHelper == null)
518                                 throw new ArgumentNullException ("sigHelper");
519                         return new SignatureToken (GetToken (sigHelper));
520                 }
521
522                 public StringToken GetStringConstant (string str)
523                 {
524                         if (str == null)
525                                 throw new ArgumentNullException ("str");
526                         return new StringToken (GetToken (str));
527                 }
528
529                 public TypeToken GetTypeToken (Type type)
530                 {
531                         if (type == null)
532                                 throw new ArgumentNullException ("type");
533                         if (type.IsByRef)
534                                 throw new ArgumentException ("type can't be a byref type", "type");
535                         if (!IsTransient () && (type.Module is ModuleBuilder) && ((ModuleBuilder)type.Module).IsTransient ())
536                                 throw new InvalidOperationException ("a non-transient module can't reference a transient module");
537                         return new TypeToken (GetToken (type));
538                 }
539
540                 public TypeToken GetTypeToken (string type)
541                 {
542                         return GetTypeToken (GetType (name));
543                 }
544
545                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
546                 private static extern int getUSIndex (ModuleBuilder mb, string str);
547
548                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
549                 private static extern int getToken (ModuleBuilder mb, object obj);
550
551                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
552                 private static extern int getMethodToken (ModuleBuilder mb, MethodInfo method,
553                                                           Type[] opt_param_types);
554
555                 internal int GetToken (string str) {
556                         if (us_string_cache.Contains (str))
557                                 return (int)us_string_cache [str];
558                         int result = getUSIndex (this, str);
559                         us_string_cache [str] = result;
560                         return result;
561                 }
562
563                 internal int GetToken (MemberInfo member) {
564                         return getToken (this, member);
565                 }
566
567                 internal int GetToken (MethodInfo method, Type[] opt_param_types) {
568                         return getMethodToken (this, method, opt_param_types);
569                 }
570
571                 internal int GetToken (SignatureHelper helper) {
572                         return getToken (this, helper);
573                 }
574
575                 internal TokenGenerator GetTokenGenerator () {
576                         if (token_gen == null)
577                                 token_gen = new ModuleBuilderTokenGenerator (this);
578                         return token_gen;
579                 }
580
581                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
582                 private static extern void build_metadata (ModuleBuilder mb);
583
584                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
585                 private extern void WriteToFile (IntPtr handle);
586
587                 internal void Save ()
588                 {
589                         if (transient && !is_main)
590                                 return;
591
592                         if (types != null) {
593                                 for (int i = 0; i < num_types; ++i)
594                                         if (!types [i].is_created)
595                                                 throw new NotSupportedException ("Type '" + types [i].FullName + "' was not completed.");
596                         }
597
598                         if ((global_type != null) && (global_type_created == null))
599                                 global_type_created = global_type.CreateType ();
600
601                         if (resource_writers != null) {
602                                 for (int i = 0; i < resource_writers.Count; ++i) {
603                                         ResourceWriter writer = (ResourceWriter)resource_writers [i];
604                                         writer.Generate ();
605                                         MemoryStream stream = (MemoryStream)writer.Stream;
606                                         resources [i].data = new byte [stream.Length];
607                                         stream.Seek (0, SeekOrigin.Begin);
608                                         stream.Read (resources [i].data, 0, (int)stream.Length);
609                                 }                                       
610                         }
611
612                         build_metadata (this);
613
614                         string fileName = fqname;
615                         if (assemblyb.AssemblyDir != null)
616                                 fileName = Path.Combine (assemblyb.AssemblyDir, fileName);
617                         
618                         using (FileStream file = new FileStream (fileName, FileMode.Create, FileAccess.Write))
619                                 WriteToFile (file.Handle);
620                         
621                         //
622                         // The constant 0x80000000 is internal to Mono, it means `make executable'
623                         //
624                         File.SetAttributes (fileName, (FileAttributes) (unchecked ((int) 0x80000000)));
625                 }
626
627                 internal string FileName {
628                         get {
629                                 return fqname;
630                         }
631                 }
632
633                 internal bool IsMain {
634                         set {
635                                 is_main = value;
636                         }
637                 }
638
639                 internal void CreateGlobalType () {
640                         if (global_type == null)
641                                 global_type = new TypeBuilder (this, 0);
642                 }
643
644                 internal static Guid Mono_GetGuid (ModuleBuilder mb)
645                 {
646                         return new Guid (mb.guid);
647                 }
648         }
649
650         internal class ModuleBuilderTokenGenerator : TokenGenerator {
651
652                 private ModuleBuilder mb;
653
654                 public ModuleBuilderTokenGenerator (ModuleBuilder mb) {
655                         this.mb = mb;
656                 }
657
658                 public int GetToken (string str) {
659                         return mb.GetToken (str);
660                 }
661
662                 public int GetToken (MemberInfo member) {
663                         return mb.GetToken (member);
664                 }
665
666                 public int GetToken (MethodInfo method, Type[] opt_param_types) {
667                         return mb.GetToken (method, opt_param_types);
668                 }
669
670                 public int GetToken (SignatureHelper helper) {
671                         return mb.GetToken (helper);
672                 }
673         }
674 }