2 // System.Reflection.Emit/AssemblyBuilder.cs
5 // Paolo Molaro (lupus@ximian.com)
7 // (C) 2001 Ximian, Inc. http://www.ximian.com
11 // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
13 // Permission is hereby granted, free of charge, to any person obtaining
14 // a copy of this software and associated documentation files (the
15 // "Software"), to deal in the Software without restriction, including
16 // without limitation the rights to use, copy, modify, merge, publish,
17 // distribute, sublicense, and/or sell copies of the Software, and to
18 // permit persons to whom the Software is furnished to do so, subject to
19 // the following conditions:
21 // The above copyright notice and this permission notice shall be
22 // included in all copies or substantial portions of the Software.
24 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
25 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
26 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
27 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
28 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
29 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
30 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
34 using System.Reflection;
35 using System.Resources;
37 using System.Security.Policy;
38 using System.Runtime.Serialization;
39 using System.Globalization;
40 using System.Runtime.CompilerServices;
41 using System.Collections;
42 using System.Runtime.InteropServices;
43 using System.Security;
44 using System.Security.Cryptography;
45 using System.Security.Permissions;
48 using Mono.Security.Cryptography;
50 namespace System.Reflection.Emit {
52 internal struct RefEmitPermissionSet {
53 public SecurityAction action;
56 public RefEmitPermissionSet (SecurityAction action, string pset) {
62 internal struct MonoResource {
65 public string filename;
66 public ResourceAttributes attrs;
70 internal struct MonoWin32Resource {
76 public MonoWin32Resource (int res_type, int res_id, int lang_id, byte[] data) {
77 this.res_type = res_type;
79 this.lang_id = lang_id;
84 public sealed class AssemblyBuilder : Assembly {
85 #region Sync with reflection.h
86 private IntPtr dynamic_assembly;
87 private MethodInfo entry_point;
88 private ModuleBuilder[] modules;
91 private CustomAttributeBuilder[] cattrs;
92 private MonoResource[] resources;
98 PEFileKinds pekind = PEFileKinds.Dll;
101 Module[] loaded_modules;
102 MonoWin32Resource[] win32_resources;
104 internal Type corlib_object_type = typeof (System.Object);
105 internal Type corlib_value_type = typeof (System.ValueType);
106 internal Type corlib_enum_type = typeof (System.Enum);
107 internal Type corlib_void_type = typeof (void);
108 ArrayList resource_writers = null;
109 Win32VersionResource version_res;
112 private Mono.Security.StrongName sn;
114 [MethodImplAttribute(MethodImplOptions.InternalCall)]
115 private static extern void basic_init (AssemblyBuilder ab);
117 internal AssemblyBuilder (AssemblyName n, string directory, AssemblyBuilderAccess access) {
119 if (directory == null || directory == String.Empty)
120 dir = Directory.GetCurrentDirectory ();
123 this.access = (uint)access;
125 /* Set defaults from n */
126 if (n.CultureInfo != null) {
127 culture = n.CultureInfo.Name;
129 Version v = n.Version;
131 version = v.ToString ();
134 if (n.KeyPair != null) {
135 // full keypair is available (for signing)
136 sn = n.KeyPair.StrongName ();
139 // public key is available (for delay-signing)
140 byte[] pk = n.GetPublicKey ();
141 if ((pk != null) && (pk.Length > 0)) {
142 sn = new Mono.Security.StrongName (pk);
149 public override string CodeBase {
151 throw not_supported ();
155 public override MethodInfo EntryPoint {
161 public override string Location {
163 throw not_supported ();
168 /* This is to keep signature compatibility with MS.NET */
169 public override string ImageRuntimeVersion {
171 return base.ImageRuntimeVersion;
176 public void AddResourceFile (string name, string fileName)
178 AddResourceFile (name, fileName, ResourceAttributes.Public);
181 public void AddResourceFile (string name, string fileName, ResourceAttributes attribute)
183 AddResourceFile (name, fileName, attribute, true);
186 private void AddResourceFile (string name, string fileName, ResourceAttributes attribute, bool fileNeedsToExists)
188 check_name_and_filename (name, fileName, fileNeedsToExists);
190 // Resource files are created/searched under the assembly storage
193 fileName = Path.Combine (dir, fileName);
195 if (resources != null) {
196 MonoResource[] new_r = new MonoResource [resources.Length + 1];
197 System.Array.Copy(resources, new_r, resources.Length);
200 resources = new MonoResource [1];
202 int p = resources.Length - 1;
203 resources [p].name = name;
204 resources [p].filename = fileName;
205 resources [p].attrs = attribute;
209 /// Don't change the method name and parameters order. It is used by mcs
211 [MonoTODO ("Missing support in runtime for parameter applying")]
212 internal void AddPermissionRequests (PermissionSet required, PermissionSet optional, PermissionSet refused)
215 throw new InvalidOperationException ("Assembly was already saved.");
218 _optional = optional;
222 internal void EmbedResourceFile (string name, string fileName)
224 EmbedResourceFile (name, fileName, ResourceAttributes.Public);
227 internal void EmbedResourceFile (string name, string fileName, ResourceAttributes attribute)
229 if (resources != null) {
230 MonoResource[] new_r = new MonoResource [resources.Length + 1];
231 System.Array.Copy(resources, new_r, resources.Length);
234 resources = new MonoResource [1];
236 int p = resources.Length - 1;
237 resources [p].name = name;
238 resources [p].attrs = attribute;
240 FileStream s = new FileStream (fileName, FileMode.Open, FileAccess.Read);
242 resources [p].data = new byte [len];
243 s.Read (resources [p].data, 0, (int)len);
250 internal void EmbedResource (string name, byte[] blob, ResourceAttributes attribute)
252 if (resources != null) {
253 MonoResource[] new_r = new MonoResource [resources.Length + 1];
254 System.Array.Copy(resources, new_r, resources.Length);
257 resources = new MonoResource [1];
259 int p = resources.Length - 1;
260 resources [p].name = name;
261 resources [p].attrs = attribute;
262 resources [p].data = blob;
265 public ModuleBuilder DefineDynamicModule (string name)
267 return DefineDynamicModule (name, name, false, true);
270 public ModuleBuilder DefineDynamicModule (string name, bool emitSymbolInfo)
272 return DefineDynamicModule (name, name, emitSymbolInfo, true);
275 public ModuleBuilder DefineDynamicModule(string name, string fileName)
277 return DefineDynamicModule (name, fileName, false, false);
280 public ModuleBuilder DefineDynamicModule (string name, string fileName,
283 return DefineDynamicModule (name, fileName, emitSymbolInfo, false);
286 private ModuleBuilder DefineDynamicModule (string name, string fileName,
287 bool emitSymbolInfo, bool transient)
289 check_name_and_filename (name, fileName, false);
292 if (Path.GetExtension (fileName) == String.Empty)
293 throw new ArgumentException ("Module file name '" + fileName + "' must have file extension.");
295 throw new NotSupportedException ("Persistable modules are not supported in a dynamic assembly created with AssemblyBuilderAccess.Run");
297 throw new InvalidOperationException ("Assembly was already saved.");
300 ModuleBuilder r = new ModuleBuilder (this, name, fileName, emitSymbolInfo, transient);
302 if ((modules != null) && is_module_only)
303 throw new InvalidOperationException ("A module-only assembly can only contain one module.");
305 if (modules != null) {
306 ModuleBuilder[] new_modules = new ModuleBuilder [modules.Length + 1];
307 System.Array.Copy(modules, new_modules, modules.Length);
308 modules = new_modules;
310 modules = new ModuleBuilder [1];
312 modules [modules.Length - 1] = r;
316 [MethodImplAttribute(MethodImplOptions.InternalCall)]
317 private extern Module InternalAddModule (string fileName);
320 * Mono extension to support /addmodule in mcs.
322 internal Module AddModule (string fileName)
324 if (fileName == null)
325 throw new ArgumentNullException (fileName);
327 Module m = InternalAddModule (fileName);
329 if (loaded_modules != null) {
330 Module[] new_modules = new Module [loaded_modules.Length + 1];
331 System.Array.Copy (loaded_modules, new_modules, loaded_modules.Length);
332 loaded_modules = new_modules;
334 loaded_modules = new Module [1];
336 loaded_modules [loaded_modules.Length - 1] = m;
341 public IResourceWriter DefineResource (string name, string description, string fileName)
343 return DefineResource (name, description, fileName, ResourceAttributes.Public);
346 public IResourceWriter DefineResource (string name, string description,
347 string fileName, ResourceAttributes attribute)
349 IResourceWriter writer;
351 // description seems to be ignored
352 AddResourceFile (name, fileName, attribute, false);
353 writer = new ResourceWriter (fileName);
354 if (resource_writers == null)
355 resource_writers = new ArrayList ();
356 resource_writers.Add (writer);
360 private void AddUnmanagedResource (Win32Resource res) {
361 MemoryStream ms = new MemoryStream ();
364 if (win32_resources != null) {
365 MonoWin32Resource[] new_res = new MonoWin32Resource [win32_resources.Length + 1];
366 System.Array.Copy (win32_resources, new_res, win32_resources.Length);
367 win32_resources = new_res;
370 win32_resources = new MonoWin32Resource [1];
372 win32_resources [win32_resources.Length - 1] = new MonoWin32Resource (res.Type.Id, res.Name.Id, res.Language, ms.ToArray ());
376 public void DefineUnmanagedResource (byte[] resource)
378 if (resource == null)
379 throw new ArgumentNullException ("resource");
382 * The format of the argument byte array is not documented
383 * so this method is impossible to implement.
386 throw new NotImplementedException ();
389 public void DefineUnmanagedResource (string resourceFileName)
391 if (resourceFileName == null)
392 throw new ArgumentNullException ("resourceFileName");
393 if (resourceFileName == String.Empty)
394 throw new ArgumentException ("resourceFileName");
395 if (!File.Exists (resourceFileName) || Directory.Exists (resourceFileName))
396 throw new FileNotFoundException ("File '" + resourceFileName + "' does not exists or is a directory.");
398 using (FileStream fs = new FileStream (resourceFileName, FileMode.Open)) {
399 Win32ResFileReader reader = new Win32ResFileReader (fs);
401 foreach (Win32EncodedResource res in reader.ReadResources ()) {
402 if (res.Name.IsName || res.Type.IsName)
403 throw new InvalidOperationException ("resource files with named resources or non-default resource types are not supported.");
405 AddUnmanagedResource (res);
410 public void DefineVersionInfoResource ()
412 if (version_res != null)
413 throw new ArgumentException ("Native resource has already been defined.");
415 version_res = new Win32VersionResource (1, 0);
417 if (cattrs != null) {
418 foreach (CustomAttributeBuilder cb in cattrs) {
419 string attrname = cb.Ctor.ReflectedType.FullName;
421 if (attrname == "System.Reflection.AssemblyProductAttribute")
422 version_res.ProductName = cb.string_arg ();
423 else if (attrname == "System.Reflection.AssemblyCompanyAttribute")
424 version_res.CompanyName = cb.string_arg ();
425 else if (attrname == "System.Reflection.AssemblyCopyrightAttribute")
426 version_res.LegalCopyright = cb.string_arg ();
427 else if (attrname == "System.Reflection.AssemblyTrademarkAttribute")
428 version_res.LegalTrademarks = cb.string_arg ();
429 else if (attrname == "System.Reflection.AssemblyCultureAttribute")
430 version_res.FileLanguage = new CultureInfo (GetCultureString (cb.string_arg ())).LCID;
431 else if (attrname == "System.Reflection.AssemblyFileVersionAttribute")
432 version_res.FileVersion = cb.string_arg ();
433 else if (attrname == "System.Reflection.AssemblyInformationalVersionAttribute")
434 version_res.ProductVersion = cb.string_arg ();
435 else if (attrname == "System.Reflection.AssemblyTitleAttribute")
436 version_res.FileDescription = cb.string_arg ();
437 else if (attrname == "System.Reflection.AssemblyDescriptionAttribute")
438 version_res.Comments = cb.string_arg ();
443 public void DefineVersionInfoResource (string product, string productVersion,
444 string company, string copyright, string trademark)
446 if (version_res != null)
447 throw new ArgumentException ("Native resource has already been defined.");
450 * We can only create the resource later, when the file name and
451 * the binary version is known.
454 version_res = new Win32VersionResource (1, 0);
455 version_res.ProductName = product;
456 version_res.ProductVersion = productVersion;
457 version_res.CompanyName = company;
458 version_res.LegalCopyright = copyright;
459 version_res.LegalTrademarks = trademark;
463 * Mono extension to support /win32icon in mcs
465 internal void DefineIconResource (string iconFileName)
467 if (iconFileName == null)
468 throw new ArgumentNullException ("iconFileName");
469 if (iconFileName == String.Empty)
470 throw new ArgumentException ("iconFileName");
471 if (!File.Exists (iconFileName) || Directory.Exists (iconFileName))
472 throw new FileNotFoundException ("File '" + iconFileName + "' does not exists or is a directory.");
474 using (FileStream fs = new FileStream (iconFileName, FileMode.Open)) {
475 Win32IconFileReader reader = new Win32IconFileReader (fs);
477 ICONDIRENTRY[] entries = reader.ReadIcons ();
479 Win32IconResource[] icons = new Win32IconResource [entries.Length];
480 for (int i = 0; i < entries.Length; ++i) {
481 icons [i] = new Win32IconResource (i + 1, 0, entries [i]);
482 AddUnmanagedResource (icons [i]);
485 Win32GroupIconResource group = new Win32GroupIconResource (1, 0, icons);
486 AddUnmanagedResource (group);
490 private void DefineVersionInfoResourceImpl (string fileName) {
492 if (version_res.FileVersion == "0.0.0.0")
493 version_res.FileVersion = version;
494 version_res.InternalName = Path.GetFileNameWithoutExtension (fileName);
495 version_res.OriginalFilename = fileName;
497 AddUnmanagedResource (version_res);
500 public ModuleBuilder GetDynamicModule (string name)
503 throw new ArgumentNullException ("name");
505 throw new ArgumentException ("Name can't be null");
508 for (int i = 0; i < modules.Length; ++i)
509 if (modules [i].name == name)
514 public override Type[] GetExportedTypes ()
516 throw not_supported ();
519 public override FileStream GetFile (string name)
521 throw not_supported ();
524 public override FileStream[] GetFiles(bool getResourceModules) {
525 throw not_supported ();
528 public override ManifestResourceInfo GetManifestResourceInfo(string resourceName) {
529 throw not_supported ();
532 public override string[] GetManifestResourceNames() {
533 throw not_supported ();
536 public override Stream GetManifestResourceStream(string name) {
537 throw not_supported ();
539 public override Stream GetManifestResourceStream(Type type, string name) {
540 throw not_supported ();
543 internal bool IsSave {
545 return access != (uint)AssemblyBuilderAccess.Run;
549 internal string AssemblyDir {
556 * Mono extension. If this is set, the assembly can only contain one
557 * module, access should be Save, and the saved image will not contain an
560 internal bool IsModuleOnly {
562 return is_module_only;
565 is_module_only = value;
569 public void Save (string assemblyFileName)
571 if (resource_writers != null) {
572 foreach (IResourceWriter writer in resource_writers) {
578 // Create a main module if not already created
579 ModuleBuilder mainModule = null;
580 if (modules != null) {
581 foreach (ModuleBuilder module in modules)
582 if (module.FullyQualifiedName == assemblyFileName)
585 if (mainModule == null)
586 mainModule = DefineDynamicModule ("RefEmit_OnDiskManifestModule", assemblyFileName);
589 mainModule.IsMain = true;
592 * Create a new entry point if the one specified
593 * by the user is in another module.
595 if ((entry_point != null) && entry_point.DeclaringType.Module != mainModule) {
597 if (entry_point.GetParameters ().Length == 1)
598 paramTypes = new Type [] { typeof (string) };
600 paramTypes = new Type [0];
602 MethodBuilder mb = mainModule.DefineGlobalMethod ("__EntryPoint$", MethodAttributes.Static|MethodAttributes.PrivateScope, entry_point.ReturnType, paramTypes);
603 ILGenerator ilgen = mb.GetILGenerator ();
604 if (paramTypes.Length == 1)
605 ilgen.Emit (OpCodes.Ldarg_0);
606 ilgen.Emit (OpCodes.Tailcall);
607 ilgen.Emit (OpCodes.Call, entry_point);
608 ilgen.Emit (OpCodes.Ret);
613 if (version_res != null)
614 DefineVersionInfoResourceImpl (assemblyFileName);
617 // runtime needs to value to embed it into the assembly
618 public_key = sn.PublicKey;
621 foreach (ModuleBuilder module in modules)
622 if (module != mainModule)
625 // Write out the main module at the end, because it needs to
626 // contain the hash of the other modules
629 if ((sn != null) && (sn.CanSign)) {
630 sn.Sign (System.IO.Path.Combine (this.AssemblyDir, assemblyFileName));
636 public void SetEntryPoint (MethodInfo entryMethod)
638 SetEntryPoint (entryMethod, PEFileKinds.ConsoleApplication);
641 public void SetEntryPoint (MethodInfo entryMethod, PEFileKinds fileKind)
643 if (entryMethod == null)
644 throw new ArgumentNullException ("entryMethod");
645 if (entryMethod.DeclaringType.Assembly != this)
646 throw new InvalidOperationException ("Entry method is not defined in the same assembly.");
648 entry_point = entryMethod;
652 public void SetCustomAttribute( CustomAttributeBuilder customBuilder)
654 if (customBuilder == null)
655 throw new ArgumentNullException ("customBuilder");
657 string attrname = customBuilder.Ctor.ReflectedType.FullName;
661 if (attrname == "System.Reflection.AssemblyVersionAttribute") {
662 version = create_assembly_version (customBuilder.string_arg ());
664 } else if (attrname == "System.Reflection.AssemblyCultureAttribute") {
665 culture = GetCultureString (customBuilder.string_arg ());
666 } else if (attrname == "System.Reflection.AssemblyAlgorithmIdAttribute") {
667 data = customBuilder.Data;
669 algid = (uint)data [pos];
670 algid |= ((uint)data [pos + 1]) << 8;
671 algid |= ((uint)data [pos + 2]) << 16;
672 algid |= ((uint)data [pos + 3]) << 24;
673 } else if (attrname == "System.Reflection.AssemblyFlagsAttribute") {
674 data = customBuilder.Data;
676 flags = (uint)data [pos];
677 flags |= ((uint)data [pos + 1]) << 8;
678 flags |= ((uint)data [pos + 2]) << 16;
679 flags |= ((uint)data [pos + 3]) << 24;
683 if (cattrs != null) {
684 CustomAttributeBuilder[] new_array = new CustomAttributeBuilder [cattrs.Length + 1];
685 cattrs.CopyTo (new_array, 0);
686 new_array [cattrs.Length] = customBuilder;
689 cattrs = new CustomAttributeBuilder [1];
690 cattrs [0] = customBuilder;
694 public void SetCustomAttribute ( ConstructorInfo con, byte[] binaryAttribute) {
696 throw new ArgumentNullException ("con");
697 if (binaryAttribute == null)
698 throw new ArgumentNullException ("binaryAttribute");
700 SetCustomAttribute (new CustomAttributeBuilder (con, binaryAttribute));
703 internal void SetCorlibTypeBuilders (Type corlib_object_type, Type corlib_value_type, Type corlib_enum_type) {
704 this.corlib_object_type = corlib_object_type;
705 this.corlib_value_type = corlib_value_type;
706 this.corlib_enum_type = corlib_enum_type;
709 internal void SetCorlibTypeBuilders (Type corlib_object_type, Type corlib_value_type, Type corlib_enum_type, Type corlib_void_type)
711 SetCorlibTypeBuilders (corlib_object_type, corlib_value_type, corlib_enum_type);
712 this.corlib_void_type = corlib_void_type;
715 private Exception not_supported () {
716 // Strange message but this is what MS.NET prints...
717 return new NotSupportedException ("The invoked member is not supported in a dynamic module.");
720 private void check_name_and_filename (string name, string fileName,
721 bool fileNeedsToExists) {
723 throw new ArgumentNullException ("name");
724 if (fileName == null)
725 throw new ArgumentNullException ("fileName");
727 throw new ArgumentException ("name cannot be empty", "name");
729 throw new ArgumentException ("fileName cannot be empty", "fileName");
730 if (Path.GetFileName (fileName) != fileName)
731 throw new ArgumentException ("fileName '" + fileName + "' must not include a path.");
733 // Resource files are created/searched under the assembly storage
735 string fullFileName = fileName;
737 fullFileName = Path.Combine (dir, fileName);
739 if (fileNeedsToExists && !File.Exists (fullFileName))
740 throw new FileNotFoundException ("Could not find file '" + fileName + "'");
742 if (resources != null) {
743 for (int i = 0; i < resources.Length; ++i) {
744 if (resources [i].filename == fullFileName)
745 throw new ArgumentException ("Duplicate file name '" + fileName + "'");
746 if (resources [i].name == name)
747 throw new ArgumentException ("Duplicate name '" + name + "'");
751 if (modules != null) {
752 for (int i = 0; i < modules.Length; ++i) {
753 // Use fileName instead of fullFileName here
754 if (!modules [i].IsTransient () && (modules [i].FileName == fileName))
755 throw new ArgumentException ("Duplicate file name '" + fileName + "'");
756 if (modules [i].Name == name)
757 throw new ArgumentException ("Duplicate name '" + name + "'");
762 private String create_assembly_version (String version) {
763 String[] parts = version.Split ('.');
764 int[] ver = new int [4] { 0, 0, 0, 0 };
766 if ((parts.Length < 0) || (parts.Length > 4))
767 throw new ArgumentException ("The version specified '" + version + "' is invalid");
769 for (int i = 0; i < parts.Length; ++i) {
770 if (parts [i] == "*") {
771 DateTime now = DateTime.Now;
774 ver [2] = (now - new DateTime (2000, 1, 1)).Days;
775 if (parts.Length == 3)
776 ver [3] = (now.Second + (now.Minute * 60) + (now.Hour * 3600)) / 2;
780 ver [3] = (now.Second + (now.Minute * 60) + (now.Hour * 3600)) / 2;
782 throw new ArgumentException ("The version specified '" + version + "' is invalid");
786 ver [i] = Int32.Parse (parts [i]);
788 catch (FormatException) {
789 throw new ArgumentException ("The version specified '" + version + "' is invalid");
794 return ver [0] + "." + ver [1] + "." + ver [2] + "." + ver [3];
797 private string GetCultureString (string str)
799 return (str == "neutral" ? String.Empty : str);