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;
88 private Mono.Security.StrongName sn;
90 [MethodImplAttribute(MethodImplOptions.InternalCall)]
91 private static extern void basic_init (AssemblyBuilder ab);
93 internal AssemblyBuilder (AssemblyName n, string directory, AssemblyBuilderAccess access) {
95 if (directory == null || directory == String.Empty)
96 dir = Directory.GetCurrentDirectory ();
99 this.access = (uint)access;
101 /* Set defaults from n */
102 if (n.CultureInfo != null) {
103 culture = n.CultureInfo.Name;
105 Version v = n.Version;
107 version = v.ToString ();
113 public override string CodeBase {
115 throw not_supported ();
119 public override MethodInfo EntryPoint {
125 public override string Location {
127 throw not_supported ();
132 /* This is to keep signature compatibility with MS.NET */
133 public override string ImageRuntimeVersion {
135 return base.ImageRuntimeVersion;
140 public void AddResourceFile (string name, string fileName)
142 AddResourceFile (name, fileName, ResourceAttributes.Public);
145 public void AddResourceFile (string name, string fileName, ResourceAttributes attribute)
147 AddResourceFile (name, fileName, attribute, true);
150 private void AddResourceFile (string name, string fileName, ResourceAttributes attribute, bool fileNeedsToExists)
152 check_name_and_filename (name, fileName, fileNeedsToExists);
154 // Resource files are created/searched under the assembly storage
157 fileName = Path.Combine (dir, fileName);
159 if (resources != null) {
160 MonoResource[] new_r = new MonoResource [resources.Length + 1];
161 System.Array.Copy(resources, new_r, resources.Length);
164 resources = new MonoResource [1];
166 int p = resources.Length - 1;
167 resources [p].name = name;
168 resources [p].filename = fileName;
169 resources [p].attrs = attribute;
172 public void EmbedResourceFile (string name, string fileName)
174 EmbedResourceFile (name, fileName, ResourceAttributes.Public);
177 public void EmbedResourceFile (string name, string fileName, ResourceAttributes attribute)
179 if (resources != null) {
180 MonoResource[] new_r = new MonoResource [resources.Length + 1];
181 System.Array.Copy(resources, new_r, resources.Length);
184 resources = new MonoResource [1];
186 int p = resources.Length - 1;
187 resources [p].name = name;
188 resources [p].attrs = attribute;
190 FileStream s = new FileStream (fileName, FileMode.Open, FileAccess.Read);
192 resources [p].data = new byte [len];
193 s.Read (resources [p].data, 0, (int)len);
200 internal void EmbedResource (string name, byte[] blob, ResourceAttributes attribute)
202 if (resources != null) {
203 MonoResource[] new_r = new MonoResource [resources.Length + 1];
204 System.Array.Copy(resources, new_r, resources.Length);
207 resources = new MonoResource [1];
209 int p = resources.Length - 1;
210 resources [p].name = name;
211 resources [p].attrs = attribute;
212 resources [p].data = blob;
215 public ModuleBuilder DefineDynamicModule (string name)
217 return DefineDynamicModule (name, name, false, true);
220 public ModuleBuilder DefineDynamicModule (string name, bool emitSymbolInfo)
222 return DefineDynamicModule (name, name, emitSymbolInfo, true);
225 public ModuleBuilder DefineDynamicModule(string name, string fileName)
227 return DefineDynamicModule (name, fileName, false, false);
230 public ModuleBuilder DefineDynamicModule (string name, string fileName,
233 return DefineDynamicModule (name, fileName, emitSymbolInfo, false);
236 private ModuleBuilder DefineDynamicModule (string name, string fileName,
237 bool emitSymbolInfo, bool transient)
239 check_name_and_filename (name, fileName, false);
242 if (Path.GetExtension (fileName) == String.Empty)
243 throw new ArgumentException ("Module file name '" + fileName + "' must have file extension.");
245 throw new NotSupportedException ("Persistable modules are not supported in a dynamic assembly created with AssemblyBuilderAccess.Run");
247 throw new InvalidOperationException ("Assembly was already saved.");
250 ModuleBuilder r = new ModuleBuilder (this, name, fileName, emitSymbolInfo, transient);
252 if ((modules != null) && is_module_only)
253 throw new InvalidOperationException ("A module-only assembly can only contain one module.");
255 if (modules != null) {
256 ModuleBuilder[] new_modules = new ModuleBuilder [modules.Length + 1];
257 System.Array.Copy(modules, new_modules, modules.Length);
258 modules = new_modules;
260 modules = new ModuleBuilder [1];
262 modules [modules.Length - 1] = r;
266 [MethodImplAttribute(MethodImplOptions.InternalCall)]
267 private extern Module InternalAddModule (string fileName);
270 * Mono extension to support /addmodule in mcs.
272 internal Module AddModule (string fileName)
274 if (fileName == null)
275 throw new ArgumentNullException (fileName);
277 Module m = InternalAddModule (fileName);
279 if (loaded_modules != null) {
280 Module[] new_modules = new Module [loaded_modules.Length + 1];
281 System.Array.Copy (loaded_modules, new_modules, loaded_modules.Length);
282 loaded_modules = new_modules;
284 loaded_modules = new Module [1];
286 loaded_modules [loaded_modules.Length - 1] = m;
291 public IResourceWriter DefineResource (string name, string description, string fileName)
293 return DefineResource (name, description, fileName, ResourceAttributes.Public);
296 public IResourceWriter DefineResource (string name, string description,
297 string fileName, ResourceAttributes attribute)
299 IResourceWriter writer;
301 // description seems to be ignored
302 AddResourceFile (name, fileName, attribute, false);
303 writer = new ResourceWriter (fileName);
304 if (resource_writers == null)
305 resource_writers = new ArrayList ();
306 resource_writers.Add (writer);
310 private void AddUnmanagedResource (Win32Resource res) {
311 MemoryStream ms = new MemoryStream ();
314 if (win32_resources != null) {
315 MonoWin32Resource[] new_res = new MonoWin32Resource [win32_resources.Length + 1];
316 System.Array.Copy (win32_resources, new_res, win32_resources.Length);
317 win32_resources = new_res;
320 win32_resources = new MonoWin32Resource [1];
322 win32_resources [win32_resources.Length - 1] = new MonoWin32Resource (res.Type.Id, res.Name.Id, res.Language, ms.ToArray ());
326 public void DefineUnmanagedResource (byte[] resource)
328 if (resource == null)
329 throw new ArgumentNullException ("resource");
332 * The format of the argument byte array is not documented
333 * so this method is impossible to implement.
336 throw new NotImplementedException ();
339 public void DefineUnmanagedResource (string resourceFileName)
341 if (resourceFileName == null)
342 throw new ArgumentNullException ("resourceFileName");
343 if (resourceFileName == String.Empty)
344 throw new ArgumentException ("resourceFileName");
345 if (!File.Exists (resourceFileName) || Directory.Exists (resourceFileName))
346 throw new FileNotFoundException ("File '" + resourceFileName + "' does not exists or is a directory.");
348 using (FileStream fs = new FileStream (resourceFileName, FileMode.Open)) {
349 Win32ResFileReader reader = new Win32ResFileReader (fs);
351 foreach (Win32EncodedResource res in reader.ReadResources ()) {
352 if (res.Name.IsName || res.Type.IsName)
353 throw new InvalidOperationException ("resource files with named resources or non-default resource types are not supported.");
355 AddUnmanagedResource (res);
360 public void DefineVersionInfoResource ()
362 if (version_res != null)
363 throw new ArgumentException ("Native resource has already been defined.");
365 version_res = new Win32VersionResource (1, 0);
367 if (cattrs != null) {
368 foreach (CustomAttributeBuilder cb in cattrs) {
369 string attrname = cb.Ctor.ReflectedType.FullName;
371 if (attrname == "System.Reflection.AssemblyProductAttribute")
372 version_res.ProductName = cb.string_arg ();
373 else if (attrname == "System.Reflection.AssemblyCompanyAttribute")
374 version_res.CompanyName = cb.string_arg ();
375 else if (attrname == "System.Reflection.AssemblyCopyrightAttribute")
376 version_res.LegalCopyright = cb.string_arg ();
377 else if (attrname == "System.Reflection.AssemblyTrademarkAttribute")
378 version_res.LegalTrademarks = cb.string_arg ();
379 else if (attrname == "System.Reflection.AssemblyCultureAttribute")
380 version_res.FileLanguage = new CultureInfo (cb.string_arg ()).LCID;
381 else if (attrname == "System.Reflection.AssemblyFileVersionAttribute")
382 version_res.FileVersion = cb.string_arg ();
383 else if (attrname == "System.Reflection.AssemblyInformationalVersionAttribute")
384 version_res.ProductVersion = cb.string_arg ();
385 else if (attrname == "System.Reflection.AssemblyTitleAttribute")
386 version_res.FileDescription = cb.string_arg ();
387 else if (attrname == "System.Reflection.AssemblyDescriptionAttribute")
388 version_res.Comments = cb.string_arg ();
393 public void DefineVersionInfoResource (string product, string productVersion,
394 string company, string copyright, string trademark)
396 if (version_res != null)
397 throw new ArgumentException ("Native resource has already been defined.");
400 * We can only create the resource later, when the file name and
401 * the binary version is known.
404 version_res = new Win32VersionResource (1, 0);
405 version_res.ProductName = product;
406 version_res.ProductVersion = productVersion;
407 version_res.CompanyName = company;
408 version_res.LegalCopyright = copyright;
409 version_res.LegalTrademarks = trademark;
413 * Mono extension to support /win32icon in mcs
415 internal void DefineIconResource (string iconFileName)
417 if (iconFileName == null)
418 throw new ArgumentNullException ("iconFileName");
419 if (iconFileName == String.Empty)
420 throw new ArgumentException ("iconFileName");
421 if (!File.Exists (iconFileName) || Directory.Exists (iconFileName))
422 throw new FileNotFoundException ("File '" + iconFileName + "' does not exists or is a directory.");
424 using (FileStream fs = new FileStream (iconFileName, FileMode.Open)) {
425 Win32IconFileReader reader = new Win32IconFileReader (fs);
427 ICONDIRENTRY[] entries = reader.ReadIcons ();
429 Win32IconResource[] icons = new Win32IconResource [entries.Length];
430 for (int i = 0; i < entries.Length; ++i) {
431 icons [i] = new Win32IconResource (i + 1, 0, entries [i]);
432 AddUnmanagedResource (icons [i]);
435 Win32GroupIconResource group = new Win32GroupIconResource (1, 0, icons);
436 AddUnmanagedResource (group);
440 private void DefineVersionInfoResourceImpl (string fileName) {
442 if (version_res.FileVersion == "0.0.0.0")
443 version_res.FileVersion = version;
444 version_res.InternalName = Path.GetFileNameWithoutExtension (fileName);
445 version_res.OriginalFilename = fileName;
447 AddUnmanagedResource (version_res);
450 public ModuleBuilder GetDynamicModule (string name)
453 throw new ArgumentNullException ("name");
455 throw new ArgumentException ("Name can't be null");
458 for (int i = 0; i < modules.Length; ++i)
459 if (modules [i].name == name)
464 public override Type[] GetExportedTypes ()
466 throw not_supported ();
469 public override FileStream GetFile (string name)
471 throw not_supported ();
474 public override FileStream[] GetFiles() {
475 throw not_supported ();
478 public override FileStream[] GetFiles(bool getResourceModules) {
479 throw not_supported ();
482 public override ManifestResourceInfo GetManifestResourceInfo(string resourceName) {
483 throw not_supported ();
486 public override string[] GetManifestResourceNames() {
487 throw not_supported ();
490 public override Stream GetManifestResourceStream(string name) {
491 throw not_supported ();
493 public override Stream GetManifestResourceStream(Type type, string name) {
494 throw not_supported ();
497 internal bool IsSave {
499 return access != (uint)AssemblyBuilderAccess.Run;
503 internal string AssemblyDir {
510 * Mono extension. If this is set, the assembly can only contain one
511 * module, access should be Save, and the saved image will not contain an
514 internal bool IsModuleOnly {
516 return is_module_only;
519 is_module_only = value;
523 public void Save (string assemblyFileName)
525 if (resource_writers != null) {
526 foreach (IResourceWriter writer in resource_writers) {
532 // Create a main module if not already created
533 ModuleBuilder mainModule = null;
534 if (modules != null) {
535 foreach (ModuleBuilder module in modules)
536 if (module.FullyQualifiedName == assemblyFileName)
539 if (mainModule == null)
540 mainModule = DefineDynamicModule ("RefEmit_OnDiskManifestModule", assemblyFileName);
543 mainModule.IsMain = true;
546 * Create a new entry point if the one specified
547 * by the user is in another module.
549 if ((entry_point != null) && entry_point.DeclaringType.Module != mainModule) {
551 if (entry_point.GetParameters ().Length == 1)
552 paramTypes = new Type [] { typeof (string) };
554 paramTypes = new Type [0];
556 MethodBuilder mb = mainModule.DefineGlobalMethod ("__EntryPoint$", MethodAttributes.Static|MethodAttributes.PrivateScope, entry_point.ReturnType, paramTypes);
557 ILGenerator ilgen = mb.GetILGenerator ();
558 if (paramTypes.Length == 1)
559 ilgen.Emit (OpCodes.Ldarg_0);
560 ilgen.Emit (OpCodes.Tailcall);
561 ilgen.Emit (OpCodes.Call, entry_point);
562 ilgen.Emit (OpCodes.Ret);
567 if (version_res != null)
568 DefineVersionInfoResourceImpl (assemblyFileName);
570 foreach (ModuleBuilder module in modules)
571 if (module != mainModule)
574 // Write out the main module at the end, because it needs to
575 // contain the hash of the other modules
578 // if not delayed then we directly strongname the assembly
579 if ((sn != null) && (!delay_sign)) {
580 sn.Sign (System.IO.Path.Combine (this.AssemblyDir, assemblyFileName));
586 public void SetEntryPoint (MethodInfo entryMethod)
588 SetEntryPoint (entryMethod, PEFileKinds.ConsoleApplication);
591 public void SetEntryPoint (MethodInfo entryMethod, PEFileKinds fileKind)
593 if (entryMethod == null)
594 throw new ArgumentNullException ("entryMethod");
595 if (entryMethod.DeclaringType.Assembly != this)
596 throw new InvalidOperationException ("Entry method is not defined in the same assembly.");
598 entry_point = entryMethod;
602 public void SetCustomAttribute( CustomAttributeBuilder customBuilder)
604 if (customBuilder == null)
605 throw new ArgumentNullException ("customBuilder");
607 string attrname = customBuilder.Ctor.ReflectedType.FullName;
611 if (attrname == "System.Reflection.AssemblyVersionAttribute") {
612 version = create_assembly_version (customBuilder.string_arg ());
614 } else if (attrname == "System.Reflection.AssemblyKeyFileAttribute") {
615 string keyfile_name = customBuilder.string_arg ();
616 if (keyfile_name == String.Empty)
618 using (FileStream fs = new FileStream (keyfile_name, FileMode.Open)) {
619 byte[] snkeypair = new byte [fs.Length];
620 fs.Read (snkeypair, 0, snkeypair.Length);
622 // this will import public or private/public keys
623 RSA rsa = CryptoConvert.FromCapiKeyBlob (snkeypair);
624 // and export only the public part
625 sn = new Mono.Security.StrongName (rsa);
626 public_key = sn.PublicKey;
629 } else if (attrname == "System.Reflection.AssemblyKeyNameAttribute") {
630 string key_name = customBuilder.string_arg ();
631 if (key_name == String.Empty)
633 CspParameters csparam = new CspParameters ();
634 csparam.KeyContainerName = key_name;
635 RSA rsacsp = new RSACryptoServiceProvider (csparam);
636 sn = new Mono.Security.StrongName (rsacsp);
637 public_key = sn.PublicKey;
639 } else if (attrname == "System.Reflection.AssemblyCultureAttribute") {
640 culture = customBuilder.string_arg ();
641 } else if (attrname == "System.Reflection.AssemblyAlgorithmIdAttribute") {
642 data = customBuilder.Data;
644 algid = (uint)data [pos];
645 algid |= ((uint)data [pos + 1]) << 8;
646 algid |= ((uint)data [pos + 2]) << 16;
647 algid |= ((uint)data [pos + 3]) << 24;
648 } else if (attrname == "System.Reflection.AssemblyFlagsAttribute") {
649 data = customBuilder.Data;
651 flags = (uint)data [pos];
652 flags |= ((uint)data [pos + 1]) << 8;
653 flags |= ((uint)data [pos + 2]) << 16;
654 flags |= ((uint)data [pos + 3]) << 24;
656 } else if (attrname == "System.Reflection.AssemblyDelaySignAttribute") {
657 data = customBuilder.Data;
659 delay_sign = data [2] != 0;
661 if (cattrs != null) {
662 CustomAttributeBuilder[] new_array = new CustomAttributeBuilder [cattrs.Length + 1];
663 cattrs.CopyTo (new_array, 0);
664 new_array [cattrs.Length] = customBuilder;
667 cattrs = new CustomAttributeBuilder [1];
668 cattrs [0] = customBuilder;
671 public void SetCustomAttribute ( ConstructorInfo con, byte[] binaryAttribute) {
673 throw new ArgumentNullException ("con");
674 if (binaryAttribute == null)
675 throw new ArgumentNullException ("binaryAttribute");
677 SetCustomAttribute (new CustomAttributeBuilder (con, binaryAttribute));
680 public void SetCorlibTypeBuilders (Type corlib_object_type, Type corlib_value_type, Type corlib_enum_type) {
681 this.corlib_object_type = corlib_object_type;
682 this.corlib_value_type = corlib_value_type;
683 this.corlib_enum_type = corlib_enum_type;
686 public void SetCorlibTypeBuilders (Type corlib_object_type, Type corlib_value_type, Type corlib_enum_type, Type corlib_void_type)
688 SetCorlibTypeBuilders (corlib_object_type, corlib_value_type, corlib_enum_type);
689 this.corlib_void_type = corlib_void_type;
692 private Exception not_supported () {
693 // Strange message but this is what MS.NET prints...
694 return new NotSupportedException ("The invoked member is not supported in a dynamic module.");
697 private void check_name_and_filename (string name, string fileName,
698 bool fileNeedsToExists) {
700 throw new ArgumentNullException ("name");
701 if (fileName == null)
702 throw new ArgumentNullException ("fileName");
704 throw new ArgumentException ("name cannot be empty", "name");
706 throw new ArgumentException ("fileName cannot be empty", "fileName");
707 if (Path.GetFileName (fileName) != fileName)
708 throw new ArgumentException ("fileName '" + fileName + "' must not include a path.");
710 // Resource files are created/searched under the assembly storage
712 string fullFileName = fileName;
714 fullFileName = Path.Combine (dir, fileName);
716 if (fileNeedsToExists && !File.Exists (fullFileName))
717 throw new FileNotFoundException ("Could not find file '" + fileName + "'");
719 if (resources != null) {
720 for (int i = 0; i < resources.Length; ++i) {
721 if (resources [i].filename == fullFileName)
722 throw new ArgumentException ("Duplicate file name '" + fileName + "'");
723 if (resources [i].name == name)
724 throw new ArgumentException ("Duplicate name '" + name + "'");
728 if (modules != null) {
729 for (int i = 0; i < modules.Length; ++i) {
730 // Use fileName instead of fullFileName here
731 if (!modules [i].IsTransient () && (modules [i].FileName == fileName))
732 throw new ArgumentException ("Duplicate file name '" + fileName + "'");
733 if (modules [i].Name == name)
734 throw new ArgumentException ("Duplicate name '" + name + "'");
739 private String create_assembly_version (String version) {
740 String[] parts = version.Split ('.');
741 int[] ver = new int [4] { 0, 0, 0, 0 };
743 if ((parts.Length < 0) || (parts.Length > 4))
744 throw new ArgumentException ("The version specified '" + version + "' is invalid");
746 for (int i = 0; i < parts.Length; ++i) {
747 if (parts [i] == "*") {
748 DateTime now = DateTime.Now;
751 ver [2] = (now - new DateTime (2000, 1, 1)).Days;
752 if (parts.Length == 3)
753 ver [3] = (now.Second + (now.Minute * 60) + (now.Hour * 3600)) / 2;
757 ver [3] = (now.Second + (now.Minute * 60) + (now.Hour * 3600)) / 2;
759 throw new ArgumentException ("The version specified '" + version + "' is invalid");
763 ver [i] = Int32.Parse (parts [i]);
765 catch (FormatException) {
766 throw new ArgumentException ("The version specified '" + version + "' is invalid");
771 return ver [0] + "." + ver [1] + "." + ver [2] + "." + ver [3];