Ooops.
[mono.git] / mcs / class / corlib / System.Reflection.Emit / ModuleBuilder.cs
index bf93fb61a9ad90752573960a006ec605be52043c..3925bcb9f4e0f225bc6bd1a7b53376fcbafcff0e 100644 (file)
@@ -1,4 +1,27 @@
 
+//
+// Copyright (C) 2004 Novell, Inc (http://www.novell.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
 //
 // System.Reflection.Emit/ModuleBuilder.cs
 //
@@ -16,11 +39,16 @@ using System.Runtime.InteropServices;
 using System.Diagnostics.SymbolStore;
 using System.IO;
 using System.Resources;
-using Mono.CSharp.Debugger;
 using System.Globalization;
 
 namespace System.Reflection.Emit {
+#if NET_2_0
+       [ComVisible (true)]
+       [ClassInterfaceAttribute (ClassInterfaceType.None)]
+       [ComDefaultInterfaceAttribute (typeof (_ModuleBuilder))]
+#endif
        public class ModuleBuilder : Module {
+               #region Sync with reflection.h
                private IntPtr dynamic_image;
                private int num_types;
                private TypeBuilder[] types;
@@ -31,14 +59,17 @@ namespace System.Reflection.Emit {
                private MethodBuilder[] global_methods;
                private FieldBuilder[] global_fields;
                bool is_main;
+               private MonoResource[] resources;
+               #endregion
                private TypeBuilder global_type;
                private Type global_type_created;
-               internal IMonoSymbolWriter symbol_writer;
                Hashtable name_cache;
                Hashtable us_string_cache = new Hashtable ();
                private int[] table_indexes;
                bool transient;
                ModuleBuilderTokenGenerator token_gen;
+               ArrayList resource_writers = null;
+               ISymbolWriter symbolWriter;
 
                [MethodImplAttribute(MethodImplOptions.InternalCall)]
                private static extern void basic_init (ModuleBuilder ab);
@@ -48,48 +79,26 @@ namespace System.Reflection.Emit {
                        this.fqname = fullyqname;
                        this.assembly = this.assemblyb = assb;
                        this.transient = transient;
-                       guid = Guid.NewGuid().ToByteArray ();
+                       // to keep mcs fast we do not want CryptoConfig wo be involved to create the RNG
+                       guid = Guid.FastNewGuidArray ();
+                       // guid = Guid.NewGuid().ToByteArray ();
                        table_idx = get_next_table_index (this, 0x00, true);
                        name_cache = new Hashtable ();
 
-                       if (emitSymbolInfo)
-                               GetSymbolWriter (fullyqname);
                        basic_init (this);
-               }
-
-               internal void GetSymbolWriter (string filename)
-               {
-                       Assembly assembly;
-                       try {
-                               assembly = Assembly.Load ("Mono.CSharp.Debugger");
-                       } catch (FileNotFoundException) {
-                               return;
-                       }
 
-                       Type type = assembly.GetType ("Mono.CSharp.Debugger.MonoSymbolWriter");
-                       if (type == null)
-                               return;
-
-                       // First get the constructor.
-                       {
-                               Type[] arg_types = new Type [1];
-                               arg_types [0] = typeof (ModuleBuilder);
-                               ConstructorInfo constructor = type.GetConstructor (arg_types);
-
-                               object[] args = new object [1];
-                               args [0] = this;
-
-                               if (constructor == null)
-                                       return;
-
-                               Object instance = constructor.Invoke (args);
-                               if (instance == null)
-                                       return;
-
-                               if (!(instance is IMonoSymbolWriter))
-                                       return;
-
-                               symbol_writer = (IMonoSymbolWriter) instance;
+                       CreateGlobalType ();
+                       
+                       if (emitSymbolInfo) {
+                               Assembly asm = Assembly.LoadWithPartialName ("Mono.CompilerServices.SymbolWriter");
+                               Type t = asm.GetType ("Mono.CompilerServices.SymbolWriter.SymbolWriterImpl");
+                               if (t != null) {
+                                       symbolWriter = (ISymbolWriter) Activator.CreateInstance (t, new object[] { this });
+                                       string fileName = fqname;
+                                       if (assemblyb.AssemblyDir != null)
+                                               fileName = Path.Combine (assemblyb.AssemblyDir, fileName);
+                                       symbolWriter.Initialize (IntPtr.Zero, fileName, true);
+                               }
                        }
                }
 
@@ -170,7 +179,7 @@ namespace System.Reflection.Emit {
                        return DefineGlobalMethod (name, attributes, callingConvention, returnType, null, null, parameterTypes, null, null);
                }
 
-#if NET_1_2
+#if NET_2_0 || BOOTSTRAP_NET_2_0
                public
 #else
                internal
@@ -215,6 +224,8 @@ namespace System.Reflection.Emit {
                }
 
                public TypeBuilder DefineType (string name, TypeAttributes attr) {
+                       if ((attr & TypeAttributes.Interface) != 0)
+                               return DefineType (name, attr, null, null);
                        return DefineType (name, attr, typeof(object), null);
                }
 
@@ -222,8 +233,8 @@ namespace System.Reflection.Emit {
                        return DefineType (name, attr, parent, null);
                }
 
-               private TypeBuilder DefineType (string name, TypeAttributes attr, Type parent, Type[] interfaces, PackingSize packsize, int typesize) {
-                       TypeBuilder res = new TypeBuilder (this, name, attr, parent, interfaces, packsize, typesize, null);
+               private void AddType (TypeBuilder tb)
+               {
                        if (types != null) {
                                if (types.Length == num_types) {
                                        TypeBuilder[] new_types = new TypeBuilder [types.Length * 2];
@@ -233,8 +244,16 @@ namespace System.Reflection.Emit {
                        } else {
                                types = new TypeBuilder [1];
                        }
-                       types [num_types] = res;
+                       types [num_types] = tb;
                        num_types ++;
+               }
+
+               private TypeBuilder DefineType (string name, TypeAttributes attr, Type parent, Type[] interfaces, PackingSize packsize, int typesize) {
+                       if (name_cache.Contains (name))
+                               throw new ArgumentException ("Duplicate type name within an assembly.");
+
+                       TypeBuilder res = new TypeBuilder (this, name, attr, parent, interfaces, packsize, typesize, null);
+                       AddType (res);
                        name_cache.Add (name, res);
                        return res;
                }
@@ -243,6 +262,9 @@ namespace System.Reflection.Emit {
                        name_cache.Add (name, tb);
                }
 
+#if NET_2_0
+               [ComVisible (true)]
+#endif
                public TypeBuilder DefineType (string name, TypeAttributes attr, Type parent, Type[] interfaces) {
                        return DefineType (name, attr, parent, interfaces, PackingSize.Unspecified, TypeBuilder.UnspecifiedTypeSize);
                }
@@ -264,21 +286,33 @@ namespace System.Reflection.Emit {
                }
 
                public EnumBuilder DefineEnum( string name, TypeAttributes visibility, Type underlyingType) {
+                       if (name_cache.Contains (name))
+                               throw new ArgumentException ("Duplicate type name within an assembly.");
+
                        EnumBuilder eb = new EnumBuilder (this, name, visibility, underlyingType);
+                       TypeBuilder res = eb.GetTypeBuilder ();
+                       AddType (res);
+                       name_cache.Add (name, res);
                        return eb;
                }
 
+#if NET_2_0
+               [ComVisible (true)]
+#endif
                public override Type GetType( string className) {
                        return GetType (className, false, false);
                }
                
+#if NET_2_0
+               [ComVisible (true)]
+#endif
                public override Type GetType( string className, bool ignoreCase) {
                        return GetType (className, false, ignoreCase);
                }
 
-               private TypeBuilder search_in_array (TypeBuilder[] arr, string className) {
+               private TypeBuilder search_in_array (TypeBuilder[] arr, int validElementsInArray, string className) {
                        int i;
-                       for (i = 0; i < arr.Length; ++i) {
+                       for (i = 0; i < validElementsInArray; ++i) {
                                if (String.Compare (className, arr [i].FullName, true, CultureInfo.InvariantCulture) == 0) {
                                        return arr [i];
                                }
@@ -286,9 +320,9 @@ namespace System.Reflection.Emit {
                        return null;
                }
 
-               private TypeBuilder search_nested_in_array (TypeBuilder[] arr, string className) {
+               private TypeBuilder search_nested_in_array (TypeBuilder[] arr, int validElementsInArray, string className) {
                        int i;
-                       for (i = 0; i < arr.Length; ++i) {
+                       for (i = 0; i < validElementsInArray; ++i) {
                                if (String.Compare (className, arr [i].Name, true, CultureInfo.InvariantCulture) == 0)
                                        return arr [i];
                        }
@@ -298,7 +332,7 @@ namespace System.Reflection.Emit {
                [MethodImplAttribute(MethodImplOptions.InternalCall)]
                private static extern Type create_modified_type (TypeBuilder tb, string modifiers);
 
-               static char[] type_modifiers = {'&', '[', '*'};
+               static readonly char [] type_modifiers = {'&', '[', '*'};
 
                private TypeBuilder GetMaybeNested (TypeBuilder t, string className) {
                        int subt;
@@ -307,19 +341,22 @@ namespace System.Reflection.Emit {
                        subt = className.IndexOf ('+');
                        if (subt < 0) {
                                if (t.subtypes != null)
-                                       return search_nested_in_array (t.subtypes, className);
+                                       return search_nested_in_array (t.subtypes, t.subtypes.Length, className);
                                return null;
                        }
                        if (t.subtypes != null) {
                                pname = className.Substring (0, subt);
                                rname = className.Substring (subt + 1);
-                               TypeBuilder result = search_nested_in_array (t.subtypes, pname);
+                               TypeBuilder result = search_nested_in_array (t.subtypes, t.subtypes.Length, pname);
                                if (result != null)
                                        return GetMaybeNested (result, rname);
                        }
                        return null;
                }
-               
+
+#if NET_2_0
+               [ComVisible (true)]
+#endif         
                public override Type GetType (string className, bool throwOnError, bool ignoreCase) {
                        int subt;
                        string orig = className;
@@ -342,12 +379,12 @@ namespace System.Reflection.Emit {
                                subt = className.IndexOf ('+');
                                if (subt < 0) {
                                        if (types != null)
-                                               result = search_in_array (types, className);
+                                               result = search_in_array (types, num_types,  className);
                                } else {
                                        string pname, rname;
                                        pname = className.Substring (0, subt);
                                        rname = className.Substring (subt + 1);
-                                       result = search_in_array (types, pname);
+                                       result = search_in_array (types, num_types, pname);
                                        if (result != null)
                                                result = GetMaybeNested (result, rname);
                                }
@@ -384,19 +421,24 @@ namespace System.Reflection.Emit {
                                cattrs [0] = customBuilder;
                        }
                }
+
+#if NET_2_0
+               [ComVisible (true)]
+#endif
                public void SetCustomAttribute( ConstructorInfo con, byte[] binaryAttribute) {
                        SetCustomAttribute (new CustomAttributeBuilder (con, binaryAttribute));
                }
 
                public ISymbolWriter GetSymWriter () {
-                       return symbol_writer;
+                       return symbolWriter;
                }
 
-               public ISymbolDocumentWriter DefineDocument (string url, Guid language, Guid languageVendor, Guid documentType) {
-                       if (symbol_writer == null)
-                               throw new InvalidOperationException ();
-
-                       return symbol_writer.DefineDocument (url, language, languageVendor, documentType);
+               public ISymbolDocumentWriter DefineDocument (string url, Guid language, Guid languageVendor, Guid documentType)
+               {
+                       if (symbolWriter != null)
+                               return symbolWriter.DefineDocument (url, language, languageVendor, documentType);
+                       else
+                               return null;
                }
 
                public override Type [] GetTypes ()
@@ -404,14 +446,13 @@ namespace System.Reflection.Emit {
                        if (types == null)
                                return new TypeBuilder [0];
 
-                       int n = types.Length;
+                       int n = num_types;
                        TypeBuilder [] copy = new TypeBuilder [n];
                        Array.Copy (types, copy, n);
 
                        return copy;
                }
 
-               [MonoTODO]
                public IResourceWriter DefineResource (string name, string description, ResourceAttributes attribute)
                {
                        if (name == null)
@@ -422,7 +463,24 @@ namespace System.Reflection.Emit {
                                throw new InvalidOperationException ("The module is transient");
                        if (!assemblyb.IsSave)
                                throw new InvalidOperationException ("The assembly is transient");
-                       throw new NotImplementedException ();
+                       ResourceWriter writer = new ResourceWriter (new MemoryStream ());
+                       if (resource_writers == null)
+                               resource_writers = new ArrayList ();
+                       resource_writers.Add (writer);
+
+                       // The data is filled out later
+                       if (resources != null) {
+                               MonoResource[] new_r = new MonoResource [resources.Length + 1];
+                               System.Array.Copy(resources, new_r, resources.Length);
+                               resources = new_r;
+                       } else {
+                               resources = new MonoResource [1];
+                       }
+                       int p = resources.Length - 1;
+                       resources [p].name = name;
+                       resources [p].attrs = attribute;
+
+                       return writer;
                }
 
                public IResourceWriter DefineResource (string name, string description)
@@ -482,7 +540,9 @@ namespace System.Reflection.Emit {
                        return GetMethodToken (GetArrayMethod (arrayClass, methodName, callingConvention, returnType, parameterTypes));
                }
 
-
+#if NET_2_0
+               [ComVisible (true)]
+#endif
                public MethodToken GetConstructorToken (ConstructorInfo con)
                {
                        if (con == null)
@@ -541,6 +601,10 @@ namespace System.Reflection.Emit {
                [MethodImplAttribute(MethodImplOptions.InternalCall)]
                private static extern int getToken (ModuleBuilder mb, object obj);
 
+               [MethodImplAttribute(MethodImplOptions.InternalCall)]
+               private static extern int getMethodToken (ModuleBuilder mb, MethodInfo method,
+                                                         Type[] opt_param_types);
+
                internal int GetToken (string str) {
                        if (us_string_cache.Contains (str))
                                return (int)us_string_cache [str];
@@ -553,6 +617,10 @@ namespace System.Reflection.Emit {
                        return getToken (this, member);
                }
 
+               internal int GetToken (MethodInfo method, Type[] opt_param_types) {
+                       return getMethodToken (this, method, opt_param_types);
+               }
+
                internal int GetToken (SignatureHelper helper) {
                        return getToken (this, helper);
                }
@@ -567,46 +635,52 @@ namespace System.Reflection.Emit {
                private static extern void build_metadata (ModuleBuilder mb);
 
                [MethodImplAttribute(MethodImplOptions.InternalCall)]
-               private static extern int getDataChunk (ModuleBuilder mb, byte[] buf, int offset);
+               private extern void WriteToFile (IntPtr handle);
 
                internal void Save ()
                {
-                       if (transient)
+                       if (transient && !is_main)
                                return;
 
-                       build_metadata (this);
-
-                       if (symbol_writer != null) {
-                               string res_name;
-                               if (is_main)
-                                       res_name = "MonoSymbolFile";
-                               else
-                                       res_name = "MonoSymbolFile:" + fqname;
-                               byte[] data = symbol_writer.CreateSymbolFile (assemblyb);
-                               assemblyb.EmbedResource (res_name, data, ResourceAttributes.Public);
+                       if (types != null) {
+                               for (int i = 0; i < num_types; ++i)
+                                       if (!types [i].is_created)
+                                               throw new NotSupportedException ("Type '" + types [i].FullName + "' was not completed.");
                        }
 
-                       string fileName = fqname;
-                       if (assemblyb.AssemblyDir != null)
-                               fileName = System.IO.Path.Combine (assemblyb.AssemblyDir, fileName);
-
-                       byte[] buf = new byte [65536];
-                       FileStream file;
-                       int count, offset;
-
-                       file = new FileStream (fileName, FileMode.Create, FileAccess.Write);
+                       if ((global_type != null) && (global_type_created == null))
+                               global_type_created = global_type.CreateType ();
 
-                       offset = 0;
-                       while ((count = getDataChunk (this, buf, offset)) != 0) {
-                               file.Write (buf, 0, count);
-                               offset += count;
+                       if (resource_writers != null) {
+                               for (int i = 0; i < resource_writers.Count; ++i) {
+                                       ResourceWriter writer = (ResourceWriter)resource_writers [i];
+                                       writer.Generate ();
+                                       MemoryStream stream = (MemoryStream)writer.Stream;
+                                       resources [i].data = new byte [stream.Length];
+                                       stream.Seek (0, SeekOrigin.Begin);
+                                       stream.Read (resources [i].data, 0, (int)stream.Length);
+                               }                                       
                        }
-                       file.Close ();
 
+                       build_metadata (this);
+
+                       string fileName = fqname;
+                       if (assemblyb.AssemblyDir != null)
+                               fileName = Path.Combine (assemblyb.AssemblyDir, fileName);
+                       
+                       using (FileStream file = new FileStream (fileName, FileMode.Create, FileAccess.Write))
+                               WriteToFile (file.Handle);
+                       
                        //
                        // The constant 0x80000000 is internal to Mono, it means `make executable'
                        //
                        File.SetAttributes (fileName, (FileAttributes) (unchecked ((int) 0x80000000)));
+                       
+                       if (types != null && symbolWriter != null) {
+                               for (int i = 0; i < num_types; ++i)
+                                       types [i].GenerateDebugInfo (symbolWriter);
+                               symbolWriter.Close ();
+                       }
                }
 
                internal string FileName {
@@ -620,6 +694,16 @@ namespace System.Reflection.Emit {
                                is_main = value;
                        }
                }
+
+               internal void CreateGlobalType () {
+                       if (global_type == null)
+                               global_type = new TypeBuilder (this, 0);
+               }
+
+               internal static Guid Mono_GetGuid (ModuleBuilder mb)
+               {
+                       return new Guid (mb.guid);
+               }
        }
 
        internal class ModuleBuilderTokenGenerator : TokenGenerator {
@@ -638,8 +722,13 @@ namespace System.Reflection.Emit {
                        return mb.GetToken (member);
                }
 
+               public int GetToken (MethodInfo method, Type[] opt_param_types) {
+                       return mb.GetToken (method, opt_param_types);
+               }
+
                public int GetToken (SignatureHelper helper) {
                        return mb.GetToken (helper);
                }
        }
 }
+