2007-01-25 Radek Doulik <rodo@novell.com>
[mono.git] / mcs / class / corlib / System.Reflection.Emit / ModuleBuilder.cs
1
2 //
3 // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
4 //
5 // Permission is hereby granted, free of charge, to any person obtaining
6 // a copy of this software and associated documentation files (the
7 // "Software"), to deal in the Software without restriction, including
8 // without limitation the rights to use, copy, modify, merge, publish,
9 // distribute, sublicense, and/or sell copies of the Software, and to
10 // permit persons to whom the Software is furnished to do so, subject to
11 // the following conditions:
12 // 
13 // The above copyright notice and this permission notice shall be
14 // included in all copies or substantial portions of the Software.
15 // 
16 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
19 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
20 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
21 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
22 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
23 //
24
25 //
26 // System.Reflection.Emit/ModuleBuilder.cs
27 //
28 // Author:
29 //   Paolo Molaro (lupus@ximian.com)
30 //
31 // (C) 2001 Ximian, Inc.  http://www.ximian.com
32 //
33
34 using System;
35 using System.Reflection;
36 using System.Collections;
37 using System.Runtime.CompilerServices;
38 using System.Runtime.InteropServices;
39 using System.Diagnostics.SymbolStore;
40 using System.IO;
41 using System.Resources;
42 using System.Globalization;
43
44 namespace System.Reflection.Emit {
45 #if NET_2_0
46         [ComVisible (true)]
47         [ComDefaultInterface (typeof (_ModuleBuilder))]
48 #endif
49         [ClassInterface (ClassInterfaceType.None)]
50         public class ModuleBuilder : Module, _ModuleBuilder {
51                 #region Sync with object-internals.h
52                 private UIntPtr dynamic_image; /* GC-tracked */
53                 private int num_types;
54                 private TypeBuilder[] types;
55                 private CustomAttributeBuilder[] cattrs;
56                 private byte[] guid;
57                 private int table_idx;
58                 internal AssemblyBuilder assemblyb;
59                 private MethodBuilder[] global_methods;
60                 private FieldBuilder[] global_fields;
61                 bool is_main;
62                 private MonoResource[] resources;
63                 #endregion
64                 private TypeBuilder global_type;
65                 private Type global_type_created;
66                 Hashtable name_cache;
67                 Hashtable us_string_cache = new Hashtable ();
68                 private int[] table_indexes;
69                 bool transient;
70                 ModuleBuilderTokenGenerator token_gen;
71                 Hashtable resource_writers;
72                 ISymbolWriter symbolWriter;
73
74                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
75                 private static extern void basic_init (ModuleBuilder ab);
76
77                 internal ModuleBuilder (AssemblyBuilder assb, string name, string fullyqname, bool emitSymbolInfo, bool transient) {
78                         this.name = this.scopename = name;
79                         this.fqname = fullyqname;
80                         this.assembly = this.assemblyb = assb;
81                         this.transient = transient;
82                         // to keep mcs fast we do not want CryptoConfig wo be involved to create the RNG
83                         guid = Guid.FastNewGuidArray ();
84                         // guid = Guid.NewGuid().ToByteArray ();
85                         table_idx = get_next_table_index (this, 0x00, true);
86                         name_cache = new Hashtable ();
87
88                         basic_init (this);
89
90                         CreateGlobalType ();
91                         
92                         if (emitSymbolInfo) {
93                                 Assembly asm = Assembly.LoadWithPartialName ("Mono.CompilerServices.SymbolWriter");
94                                 Type t = asm.GetType ("Mono.CompilerServices.SymbolWriter.SymbolWriterImpl");
95                                 if (t != null) {
96                                         symbolWriter = (ISymbolWriter) Activator.CreateInstance (t, new object[] { this });
97                                         string fileName = fqname;
98                                         if (assemblyb.AssemblyDir != null)
99                                                 fileName = Path.Combine (assemblyb.AssemblyDir, fileName);
100                                         symbolWriter.Initialize (IntPtr.Zero, fileName, true);
101                                 }
102                         }
103                 }
104
105                 public override string FullyQualifiedName {get { return fqname;}}
106
107                 public bool IsTransient () {
108                         return transient;
109                 }
110
111                 public void CreateGlobalFunctions () 
112                 {
113                         if (global_type_created != null)
114                                 throw new InvalidOperationException ("global methods already created");
115                         if (global_type != null)
116                                 global_type_created = global_type.CreateType ();
117                 }
118
119                 public FieldBuilder DefineInitializedData( string name, byte[] data, FieldAttributes attributes) {
120                         if (data == null)
121                                 throw new ArgumentNullException ("data");
122
123                         FieldBuilder fb = DefineUninitializedData (name, data.Length, 
124                                                                                                            attributes | FieldAttributes.HasFieldRVA);
125                         fb.SetRVAData (data);
126
127                         return fb;
128                 }
129
130                 public FieldBuilder DefineUninitializedData( string name, int size, FieldAttributes attributes) {
131                         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                                 Type mt = create_modified_type (result, modifiers);
396                                 if (mt is TypeBuilder)
397                                         result = mt as TypeBuilder;
398                                 else
399                                         return mt;
400                         }
401                         if (result != null && result.is_created)
402                                 return result.CreateType ();
403                         else
404                                 return result;
405                 }
406
407                 internal int get_next_table_index (object obj, int table, bool inc) {
408                         if (table_indexes == null) {
409                                 table_indexes = new int [64];
410                                 for (int i=0; i < 64; ++i)
411                                         table_indexes [i] = 1;
412                                 /* allow room for .<Module> in TypeDef table */
413                                 table_indexes [0x02] = 2;
414                         }
415                         // Console.WriteLine ("getindex for table "+table.ToString()+" got "+table_indexes [table].ToString());
416                         if (inc)
417                                 return table_indexes [table]++;
418                         return table_indexes [table];
419                 }
420
421                 public void SetCustomAttribute( CustomAttributeBuilder customBuilder) {
422                         if (cattrs != null) {
423                                 CustomAttributeBuilder[] new_array = new CustomAttributeBuilder [cattrs.Length + 1];
424                                 cattrs.CopyTo (new_array, 0);
425                                 new_array [cattrs.Length] = customBuilder;
426                                 cattrs = new_array;
427                         } else {
428                                 cattrs = new CustomAttributeBuilder [1];
429                                 cattrs [0] = customBuilder;
430                         }
431                 }
432
433 #if NET_2_0
434                 [ComVisible (true)]
435 #endif
436                 public void SetCustomAttribute( ConstructorInfo con, byte[] binaryAttribute) {
437                         SetCustomAttribute (new CustomAttributeBuilder (con, binaryAttribute));
438                 }
439
440                 public ISymbolWriter GetSymWriter () {
441                         return symbolWriter;
442                 }
443
444                 public ISymbolDocumentWriter DefineDocument (string url, Guid language, Guid languageVendor, Guid documentType)
445                 {
446                         if (symbolWriter != null)
447                                 return symbolWriter.DefineDocument (url, language, languageVendor, documentType);
448                         else
449                                 return null;
450                 }
451
452                 public override Type [] GetTypes ()
453                 {
454                         if (types == null)
455                                 return new TypeBuilder [0];
456
457                         int n = num_types;
458                         TypeBuilder [] copy = new TypeBuilder [n];
459                         Array.Copy (types, copy, n);
460
461                         return copy;
462                 }
463
464                 public IResourceWriter DefineResource (string name, string description, ResourceAttributes attribute)
465                 {
466                         if (name == null)
467                                 throw new ArgumentNullException ("name");
468                         if (name == String.Empty)
469                                 throw new ArgumentException ("name cannot be empty");
470                         if (transient)
471                                 throw new InvalidOperationException ("The module is transient");
472                         if (!assemblyb.IsSave)
473                                 throw new InvalidOperationException ("The assembly is transient");
474                         ResourceWriter writer = new ResourceWriter (new MemoryStream ());
475                         if (resource_writers == null)
476                                 resource_writers = new Hashtable ();
477                         resource_writers [name] = writer;
478
479                         // The data is filled out later
480                         if (resources != null) {
481                                 MonoResource[] new_r = new MonoResource [resources.Length + 1];
482                                 System.Array.Copy(resources, new_r, resources.Length);
483                                 resources = new_r;
484                         } else {
485                                 resources = new MonoResource [1];
486                         }
487                         int p = resources.Length - 1;
488                         resources [p].name = name;
489                         resources [p].attrs = attribute;
490
491                         return writer;
492                 }
493
494                 public IResourceWriter DefineResource (string name, string description)
495                 {
496                         return DefineResource (name, description, ResourceAttributes.Public);
497                 }
498
499                 [MonoTODO]
500                 public void DefineUnmanagedResource (byte[] resource)
501                 {
502                         if (resource == null)
503                                 throw new ArgumentNullException ("resource");
504
505                         throw new NotImplementedException ();
506                 }
507
508                 [MonoTODO]
509                 public void DefineUnmanagedResource (string resourceFileName)
510                 {
511                         if (resourceFileName == null)
512                                 throw new ArgumentNullException ("resourceFileName");
513                         if (resourceFileName == String.Empty)
514                                 throw new ArgumentException ("resourceFileName");
515                         if (!File.Exists (resourceFileName) || Directory.Exists (resourceFileName))
516                                 throw new FileNotFoundException ("File '" + resourceFileName + "' does not exists or is a directory.");
517
518                         throw new NotImplementedException ();
519                 }
520
521 #if NET_2_0
522                 public void DefineManifestResource (string name, Stream stream, ResourceAttributes attribute) {
523                         if (name == null)
524                                 throw new ArgumentNullException ("name");
525                         if (name == String.Empty)
526                                 throw new ArgumentException ("name cannot be empty");
527                         if (stream == null)
528                                 throw new ArgumentNullException ("stream");
529                         if (transient)
530                                 throw new InvalidOperationException ("The module is transient");
531                         if (!assemblyb.IsSave)
532                                 throw new InvalidOperationException ("The assembly is transient");
533
534                         if (resources != null) {
535                                 MonoResource[] new_r = new MonoResource [resources.Length + 1];
536                                 System.Array.Copy(resources, new_r, resources.Length);
537                                 resources = new_r;
538                         } else {
539                                 resources = new MonoResource [1];
540                         }
541                         int p = resources.Length - 1;
542                         resources [p].name = name;
543                         resources [p].attrs = attribute;
544                         resources [p].stream = stream;
545                 }
546 #endif
547
548                 [MonoTODO]
549                 public void SetSymCustomAttribute (string name, byte[] data)
550                 {
551                         throw new NotImplementedException ();
552                 }
553
554                 [MonoTODO]
555                 public void SetUserEntryPoint (MethodInfo entryPoint)
556                 {
557                         if (entryPoint == null)
558                                 throw new ArgumentNullException ("entryPoint");
559                         if (entryPoint.DeclaringType.Module != this)
560                                 throw new InvalidOperationException ("entryPoint is not contained in this module");
561                         throw new NotImplementedException ();
562                 }
563
564                 public MethodToken GetMethodToken (MethodInfo method)
565                 {
566                         if (method == null)
567                                 throw new ArgumentNullException ("method");
568                         if (method.DeclaringType.Module != this)
569                                 throw new InvalidOperationException ("The method is not in this module");
570                         return new MethodToken (GetToken (method));
571                 }
572
573                 public MethodToken GetArrayMethodToken (Type arrayClass, string methodName, CallingConventions callingConvention, Type returnType, Type[] parameterTypes)
574                 {
575                         return GetMethodToken (GetArrayMethod (arrayClass, methodName, callingConvention, returnType, parameterTypes));
576                 }
577
578 #if NET_2_0
579                 [ComVisible (true)]
580 #endif
581                 public MethodToken GetConstructorToken (ConstructorInfo con)
582                 {
583                         if (con == null)
584                                 throw new ArgumentNullException ("con");
585                         return new MethodToken (GetToken (con));
586                 }
587
588                 public FieldToken GetFieldToken (FieldInfo field)
589                 {
590                         if (field == null)
591                                 throw new ArgumentNullException ("field");
592                         if (field.DeclaringType.Module != this)
593                                 throw new InvalidOperationException ("The method is not in this module");
594                         return new FieldToken (GetToken (field));
595                 }
596
597                 [MonoTODO]
598                 public SignatureToken GetSignatureToken (byte[] sigBytes, int sigLength)
599                 {
600                         throw new NotImplementedException ();
601                 }
602
603                 public SignatureToken GetSignatureToken (SignatureHelper sigHelper)
604                 {
605                         if (sigHelper == null)
606                                 throw new ArgumentNullException ("sigHelper");
607                         return new SignatureToken (GetToken (sigHelper));
608                 }
609
610                 public StringToken GetStringConstant (string str)
611                 {
612                         if (str == null)
613                                 throw new ArgumentNullException ("str");
614                         return new StringToken (GetToken (str));
615                 }
616
617                 public TypeToken GetTypeToken (Type type)
618                 {
619                         if (type == null)
620                                 throw new ArgumentNullException ("type");
621                         if (type.IsByRef)
622                                 throw new ArgumentException ("type can't be a byref type", "type");
623                         if (!IsTransient () && (type.Module is ModuleBuilder) && ((ModuleBuilder)type.Module).IsTransient ())
624                                 throw new InvalidOperationException ("a non-transient module can't reference a transient module");
625                         return new TypeToken (GetToken (type));
626                 }
627
628                 public TypeToken GetTypeToken (string type)
629                 {
630                         return GetTypeToken (GetType (name));
631                 }
632
633                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
634                 private static extern int getUSIndex (ModuleBuilder mb, string str);
635
636                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
637                 private static extern int getToken (ModuleBuilder mb, object obj);
638
639                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
640                 private static extern int getMethodToken (ModuleBuilder mb, MethodInfo method,
641                                                           Type[] opt_param_types);
642
643                 internal int GetToken (string str) {
644                         if (us_string_cache.Contains (str))
645                                 return (int)us_string_cache [str];
646                         int result = getUSIndex (this, str);
647                         us_string_cache [str] = result;
648                         return result;
649                 }
650
651                 internal int GetToken (MemberInfo member) {
652                         return getToken (this, member);
653                 }
654
655                 internal int GetToken (MethodInfo method, Type[] opt_param_types) {
656                         return getMethodToken (this, method, opt_param_types);
657                 }
658
659                 internal int GetToken (SignatureHelper helper) {
660                         return getToken (this, helper);
661                 }
662
663                 internal TokenGenerator GetTokenGenerator () {
664                         if (token_gen == null)
665                                 token_gen = new ModuleBuilderTokenGenerator (this);
666                         return token_gen;
667                 }
668
669                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
670                 private static extern void build_metadata (ModuleBuilder mb);
671
672                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
673                 private extern void WriteToFile (IntPtr handle);
674
675                 internal void Save ()
676                 {
677                         if (transient && !is_main)
678                                 return;
679
680                         if (types != null) {
681                                 for (int i = 0; i < num_types; ++i)
682                                         if (!types [i].is_created)
683                                                 throw new NotSupportedException ("Type '" + types [i].FullName + "' was not completed.");
684                         }
685
686                         if ((global_type != null) && (global_type_created == null))
687                                 global_type_created = global_type.CreateType ();
688
689                         if (resources != null) {
690                                 for (int i = 0; i < resources.Length; ++i) {
691                                         IResourceWriter rwriter;
692                                         if (resource_writers != null && (rwriter = resource_writers [resources [i].name] as IResourceWriter) != null) {
693                                                 ResourceWriter writer = (ResourceWriter)rwriter;
694                                                 writer.Generate ();
695                                                 MemoryStream mstream = (MemoryStream)writer.Stream;
696                                                 resources [i].data = new byte [mstream.Length];
697                                                 mstream.Seek (0, SeekOrigin.Begin);
698                                                 mstream.Read (resources [i].data, 0, (int)mstream.Length);
699                                                 continue;
700                                         }
701                                         Stream stream = resources [i].stream;
702
703                                         // According to MSDN docs, the stream is read during assembly save, not earlier
704                                         if (stream != null) {
705                                                 try {
706                                                         long len = stream.Length;
707                                                         resources [i].data = new byte [len];
708                                                         stream.Seek (0, SeekOrigin.Begin);
709                                                         stream.Read (resources [i].data, 0, (int)len);
710                                                 } catch {
711                                                         /* do something */
712                                                 }
713                                         }
714                                 }
715                         }
716
717                         build_metadata (this);
718
719                         string fileName = fqname;
720                         if (assemblyb.AssemblyDir != null)
721                                 fileName = Path.Combine (assemblyb.AssemblyDir, fileName);
722
723                         try {
724                                 // We mmap the file, so unlink the previous version since it may be in use
725                                 File.Delete (fileName);
726                         } catch {
727                                 // We can safely ignore
728                         }
729                         using (FileStream file = new FileStream (fileName, FileMode.Create, FileAccess.Write))
730                                 WriteToFile (file.Handle);
731                         
732                         //
733                         // The constant 0x80000000 is internal to Mono, it means `make executable'
734                         //
735                         File.SetAttributes (fileName, (FileAttributes) (unchecked ((int) 0x80000000)));
736                         
737                         if (types != null && symbolWriter != null) {
738                                 for (int i = 0; i < num_types; ++i)
739                                         types [i].GenerateDebugInfo (symbolWriter);
740                                 symbolWriter.Close ();
741                         }
742                 }
743
744                 internal string FileName {
745                         get {
746                                 return fqname;
747                         }
748                 }
749
750                 internal bool IsMain {
751                         set {
752                                 is_main = value;
753                         }
754                 }
755
756                 internal void CreateGlobalType () {
757                         if (global_type == null)
758                                 global_type = new TypeBuilder (this, 0);
759                 }
760
761                 internal static Guid Mono_GetGuid (ModuleBuilder mb)
762                 {
763                         return new Guid (mb.guid);
764                 }
765
766                 void _ModuleBuilder.GetIDsOfNames ([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
767                 {
768                         throw new NotImplementedException ();
769                 }
770
771                 void _ModuleBuilder.GetTypeInfo (uint iTInfo, uint lcid, IntPtr ppTInfo)
772                 {
773                         throw new NotImplementedException ();
774                 }
775
776                 void _ModuleBuilder.GetTypeInfoCount (out uint pcTInfo)
777                 {
778                         throw new NotImplementedException ();
779                 }
780
781                 void _ModuleBuilder.Invoke (uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
782                 {
783                         throw new NotImplementedException ();
784                 }
785         }
786
787         internal class ModuleBuilderTokenGenerator : TokenGenerator {
788
789                 private ModuleBuilder mb;
790
791                 public ModuleBuilderTokenGenerator (ModuleBuilder mb) {
792                         this.mb = mb;
793                 }
794
795                 public int GetToken (string str) {
796                         return mb.GetToken (str);
797                 }
798
799                 public int GetToken (MemberInfo member) {
800                         return mb.GetToken (member);
801                 }
802
803                 public int GetToken (MethodInfo method, Type[] opt_param_types) {
804                         return mb.GetToken (method, opt_param_types);
805                 }
806
807                 public int GetToken (SignatureHelper helper) {
808                         return mb.GetToken (helper);
809                 }
810         }
811 }
812