2 // System.Reflection.Emit/AssemblyBuilder.cs
5 // Paolo Molaro (lupus@ximian.com)
7 // (C) 2001 Ximian, Inc. http://www.ximian.com
11 using System.Reflection;
12 using System.Resources;
14 using System.Security.Policy;
15 using System.Runtime.Serialization;
16 using System.Globalization;
17 using System.Runtime.CompilerServices;
18 using System.Collections;
19 using System.Runtime.InteropServices;
20 using System.Security.Cryptography;
21 using System.Security.Permissions;
24 using Mono.Security.Cryptography;
26 namespace System.Reflection.Emit {
28 internal struct RefEmitPermissionSet {
29 public SecurityAction action;
32 public RefEmitPermissionSet (SecurityAction action, string pset) {
38 internal struct MonoResource {
41 public string filename;
42 public ResourceAttributes attrs;
46 internal struct MonoWin32Resource {
52 public MonoWin32Resource (int res_type, int res_id, int lang_id, byte[] data) {
53 this.res_type = res_type;
55 this.lang_id = lang_id;
60 public sealed class AssemblyBuilder : Assembly {
61 #region Sync with reflection.h
62 private IntPtr dynamic_assembly;
63 private MethodInfo entry_point;
64 private ModuleBuilder[] modules;
67 private CustomAttributeBuilder[] cattrs;
68 private MonoResource[] resources;
74 PEFileKinds pekind = PEFileKinds.Dll;
77 Module[] loaded_modules;
78 MonoWin32Resource[] win32_resources;
80 internal Type corlib_object_type = typeof (System.Object);
81 internal Type corlib_value_type = typeof (System.ValueType);
82 internal Type corlib_enum_type = typeof (System.Enum);
83 internal Type corlib_void_type = typeof (void);
84 ArrayList resource_writers = null;
85 Win32VersionResource version_res;
89 private Mono.Security.StrongName sn;
91 [MethodImplAttribute(MethodImplOptions.InternalCall)]
92 private static extern void basic_init (AssemblyBuilder ab);
94 internal AssemblyBuilder (AssemblyName n, string directory, AssemblyBuilderAccess access) {
96 if (directory == null || directory == String.Empty)
97 dir = Directory.GetCurrentDirectory ();
100 this.access = (uint)access;
102 /* Set defaults from n */
103 if (n.CultureInfo != null) {
104 culture = n.CultureInfo.Name;
106 Version v = n.Version;
108 version = v.ToString ();
114 public override string CodeBase {
116 throw not_supported ();
120 public override MethodInfo EntryPoint {
126 public override string Location {
128 throw not_supported ();
133 /* This is to keep signature compatibility with MS.NET */
134 public override string ImageRuntimeVersion {
136 return base.ImageRuntimeVersion;
141 public void AddResourceFile (string name, string fileName)
143 AddResourceFile (name, fileName, ResourceAttributes.Public);
146 public void AddResourceFile (string name, string fileName, ResourceAttributes attribute)
148 AddResourceFile (name, fileName, attribute, true);
151 private void AddResourceFile (string name, string fileName, ResourceAttributes attribute, bool fileNeedsToExists)
153 check_name_and_filename (name, fileName, fileNeedsToExists);
155 // Resource files are created/searched under the assembly storage
158 fileName = Path.Combine (dir, fileName);
160 if (resources != null) {
161 MonoResource[] new_r = new MonoResource [resources.Length + 1];
162 System.Array.Copy(resources, new_r, resources.Length);
165 resources = new MonoResource [1];
167 int p = resources.Length - 1;
168 resources [p].name = name;
169 resources [p].filename = fileName;
170 resources [p].attrs = attribute;
173 public void EmbedResourceFile (string name, string fileName)
175 EmbedResourceFile (name, fileName, ResourceAttributes.Public);
178 public void EmbedResourceFile (string name, string fileName, ResourceAttributes attribute)
180 if (resources != null) {
181 MonoResource[] new_r = new MonoResource [resources.Length + 1];
182 System.Array.Copy(resources, new_r, resources.Length);
185 resources = new MonoResource [1];
187 int p = resources.Length - 1;
188 resources [p].name = name;
189 resources [p].attrs = attribute;
191 FileStream s = new FileStream (fileName, FileMode.Open, FileAccess.Read);
193 resources [p].data = new byte [len];
194 s.Read (resources [p].data, 0, (int)len);
201 internal void EmbedResource (string name, byte[] blob, ResourceAttributes attribute)
203 if (resources != null) {
204 MonoResource[] new_r = new MonoResource [resources.Length + 1];
205 System.Array.Copy(resources, new_r, resources.Length);
208 resources = new MonoResource [1];
210 int p = resources.Length - 1;
211 resources [p].name = name;
212 resources [p].attrs = attribute;
213 resources [p].data = blob;
216 public ModuleBuilder DefineDynamicModule (string name)
218 return DefineDynamicModule (name, name, false, true);
221 public ModuleBuilder DefineDynamicModule (string name, bool emitSymbolInfo)
223 return DefineDynamicModule (name, name, emitSymbolInfo, true);
226 public ModuleBuilder DefineDynamicModule(string name, string fileName)
228 return DefineDynamicModule (name, fileName, false, false);
231 public ModuleBuilder DefineDynamicModule (string name, string fileName,
234 return DefineDynamicModule (name, fileName, emitSymbolInfo, false);
237 private ModuleBuilder DefineDynamicModule (string name, string fileName,
238 bool emitSymbolInfo, bool transient)
240 check_name_and_filename (name, fileName, false);
243 if (Path.GetExtension (fileName) == String.Empty)
244 throw new ArgumentException ("Module file name '" + fileName + "' must have file extension.");
246 throw new NotSupportedException ("Persistable modules are not supported in a dynamic assembly created with AssemblyBuilderAccess.Run");
248 throw new InvalidOperationException ("Assembly was already saved.");
251 ModuleBuilder r = new ModuleBuilder (this, name, fileName, emitSymbolInfo, transient);
253 if ((modules != null) && is_module_only)
254 throw new InvalidOperationException ("A module-only assembly can only contain one module.");
256 if (modules != null) {
257 ModuleBuilder[] new_modules = new ModuleBuilder [modules.Length + 1];
258 System.Array.Copy(modules, new_modules, modules.Length);
259 modules = new_modules;
261 modules = new ModuleBuilder [1];
263 modules [modules.Length - 1] = r;
267 [MethodImplAttribute(MethodImplOptions.InternalCall)]
268 private extern Module InternalAddModule (string fileName);
271 * Mono extension to support /addmodule in mcs.
273 internal Module AddModule (string fileName)
275 if (fileName == null)
276 throw new ArgumentNullException (fileName);
278 Module m = InternalAddModule (fileName);
280 if (loaded_modules != null) {
281 Module[] new_modules = new Module [loaded_modules.Length + 1];
282 System.Array.Copy (loaded_modules, new_modules, loaded_modules.Length);
283 loaded_modules = new_modules;
285 loaded_modules = new Module [1];
287 loaded_modules [loaded_modules.Length - 1] = m;
292 public IResourceWriter DefineResource (string name, string description, string fileName)
294 return DefineResource (name, description, fileName, ResourceAttributes.Public);
297 public IResourceWriter DefineResource (string name, string description,
298 string fileName, ResourceAttributes attribute)
300 IResourceWriter writer;
302 // description seems to be ignored
303 AddResourceFile (name, fileName, attribute, false);
304 writer = new ResourceWriter (fileName);
305 if (resource_writers == null)
306 resource_writers = new ArrayList ();
307 resource_writers.Add (writer);
311 private void AddUnmanagedResource (Win32Resource res) {
312 MemoryStream ms = new MemoryStream ();
315 if (win32_resources != null) {
316 MonoWin32Resource[] new_res = new MonoWin32Resource [win32_resources.Length + 1];
317 System.Array.Copy (win32_resources, new_res, win32_resources.Length);
318 win32_resources = new_res;
321 win32_resources = new MonoWin32Resource [1];
323 win32_resources [win32_resources.Length - 1] = new MonoWin32Resource (res.Type.Id, res.Name.Id, res.Language, ms.ToArray ());
327 public void DefineUnmanagedResource (byte[] resource)
329 if (resource == null)
330 throw new ArgumentNullException ("resource");
333 * The format of the argument byte array is not documented
334 * so this method is impossible to implement.
337 throw new NotImplementedException ();
340 public void DefineUnmanagedResource (string resourceFileName)
342 if (resourceFileName == null)
343 throw new ArgumentNullException ("resourceFileName");
344 if (resourceFileName == String.Empty)
345 throw new ArgumentException ("resourceFileName");
346 if (!File.Exists (resourceFileName) || Directory.Exists (resourceFileName))
347 throw new FileNotFoundException ("File '" + resourceFileName + "' does not exists or is a directory.");
349 using (FileStream fs = new FileStream (resourceFileName, FileMode.Open)) {
350 Win32ResFileReader reader = new Win32ResFileReader (fs);
352 foreach (Win32EncodedResource res in reader.ReadResources ()) {
353 if (res.Name.IsName || res.Type.IsName)
354 throw new InvalidOperationException ("resource files with named resources or non-default resource types are not supported.");
356 AddUnmanagedResource (res);
361 public void DefineVersionInfoResource ()
363 if (version_res != null)
364 throw new ArgumentException ("Native resource has already been defined.");
366 version_res = new Win32VersionResource (1, 0);
368 if (cattrs != null) {
369 foreach (CustomAttributeBuilder cb in cattrs) {
370 string attrname = cb.Ctor.ReflectedType.FullName;
372 if (attrname == "System.Reflection.AssemblyProductAttribute")
373 version_res.ProductName = cb.string_arg ();
374 else if (attrname == "System.Reflection.AssemblyCompanyAttribute")
375 version_res.CompanyName = cb.string_arg ();
376 else if (attrname == "System.Reflection.AssemblyCopyrightAttribute")
377 version_res.LegalCopyright = cb.string_arg ();
378 else if (attrname == "System.Reflection.AssemblyTrademarkAttribute")
379 version_res.LegalTrademarks = cb.string_arg ();
380 else if (attrname == "System.Reflection.AssemblyCultureAttribute")
381 version_res.FileLanguage = new CultureInfo (cb.string_arg ()).LCID;
382 else if (attrname == "System.Reflection.AssemblyFileVersionAttribute")
383 version_res.FileVersion = cb.string_arg ();
384 else if (attrname == "System.Reflection.AssemblyInformationalVersionAttribute")
385 version_res.ProductVersion = cb.string_arg ();
386 else if (attrname == "System.Reflection.AssemblyTitleAttribute")
387 version_res.FileDescription = cb.string_arg ();
388 else if (attrname == "System.Reflection.AssemblyDescriptionAttribute")
389 version_res.Comments = cb.string_arg ();
394 public void DefineVersionInfoResource (string product, string productVersion,
395 string company, string copyright, string trademark)
397 if (version_res != null)
398 throw new ArgumentException ("Native resource has already been defined.");
401 * We can only create the resource later, when the file name and
402 * the binary version is known.
405 version_res = new Win32VersionResource (1, 0);
406 version_res.ProductName = product;
407 version_res.ProductVersion = productVersion;
408 version_res.CompanyName = company;
409 version_res.LegalCopyright = copyright;
410 version_res.LegalTrademarks = trademark;
414 * Mono extension to support /win32icon in mcs
416 internal void DefineIconResource (string iconFileName)
418 if (iconFileName == null)
419 throw new ArgumentNullException ("iconFileName");
420 if (iconFileName == String.Empty)
421 throw new ArgumentException ("iconFileName");
422 if (!File.Exists (iconFileName) || Directory.Exists (iconFileName))
423 throw new FileNotFoundException ("File '" + iconFileName + "' does not exists or is a directory.");
425 using (FileStream fs = new FileStream (iconFileName, FileMode.Open)) {
426 Win32IconFileReader reader = new Win32IconFileReader (fs);
428 ICONDIRENTRY[] entries = reader.ReadIcons ();
430 Win32IconResource[] icons = new Win32IconResource [entries.Length];
431 for (int i = 0; i < entries.Length; ++i) {
432 icons [i] = new Win32IconResource (i + 1, 0, entries [i]);
433 AddUnmanagedResource (icons [i]);
436 Win32GroupIconResource group = new Win32GroupIconResource (1, 0, icons);
437 AddUnmanagedResource (group);
441 private void DefineVersionInfoResourceImpl (string fileName) {
443 if (version_res.FileVersion == "0.0.0.0")
444 version_res.FileVersion = version;
445 version_res.InternalName = Path.GetFileNameWithoutExtension (fileName);
446 version_res.OriginalFilename = fileName;
448 AddUnmanagedResource (version_res);
451 public ModuleBuilder GetDynamicModule (string name)
454 throw new ArgumentNullException ("name");
456 throw new ArgumentException ("Name can't be null");
459 for (int i = 0; i < modules.Length; ++i)
460 if (modules [i].name == name)
465 public override Type[] GetExportedTypes ()
467 throw not_supported ();
470 public override FileStream GetFile (string name)
472 throw not_supported ();
475 public override FileStream[] GetFiles() {
476 throw not_supported ();
479 public override FileStream[] GetFiles(bool getResourceModules) {
480 throw not_supported ();
483 public override ManifestResourceInfo GetManifestResourceInfo(string resourceName) {
484 throw not_supported ();
487 public override string[] GetManifestResourceNames() {
488 throw not_supported ();
491 public override Stream GetManifestResourceStream(string name) {
492 throw not_supported ();
494 public override Stream GetManifestResourceStream(Type type, string name) {
495 throw not_supported ();
498 internal bool IsSave {
500 return access != (uint)AssemblyBuilderAccess.Run;
504 internal string AssemblyDir {
511 * Mono extension. If this is set, the assembly can only contain one
512 * module, access should be Save, and the saved image will not contain an
515 internal bool IsModuleOnly {
517 return is_module_only;
520 is_module_only = value;
524 public void Save (string assemblyFileName)
526 if (resource_writers != null) {
527 foreach (IResourceWriter writer in resource_writers) {
533 // Create a main module if not already created
534 ModuleBuilder mainModule = null;
535 if (modules != null) {
536 foreach (ModuleBuilder module in modules)
537 if (module.FullyQualifiedName == assemblyFileName)
540 if (mainModule == null)
541 mainModule = DefineDynamicModule ("RefEmit_OnDiskManifestModule", assemblyFileName);
544 mainModule.IsMain = true;
547 * Create a new entry point if the one specified
548 * by the user is in another module.
550 if ((entry_point != null) && entry_point.DeclaringType.Module != mainModule) {
552 if (entry_point.GetParameters ().Length == 1)
553 paramTypes = new Type [] { typeof (string) };
555 paramTypes = new Type [0];
557 MethodBuilder mb = mainModule.DefineGlobalMethod ("__EntryPoint$", MethodAttributes.Static|MethodAttributes.PrivateScope, entry_point.ReturnType, paramTypes);
558 ILGenerator ilgen = mb.GetILGenerator ();
559 if (paramTypes.Length == 1)
560 ilgen.Emit (OpCodes.Ldarg_0);
561 ilgen.Emit (OpCodes.Tailcall);
562 ilgen.Emit (OpCodes.Call, entry_point);
563 ilgen.Emit (OpCodes.Ret);
568 if (version_res != null)
569 DefineVersionInfoResourceImpl (assemblyFileName);
571 if ((keyfile_name != null) && (keyfile_name != String.Empty)) {
572 // the StrongName key file may be relative to (a) the compiled
573 // file or (b) to the output assembly. See bugzilla #55320
574 // http://bugzilla.ximian.com/show_bug.cgi?id=55320
576 // (a) relative to the compiled file
577 string filename = Path.GetFullPath (keyfile_name);
578 bool exist = File.Exists (filename);
579 if ((!exist) && (AssemblyDir != null)) {
580 // (b) relative to the outputed assembly
581 filename = Path.GetFullPath (Path.Combine (AssemblyDir, keyfile_name));
582 exist = File.Exists (filename);
586 using (FileStream fs = new FileStream (filename, FileMode.Open)) {
587 byte[] snkeypair = new byte [fs.Length];
588 fs.Read (snkeypair, 0, snkeypair.Length);
590 // this will import public or private/public keys
591 RSA rsa = CryptoConvert.FromCapiKeyBlob (snkeypair);
592 // and export only the public part
593 sn = new Mono.Security.StrongName (rsa);
594 public_key = sn.PublicKey;
599 foreach (ModuleBuilder module in modules)
600 if (module != mainModule)
603 // Write out the main module at the end, because it needs to
604 // contain the hash of the other modules
607 // if not delayed then we directly strongname the assembly
608 if ((sn != null) && (!delay_sign)) {
609 sn.Sign (System.IO.Path.Combine (this.AssemblyDir, assemblyFileName));
615 public void SetEntryPoint (MethodInfo entryMethod)
617 SetEntryPoint (entryMethod, PEFileKinds.ConsoleApplication);
620 public void SetEntryPoint (MethodInfo entryMethod, PEFileKinds fileKind)
622 if (entryMethod == null)
623 throw new ArgumentNullException ("entryMethod");
624 if (entryMethod.DeclaringType.Assembly != this)
625 throw new InvalidOperationException ("Entry method is not defined in the same assembly.");
627 entry_point = entryMethod;
631 public void SetCustomAttribute( CustomAttributeBuilder customBuilder)
633 if (customBuilder == null)
634 throw new ArgumentNullException ("customBuilder");
636 string attrname = customBuilder.Ctor.ReflectedType.FullName;
640 if (attrname == "System.Reflection.AssemblyVersionAttribute") {
641 version = create_assembly_version (customBuilder.string_arg ());
643 } else if (attrname == "System.Reflection.AssemblyKeyFileAttribute") {
644 keyfile_name = customBuilder.string_arg ();
646 } else if (attrname == "System.Reflection.AssemblyKeyNameAttribute") {
647 string key_name = customBuilder.string_arg ();
648 if (key_name == String.Empty)
650 CspParameters csparam = new CspParameters ();
651 csparam.KeyContainerName = key_name;
652 RSA rsacsp = new RSACryptoServiceProvider (csparam);
653 sn = new Mono.Security.StrongName (rsacsp);
654 public_key = sn.PublicKey;
656 } else if (attrname == "System.Reflection.AssemblyCultureAttribute") {
657 culture = customBuilder.string_arg ();
658 } else if (attrname == "System.Reflection.AssemblyAlgorithmIdAttribute") {
659 data = customBuilder.Data;
661 algid = (uint)data [pos];
662 algid |= ((uint)data [pos + 1]) << 8;
663 algid |= ((uint)data [pos + 2]) << 16;
664 algid |= ((uint)data [pos + 3]) << 24;
665 } else if (attrname == "System.Reflection.AssemblyFlagsAttribute") {
666 data = customBuilder.Data;
668 flags = (uint)data [pos];
669 flags |= ((uint)data [pos + 1]) << 8;
670 flags |= ((uint)data [pos + 2]) << 16;
671 flags |= ((uint)data [pos + 3]) << 24;
673 } else if (attrname == "System.Reflection.AssemblyDelaySignAttribute") {
674 data = customBuilder.Data;
676 delay_sign = data [2] != 0;
678 if (cattrs != null) {
679 CustomAttributeBuilder[] new_array = new CustomAttributeBuilder [cattrs.Length + 1];
680 cattrs.CopyTo (new_array, 0);
681 new_array [cattrs.Length] = customBuilder;
684 cattrs = new CustomAttributeBuilder [1];
685 cattrs [0] = customBuilder;
688 public void SetCustomAttribute ( ConstructorInfo con, byte[] binaryAttribute) {
690 throw new ArgumentNullException ("con");
691 if (binaryAttribute == null)
692 throw new ArgumentNullException ("binaryAttribute");
694 SetCustomAttribute (new CustomAttributeBuilder (con, binaryAttribute));
697 public void SetCorlibTypeBuilders (Type corlib_object_type, Type corlib_value_type, Type corlib_enum_type) {
698 this.corlib_object_type = corlib_object_type;
699 this.corlib_value_type = corlib_value_type;
700 this.corlib_enum_type = corlib_enum_type;
703 public void SetCorlibTypeBuilders (Type corlib_object_type, Type corlib_value_type, Type corlib_enum_type, Type corlib_void_type)
705 SetCorlibTypeBuilders (corlib_object_type, corlib_value_type, corlib_enum_type);
706 this.corlib_void_type = corlib_void_type;
709 private Exception not_supported () {
710 // Strange message but this is what MS.NET prints...
711 return new NotSupportedException ("The invoked member is not supported in a dynamic module.");
714 private void check_name_and_filename (string name, string fileName,
715 bool fileNeedsToExists) {
717 throw new ArgumentNullException ("name");
718 if (fileName == null)
719 throw new ArgumentNullException ("fileName");
721 throw new ArgumentException ("name cannot be empty", "name");
723 throw new ArgumentException ("fileName cannot be empty", "fileName");
724 if (Path.GetFileName (fileName) != fileName)
725 throw new ArgumentException ("fileName '" + fileName + "' must not include a path.");
727 // Resource files are created/searched under the assembly storage
729 string fullFileName = fileName;
731 fullFileName = Path.Combine (dir, fileName);
733 if (fileNeedsToExists && !File.Exists (fullFileName))
734 throw new FileNotFoundException ("Could not find file '" + fileName + "'");
736 if (resources != null) {
737 for (int i = 0; i < resources.Length; ++i) {
738 if (resources [i].filename == fullFileName)
739 throw new ArgumentException ("Duplicate file name '" + fileName + "'");
740 if (resources [i].name == name)
741 throw new ArgumentException ("Duplicate name '" + name + "'");
745 if (modules != null) {
746 for (int i = 0; i < modules.Length; ++i) {
747 // Use fileName instead of fullFileName here
748 if (!modules [i].IsTransient () && (modules [i].FileName == fileName))
749 throw new ArgumentException ("Duplicate file name '" + fileName + "'");
750 if (modules [i].Name == name)
751 throw new ArgumentException ("Duplicate name '" + name + "'");
756 private String create_assembly_version (String version) {
757 String[] parts = version.Split ('.');
758 int[] ver = new int [4] { 0, 0, 0, 0 };
760 if ((parts.Length < 0) || (parts.Length > 4))
761 throw new ArgumentException ("The version specified '" + version + "' is invalid");
763 for (int i = 0; i < parts.Length; ++i) {
764 if (parts [i] == "*") {
765 DateTime now = DateTime.Now;
768 ver [2] = (now - new DateTime (2000, 1, 1)).Days;
769 if (parts.Length == 3)
770 ver [3] = (now.Second + (now.Minute * 60) + (now.Hour * 3600)) / 2;
774 ver [3] = (now.Second + (now.Minute * 60) + (now.Hour * 3600)) / 2;
776 throw new ArgumentException ("The version specified '" + version + "' is invalid");
780 ver [i] = Int32.Parse (parts [i]);
782 catch (FormatException) {
783 throw new ArgumentException ("The version specified '" + version + "' is invalid");
788 return ver [0] + "." + ver [1] + "." + ver [2] + "." + ver [3];