2004-01-13 Zoltan Varga <vargaz@freemail.hu>
[mono.git] / mcs / class / corlib / System.Reflection.Emit / AssemblyBuilder.cs
index e2b71189c387b35f5a0a5971a7627a4e02c4f3e2..c7487443bd4a90ba24afac2268ed778a8afd3e8b 100755 (executable)
@@ -17,17 +17,48 @@ using System.Globalization;
 using System.Runtime.CompilerServices;
 using System.Collections;
 using System.Runtime.InteropServices;
+using System.Security.Cryptography;
+using System.Security.Permissions;
+
+using Mono.Security;
+using Mono.Security.Cryptography;
 
 namespace System.Reflection.Emit {
 
+       internal struct RefEmitPermissionSet {
+               public SecurityAction action;
+               public string pset;
+
+               public RefEmitPermissionSet (SecurityAction action, string pset) {
+                       this.action = action;
+                       this.pset = pset;
+               }
+       }
+
        internal struct MonoResource {
                public byte[] data;
                public string name;
                public string filename;
                public ResourceAttributes attrs;
+               public int offset;
+       }
+
+       internal struct MonoWin32Resource {
+               public int res_type;
+               public int res_id;
+               public int lang_id;
+               public byte[] data;
+
+               public MonoWin32Resource (int res_type, int res_id, int lang_id, byte[] data) {
+                       this.res_type = res_type;
+                       this.res_id = res_id;
+                       this.lang_id = lang_id;
+                       this.data = data;
+               }
        }
 
        public sealed class AssemblyBuilder : Assembly {
+               #region Sync with reflection.h
                private IntPtr dynamic_assembly;
                private MethodInfo entry_point;
                private ModuleBuilder[] modules;
@@ -35,7 +66,7 @@ namespace System.Reflection.Emit {
                private string dir;
                private CustomAttributeBuilder[] cattrs;
                private MonoResource[] resources;
-               string keyfile;
+               byte[] public_key;
                string version;
                string culture;
                uint algid;
@@ -43,21 +74,27 @@ namespace System.Reflection.Emit {
                PEFileKinds pekind = PEFileKinds.Dll;
                bool delay_sign;
                uint access;
+               Module[] loaded_modules;
+               MonoWin32Resource[] win32_resources;
+               #endregion
                internal Type corlib_object_type = typeof (System.Object);
                internal Type corlib_value_type = typeof (System.ValueType);
                internal Type corlib_enum_type = typeof (System.Enum);
                internal Type corlib_void_type = typeof (void);
-               private int[] table_indexes;
-               Hashtable us_string_cache = new Hashtable ();
                ArrayList resource_writers = null;
+               Win32VersionResource version_res;
                bool created;
+               bool is_module_only;
 
                [MethodImplAttribute(MethodImplOptions.InternalCall)]
                private static extern void basic_init (AssemblyBuilder ab);
                
                internal AssemblyBuilder (AssemblyName n, string directory, AssemblyBuilderAccess access) {
                        name = n.Name;
-                       dir = directory;
+                       if (directory == null || directory == String.Empty)
+                               dir = Directory.GetCurrentDirectory ();
+                       else
+                               dir = directory;
                        this.access = (uint)access;
 
                        /* Set defaults from n */
@@ -72,20 +109,6 @@ namespace System.Reflection.Emit {
                        basic_init (this);
                }
 
-               internal int get_next_table_index (object obj, int table, bool inc) {
-                       if (table_indexes == null) {
-                               table_indexes = new int [64];
-                               for (int i=0; i < 64; ++i)
-                                       table_indexes [i] = 1;
-                               /* allow room for .<Module> in TypeDef table */
-                               table_indexes [0x02] = 2;
-                       }
-                       // Console.WriteLine ("getindex for table "+table.ToString()+" got "+table_indexes [table].ToString());
-                       if (inc)
-                               return table_indexes [table]++;
-                       return table_indexes [table];
-               }
-
                public override string CodeBase {
                        get {
                                throw not_supported ();
@@ -104,6 +127,15 @@ namespace System.Reflection.Emit {
                        }
                }
 
+#if NET_1_1
+               /* This is to keep signature compatibility with MS.NET */
+               public override string ImageRuntimeVersion {
+                       get {
+                               return base.ImageRuntimeVersion;
+                       }
+               }
+#endif
+
                public void AddResourceFile (string name, string fileName)
                {
                        AddResourceFile (name, fileName, ResourceAttributes.Public);
@@ -200,8 +232,8 @@ namespace System.Reflection.Emit {
                        return DefineDynamicModule (name, fileName, emitSymbolInfo, false);
                }
 
-               public ModuleBuilder DefineDynamicModule (string name, string fileName,
-                                                         bool emitSymbolInfo, bool transient)
+               private ModuleBuilder DefineDynamicModule (string name, string fileName,
+                                                                                                  bool emitSymbolInfo, bool transient)
                {
                        check_name_and_filename (name, fileName, false);
 
@@ -214,20 +246,47 @@ namespace System.Reflection.Emit {
                                        throw new InvalidOperationException ("Assembly was already saved.");
                        }
 
-                       ModuleBuilder r = new ModuleBuilder (this, name, fileName, emitSymbolInfo, modules == null, transient);
+                       ModuleBuilder r = new ModuleBuilder (this, name, fileName, emitSymbolInfo, transient);
+
+                       if ((modules != null) && is_module_only)
+                               throw new InvalidOperationException ("A module-only assembly can only contain one module.");
 
                        if (modules != null) {
                                ModuleBuilder[] new_modules = new ModuleBuilder [modules.Length + 1];
                                System.Array.Copy(modules, new_modules, modules.Length);
-                               new_modules [modules.Length] = r;
                                modules = new_modules;
                        } else {
                                modules = new ModuleBuilder [1];
-                               modules [0] = r;
                        }
+                       modules [modules.Length - 1] = r;
                        return r;
                }
 
+               [MethodImplAttribute(MethodImplOptions.InternalCall)]
+               private extern Module InternalAddModule (string fileName);
+
+               /*
+                * Mono extension to support /addmodule in mcs.
+                */
+               internal Module AddModule (string fileName)
+               {
+                       if (fileName == null)
+                               throw new ArgumentNullException (fileName);
+
+                       Module m = InternalAddModule (fileName);
+
+                       if (loaded_modules != null) {
+                               Module[] new_modules = new Module [loaded_modules.Length + 1];
+                               System.Array.Copy (loaded_modules, new_modules, loaded_modules.Length);
+                               loaded_modules = new_modules;
+                       } else {
+                               loaded_modules = new Module [1];
+                       }
+                       loaded_modules [loaded_modules.Length - 1] = m;
+
+                       return m;
+               }
+
                public IResourceWriter DefineResource (string name, string description, string fileName)
                {
                        return DefineResource (name, description, fileName, ResourceAttributes.Public);
@@ -247,16 +306,35 @@ namespace System.Reflection.Emit {
                        return writer;
                }
 
+               private void AddUnmanagedResource (Win32Resource res) {
+                       MemoryStream ms = new MemoryStream ();
+                       res.WriteTo (ms);
+
+                       if (win32_resources != null) {
+                               MonoWin32Resource[] new_res = new MonoWin32Resource [win32_resources.Length + 1];
+                               System.Array.Copy (win32_resources, new_res, win32_resources.Length);
+                               win32_resources = new_res;
+                       }
+                       else
+                               win32_resources = new MonoWin32Resource [1];
+
+                       win32_resources [win32_resources.Length - 1] = new MonoWin32Resource (res.Type.Id, res.Name.Id, res.Language, ms.ToArray ());
+               }
+
                [MonoTODO]
                public void DefineUnmanagedResource (byte[] resource)
                {
                        if (resource == null)
                                throw new ArgumentNullException ("resource");
 
+                       /*
+                        * The format of the argument byte array is not documented
+                        * so this method is impossible to implement.
+                        */
+
                        throw new NotImplementedException ();
                }
 
-               [MonoTODO]
                public void DefineUnmanagedResource (string resourceFileName)
                {
                        if (resourceFileName == null)
@@ -266,20 +344,106 @@ namespace System.Reflection.Emit {
                        if (!File.Exists (resourceFileName) || Directory.Exists (resourceFileName))
                                throw new FileNotFoundException ("File '" + resourceFileName + "' does not exists or is a directory.");
 
-                       throw new NotImplementedException ();
+                       using (FileStream fs = new FileStream (resourceFileName, FileMode.Open)) {
+                               Win32ResFileReader reader = new Win32ResFileReader (fs);
+
+                               foreach (Win32EncodedResource res in reader.ReadResources ()) {
+                                       if (res.Name.IsName || res.Type.IsName)
+                                               throw new InvalidOperationException ("resource files with named resources or non-default resource types are not supported.");
+
+                                       AddUnmanagedResource (res);
+                               }
+                       }
                }
 
-               [MonoTODO]
                public void DefineVersionInfoResource ()
                {
-                       throw new NotImplementedException ();
+                       if (version_res != null)
+                               throw new ArgumentException ("Native resource has already been defined.");                      
+
+                       version_res = new Win32VersionResource (1, 0);
+
+                       if (cattrs != null) {
+                               foreach (CustomAttributeBuilder cb in cattrs) {
+                                       string attrname = cb.Ctor.ReflectedType.FullName;
+
+                                       if (attrname == "System.Reflection.AssemblyProductAttribute")
+                                               version_res.ProductName = cb.string_arg ();
+                                       else if (attrname == "System.Reflection.AssemblyCompanyAttribute")
+                                               version_res.CompanyName = cb.string_arg ();
+                                       else if (attrname == "System.Reflection.AssemblyCopyrightAttribute")
+                                               version_res.LegalCopyright = cb.string_arg ();
+                                       else if (attrname == "System.Reflection.AssemblyTrademarkAttribute")
+                                               version_res.LegalTrademarks = cb.string_arg ();
+                                       else if (attrname == "System.Reflection.AssemblyCultureAttribute")
+                                               version_res.FileLanguage = new CultureInfo (cb.string_arg ()).LCID;
+                                       else if (attrname == "System.Reflection.AssemblyFileVersionAttribute")
+                                               version_res.FileVersion = cb.string_arg ();
+                                       else if (attrname == "System.Reflection.AssemblyInformationalVersionAttribute")
+                                               version_res.ProductVersion = cb.string_arg ();
+                                       else if (attrname == "System.Reflection.AssemblyTitleAttribute")
+                                               version_res.FileDescription = cb.string_arg ();
+                                       else if (attrname == "System.Reflection.AssemblyDescriptionAttribute")
+                                               version_res.Comments = cb.string_arg ();
+                               }
+                       }
                }
 
-               [MonoTODO]
                public void DefineVersionInfoResource (string product, string productVersion,
                                                       string company, string copyright, string trademark)
                {
-                       throw new NotImplementedException ();
+                       if (version_res != null)
+                               throw new ArgumentException ("Native resource has already been defined.");
+
+                       /*
+                        * We can only create the resource later, when the file name and
+                        * the binary version is known.
+                        */
+
+                       version_res = new Win32VersionResource (1, 0);
+                       version_res.ProductName = product;
+                       version_res.ProductVersion = productVersion;
+                       version_res.CompanyName = company;
+                       version_res.LegalCopyright = copyright;
+                       version_res.LegalTrademarks = trademark;
+               }
+
+               /* 
+                * Mono extension to support /win32icon in mcs
+                */
+               internal void DefineIconResource (string iconFileName)
+               {
+                       if (iconFileName == null)
+                               throw new ArgumentNullException ("iconFileName");
+                       if (iconFileName == String.Empty)
+                               throw new ArgumentException ("iconFileName");
+                       if (!File.Exists (iconFileName) || Directory.Exists (iconFileName))
+                               throw new FileNotFoundException ("File '" + iconFileName + "' does not exists or is a directory.");
+
+                       using (FileStream fs = new FileStream (iconFileName, FileMode.Open)) {
+                               Win32IconFileReader reader = new Win32IconFileReader (fs);
+                               
+                               ICONDIRENTRY[] entries = reader.ReadIcons ();
+
+                               Win32IconResource[] icons = new Win32IconResource [entries.Length];
+                               for (int i = 0; i < entries.Length; ++i) {
+                                       icons [i] = new Win32IconResource (i + 1, 0, entries [i]);
+                                       AddUnmanagedResource (icons [i]);
+                               }
+
+                               Win32GroupIconResource group = new Win32GroupIconResource (1, 0, icons);
+                               AddUnmanagedResource (group);
+                       }
+               }
+
+               private void DefineVersionInfoResourceImpl (string fileName) {
+                       // Add missing info
+                       if (version_res.FileVersion == "0.0.0.0")
+                               version_res.FileVersion = version;
+                       version_res.InternalName = Path.GetFileNameWithoutExtension (fileName);
+                       version_res.OriginalFilename = fileName;
+
+                       AddUnmanagedResource (version_res);
                }
 
                public ModuleBuilder GetDynamicModule (string name)
@@ -306,10 +470,6 @@ namespace System.Reflection.Emit {
                        throw not_supported ();
                }
 
-               public override FileStream[] GetFiles() {
-                       throw not_supported ();
-               }
-
                public override FileStream[] GetFiles(bool getResourceModules) {
                        throw not_supported ();
                }
@@ -329,43 +489,34 @@ namespace System.Reflection.Emit {
                        throw not_supported ();
                }
 
-               [MethodImplAttribute(MethodImplOptions.InternalCall)]
-               private static extern int getUSIndex (AssemblyBuilder ab, string str);
-
-               [MethodImplAttribute(MethodImplOptions.InternalCall)]
-               private static extern int getToken (AssemblyBuilder ab, object obj);
-
-               internal int GetToken (string str) {
-                       if (us_string_cache.Contains (str))
-                               return (int)us_string_cache [str];
-                       int result = getUSIndex (this, str);
-                       us_string_cache [str] = result;
-                       return result;
-               }
-               
-               internal int GetToken (MemberInfo member) {
-                       return getToken (this, member);
+               internal bool IsSave {
+                       get {
+                               return access != (uint)AssemblyBuilderAccess.Run;
+                       }
                }
 
-               internal int GetToken (SignatureHelper helper) {
-                       return getToken (this, helper);
+               internal string AssemblyDir {
+                       get {
+                               return dir;
+                       }
                }
 
-               internal bool IsSave {
+               /*
+                * Mono extension. If this is set, the assembly can only contain one
+                * module, access should be Save, and the saved image will not contain an
+                * assembly manifest.
+                */
+               internal bool IsModuleOnly {
                        get {
-                               return access != (uint)AssemblyBuilderAccess.Run;
+                               return is_module_only;
+                       }
+                       set {
+                               is_module_only = value;
                        }
                }
 
-               [MethodImplAttribute(MethodImplOptions.InternalCall)]
-               private static extern int getDataChunk (AssemblyBuilder ab, byte[] buf, int offset);
-
                public void Save (string assemblyFileName)
                {
-                       byte[] buf = new byte [65536];
-                       FileStream file;
-                       int count, offset;
-
                        if (resource_writers != null) {
                                foreach (IResourceWriter writer in resource_writers) {
                                        writer.Generate ();
@@ -373,35 +524,33 @@ namespace System.Reflection.Emit {
                                }
                        }
 
-                       build_metadata (this);
-
-                       foreach (ModuleBuilder module in modules)
-                               module.Save ();
-
-                       if (dir != null) {
-                               assemblyFileName = String.Format ("{0}{1}{2}", dir, System.IO.Path.DirectorySeparatorChar, assemblyFileName);
+                       // Create a main module if not already created
+                       ModuleBuilder mainModule = null;
+                       if (modules != null) {
+                               foreach (ModuleBuilder module in modules)
+                                       if (module.FullyQualifiedName == assemblyFileName)
+                                               mainModule = module;
                        }
+                       if (mainModule == null)
+                               mainModule = DefineDynamicModule ("RefEmit_OnDiskManifestModule", assemblyFileName);
 
-                       file = new FileStream (assemblyFileName, FileMode.Create, FileAccess.Write);
+                       if (!is_module_only)
+                               mainModule.IsMain = true;
 
-                       offset = 0;
-                       while ((count = getDataChunk (this, buf, offset)) != 0) {
-                               file.Write (buf, 0, count);
-                               offset += count;
-                       }
-                       file.Close ();
+                       if (version_res != null)
+                               DefineVersionInfoResourceImpl (assemblyFileName);
+                       
+                       foreach (ModuleBuilder module in modules)
+                               if (module != mainModule)
+                                       module.Save ();
 
-                       created = true;
+                       // Write out the main module at the end, because it needs to
+                       // contain the hash of the other modules
+                       mainModule.Save ();
 
-                       //
-                       // The constant 0x80000000 is internal to Mono, it means `make executable'
-                       //
-                       File.SetAttributes (assemblyFileName, (FileAttributes) (unchecked ((int) 0x80000000)));
+                       created = true;
                }
 
-               [MethodImplAttribute(MethodImplOptions.InternalCall)]
-               private static extern void build_metadata (AssemblyBuilder ab);
-
                public void SetEntryPoint (MethodInfo entryMethod)
                {
                        SetEntryPoint (entryMethod, PEFileKinds.ConsoleApplication);
@@ -418,29 +567,45 @@ namespace System.Reflection.Emit {
                        pekind = fileKind;
                }
 
-               public void SetCustomAttribute( CustomAttributeBuilder customBuilder) {
+               public void SetCustomAttribute( CustomAttributeBuilder customBuilder) 
+               {
                        if (customBuilder == null)
                                throw new ArgumentNullException ("customBuilder");
 
                        string attrname = customBuilder.Ctor.ReflectedType.FullName;
                        byte[] data;
                        int len, pos;
+                       Mono.Security.StrongName sn;
                        if (attrname == "System.Reflection.AssemblyVersionAttribute") {
-                               data = customBuilder.Data;
-                               pos = 2;
-                               len = CustomAttributeBuilder.decode_len (data, pos, out pos);
-                               version = CustomAttributeBuilder.string_from_bytes (data, pos, len);
+                               version = create_assembly_version (customBuilder.string_arg ());
                                return;
                        } else if (attrname == "System.Reflection.AssemblyKeyFileAttribute") {
-                               data = customBuilder.Data;
-                               pos = 2;
-                               len = CustomAttributeBuilder.decode_len (data, pos, out pos);
-                               keyfile = CustomAttributeBuilder.string_from_bytes (data, pos, len);
+                               string keyfile_name = customBuilder.string_arg ();
+                               if (keyfile_name == String.Empty)
+                                       return;
+                               using (FileStream fs = new FileStream (keyfile_name, FileMode.Open)) {
+                                       byte[] snkeypair = new byte [fs.Length];
+                                       fs.Read (snkeypair, 0, snkeypair.Length);
+
+                                       // this will import public or private/public keys
+                                       RSA rsa = CryptoConvert.FromCapiKeyBlob (snkeypair);
+                                       // and export only the public part
+                                       sn = new Mono.Security.StrongName (rsa);
+                                       public_key = sn.PublicKey;
+                               }
+                               return;
+                       } else if (attrname == "System.Reflection.AssemblyKeyNameAttribute") {
+                               string key_name = customBuilder.string_arg ();
+                               if (key_name == String.Empty)
+                                       return;
+                               CspParameters csparam = new CspParameters ();
+                               csparam.KeyContainerName = key_name;
+                               RSA rsacsp = new RSACryptoServiceProvider (csparam);
+                               sn = new Mono.Security.StrongName (rsacsp);
+                               public_key = sn.PublicKey;
+                               return;
                        } else if (attrname == "System.Reflection.AssemblyCultureAttribute") {
-                               data = customBuilder.Data;
-                               pos = 2;
-                               len = CustomAttributeBuilder.decode_len (data, pos, out pos);
-                               culture = CustomAttributeBuilder.string_from_bytes (data, pos, len);
+                               culture = customBuilder.string_arg ();
                        } else if (attrname == "System.Reflection.AssemblyAlgorithmIdAttribute") {
                                data = customBuilder.Data;
                                pos = 2;
@@ -471,7 +636,7 @@ namespace System.Reflection.Emit {
                                cattrs [0] = customBuilder;
                        }
                }
-               public void SetCustomAttribute( ConstructorInfo con, byte[] binaryAttribute) {
+               public void SetCustomAttribute ( ConstructorInfo con, byte[] binaryAttribute) {
                        if (con == null)
                                throw new ArgumentNullException ("con");
                        if (binaryAttribute == null)
@@ -537,6 +702,41 @@ namespace System.Reflection.Emit {
                                                throw new ArgumentException ("Duplicate name '" + name + "'");
                                }
                        }
-               }                       
+               }
+
+               private String create_assembly_version (String version) {
+                       String[] parts = version.Split ('.');
+                       int[] ver = new int [4] { 0, 0, 0, 0 };
+
+                       if ((parts.Length < 0) || (parts.Length > 4))
+                               throw new ArgumentException ("The version specified '" + version + "' is invalid");
+
+                       for (int i = 0; i < parts.Length; ++i) {
+                               if (parts [i] == "*") {
+                                       DateTime now = DateTime.Now;
+
+                                       if (i == 2) {
+                                               ver [2] = (now - new DateTime (2000, 1, 1)).Days;
+                                               if (parts.Length == 3)
+                                                       ver [3] = (now.Second + (now.Minute * 60) + (now.Hour * 3600)) / 2;
+                                       }
+                                       else
+                                               if (i == 3)
+                                                       ver [3] = (now.Second + (now.Minute * 60) + (now.Hour * 3600)) / 2;
+                                       else
+                                               throw new ArgumentException ("The version specified '" + version + "' is invalid");
+                               }
+                               else {
+                                       try {
+                                               ver [i] = Int32.Parse (parts [i]);
+                                       }
+                                       catch (FormatException) {
+                                               throw new ArgumentException ("The version specified '" + version + "' is invalid");
+                                       }
+                               }
+                       }
+
+                       return ver [0] + "." + ver [1] + "." + ver [2] + "." + ver [3];
+               }
        }
 }