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.Cryptography;
44 using System.Security.Permissions;
47 using Mono.Security.Cryptography;
49 namespace System.Reflection.Emit {
51 internal struct RefEmitPermissionSet {
52 public SecurityAction action;
55 public RefEmitPermissionSet (SecurityAction action, string pset) {
61 internal struct MonoResource {
64 public string filename;
65 public ResourceAttributes attrs;
69 internal struct MonoWin32Resource {
75 public MonoWin32Resource (int res_type, int res_id, int lang_id, byte[] data) {
76 this.res_type = res_type;
78 this.lang_id = lang_id;
83 public sealed class AssemblyBuilder : Assembly {
84 #region Sync with reflection.h
85 private IntPtr dynamic_assembly;
86 private MethodInfo entry_point;
87 private ModuleBuilder[] modules;
90 private CustomAttributeBuilder[] cattrs;
91 private MonoResource[] resources;
97 PEFileKinds pekind = PEFileKinds.Dll;
100 Module[] loaded_modules;
101 MonoWin32Resource[] win32_resources;
103 internal Type corlib_object_type = typeof (System.Object);
104 internal Type corlib_value_type = typeof (System.ValueType);
105 internal Type corlib_enum_type = typeof (System.Enum);
106 internal Type corlib_void_type = typeof (void);
107 ArrayList resource_writers = null;
108 Win32VersionResource version_res;
111 private Mono.Security.StrongName sn;
113 [MethodImplAttribute(MethodImplOptions.InternalCall)]
114 private static extern void basic_init (AssemblyBuilder ab);
116 internal AssemblyBuilder (AssemblyName n, string directory, AssemblyBuilderAccess access) {
118 if (directory == null || directory == String.Empty)
119 dir = Directory.GetCurrentDirectory ();
122 this.access = (uint)access;
124 /* Set defaults from n */
125 if (n.CultureInfo != null) {
126 culture = n.CultureInfo.Name;
128 Version v = n.Version;
130 version = v.ToString ();
133 if (n.KeyPair != null) {
134 // full keypair is available (for signing)
135 sn = n.KeyPair.StrongName ();
138 // public key is available (for delay-signing)
139 byte[] pk = n.GetPublicKey ();
140 if ((pk != null) && (pk.Length > 0)) {
141 sn = new Mono.Security.StrongName (pk);
148 public override string CodeBase {
150 throw not_supported ();
154 public override MethodInfo EntryPoint {
160 public override string Location {
162 throw not_supported ();
167 /* This is to keep signature compatibility with MS.NET */
168 public override string ImageRuntimeVersion {
170 return base.ImageRuntimeVersion;
175 public void AddResourceFile (string name, string fileName)
177 AddResourceFile (name, fileName, ResourceAttributes.Public);
180 public void AddResourceFile (string name, string fileName, ResourceAttributes attribute)
182 AddResourceFile (name, fileName, attribute, true);
185 private void AddResourceFile (string name, string fileName, ResourceAttributes attribute, bool fileNeedsToExists)
187 check_name_and_filename (name, fileName, fileNeedsToExists);
189 // Resource files are created/searched under the assembly storage
192 fileName = Path.Combine (dir, fileName);
194 if (resources != null) {
195 MonoResource[] new_r = new MonoResource [resources.Length + 1];
196 System.Array.Copy(resources, new_r, resources.Length);
199 resources = new MonoResource [1];
201 int p = resources.Length - 1;
202 resources [p].name = name;
203 resources [p].filename = fileName;
204 resources [p].attrs = attribute;
207 internal void EmbedResourceFile (string name, string fileName)
209 EmbedResourceFile (name, fileName, ResourceAttributes.Public);
212 internal void EmbedResourceFile (string name, string fileName, ResourceAttributes attribute)
214 if (resources != null) {
215 MonoResource[] new_r = new MonoResource [resources.Length + 1];
216 System.Array.Copy(resources, new_r, resources.Length);
219 resources = new MonoResource [1];
221 int p = resources.Length - 1;
222 resources [p].name = name;
223 resources [p].attrs = attribute;
225 FileStream s = new FileStream (fileName, FileMode.Open, FileAccess.Read);
227 resources [p].data = new byte [len];
228 s.Read (resources [p].data, 0, (int)len);
235 internal void EmbedResource (string name, byte[] blob, ResourceAttributes attribute)
237 if (resources != null) {
238 MonoResource[] new_r = new MonoResource [resources.Length + 1];
239 System.Array.Copy(resources, new_r, resources.Length);
242 resources = new MonoResource [1];
244 int p = resources.Length - 1;
245 resources [p].name = name;
246 resources [p].attrs = attribute;
247 resources [p].data = blob;
250 public ModuleBuilder DefineDynamicModule (string name)
252 return DefineDynamicModule (name, name, false, true);
255 public ModuleBuilder DefineDynamicModule (string name, bool emitSymbolInfo)
257 return DefineDynamicModule (name, name, emitSymbolInfo, true);
260 public ModuleBuilder DefineDynamicModule(string name, string fileName)
262 return DefineDynamicModule (name, fileName, false, false);
265 public ModuleBuilder DefineDynamicModule (string name, string fileName,
268 return DefineDynamicModule (name, fileName, emitSymbolInfo, false);
271 private ModuleBuilder DefineDynamicModule (string name, string fileName,
272 bool emitSymbolInfo, bool transient)
274 check_name_and_filename (name, fileName, false);
277 if (Path.GetExtension (fileName) == String.Empty)
278 throw new ArgumentException ("Module file name '" + fileName + "' must have file extension.");
280 throw new NotSupportedException ("Persistable modules are not supported in a dynamic assembly created with AssemblyBuilderAccess.Run");
282 throw new InvalidOperationException ("Assembly was already saved.");
285 ModuleBuilder r = new ModuleBuilder (this, name, fileName, emitSymbolInfo, transient);
287 if ((modules != null) && is_module_only)
288 throw new InvalidOperationException ("A module-only assembly can only contain one module.");
290 if (modules != null) {
291 ModuleBuilder[] new_modules = new ModuleBuilder [modules.Length + 1];
292 System.Array.Copy(modules, new_modules, modules.Length);
293 modules = new_modules;
295 modules = new ModuleBuilder [1];
297 modules [modules.Length - 1] = r;
301 [MethodImplAttribute(MethodImplOptions.InternalCall)]
302 private extern Module InternalAddModule (string fileName);
305 * Mono extension to support /addmodule in mcs.
307 internal Module AddModule (string fileName)
309 if (fileName == null)
310 throw new ArgumentNullException (fileName);
312 Module m = InternalAddModule (fileName);
314 if (loaded_modules != null) {
315 Module[] new_modules = new Module [loaded_modules.Length + 1];
316 System.Array.Copy (loaded_modules, new_modules, loaded_modules.Length);
317 loaded_modules = new_modules;
319 loaded_modules = new Module [1];
321 loaded_modules [loaded_modules.Length - 1] = m;
326 public IResourceWriter DefineResource (string name, string description, string fileName)
328 return DefineResource (name, description, fileName, ResourceAttributes.Public);
331 public IResourceWriter DefineResource (string name, string description,
332 string fileName, ResourceAttributes attribute)
334 IResourceWriter writer;
336 // description seems to be ignored
337 AddResourceFile (name, fileName, attribute, false);
338 writer = new ResourceWriter (fileName);
339 if (resource_writers == null)
340 resource_writers = new ArrayList ();
341 resource_writers.Add (writer);
345 private void AddUnmanagedResource (Win32Resource res) {
346 MemoryStream ms = new MemoryStream ();
349 if (win32_resources != null) {
350 MonoWin32Resource[] new_res = new MonoWin32Resource [win32_resources.Length + 1];
351 System.Array.Copy (win32_resources, new_res, win32_resources.Length);
352 win32_resources = new_res;
355 win32_resources = new MonoWin32Resource [1];
357 win32_resources [win32_resources.Length - 1] = new MonoWin32Resource (res.Type.Id, res.Name.Id, res.Language, ms.ToArray ());
361 public void DefineUnmanagedResource (byte[] resource)
363 if (resource == null)
364 throw new ArgumentNullException ("resource");
367 * The format of the argument byte array is not documented
368 * so this method is impossible to implement.
371 throw new NotImplementedException ();
374 public void DefineUnmanagedResource (string resourceFileName)
376 if (resourceFileName == null)
377 throw new ArgumentNullException ("resourceFileName");
378 if (resourceFileName == String.Empty)
379 throw new ArgumentException ("resourceFileName");
380 if (!File.Exists (resourceFileName) || Directory.Exists (resourceFileName))
381 throw new FileNotFoundException ("File '" + resourceFileName + "' does not exists or is a directory.");
383 using (FileStream fs = new FileStream (resourceFileName, FileMode.Open)) {
384 Win32ResFileReader reader = new Win32ResFileReader (fs);
386 foreach (Win32EncodedResource res in reader.ReadResources ()) {
387 if (res.Name.IsName || res.Type.IsName)
388 throw new InvalidOperationException ("resource files with named resources or non-default resource types are not supported.");
390 AddUnmanagedResource (res);
395 public void DefineVersionInfoResource ()
397 if (version_res != null)
398 throw new ArgumentException ("Native resource has already been defined.");
400 version_res = new Win32VersionResource (1, 0);
402 if (cattrs != null) {
403 foreach (CustomAttributeBuilder cb in cattrs) {
404 string attrname = cb.Ctor.ReflectedType.FullName;
406 if (attrname == "System.Reflection.AssemblyProductAttribute")
407 version_res.ProductName = cb.string_arg ();
408 else if (attrname == "System.Reflection.AssemblyCompanyAttribute")
409 version_res.CompanyName = cb.string_arg ();
410 else if (attrname == "System.Reflection.AssemblyCopyrightAttribute")
411 version_res.LegalCopyright = cb.string_arg ();
412 else if (attrname == "System.Reflection.AssemblyTrademarkAttribute")
413 version_res.LegalTrademarks = cb.string_arg ();
414 else if (attrname == "System.Reflection.AssemblyCultureAttribute")
415 version_res.FileLanguage = new CultureInfo (cb.string_arg ()).LCID;
416 else if (attrname == "System.Reflection.AssemblyFileVersionAttribute")
417 version_res.FileVersion = cb.string_arg ();
418 else if (attrname == "System.Reflection.AssemblyInformationalVersionAttribute")
419 version_res.ProductVersion = cb.string_arg ();
420 else if (attrname == "System.Reflection.AssemblyTitleAttribute")
421 version_res.FileDescription = cb.string_arg ();
422 else if (attrname == "System.Reflection.AssemblyDescriptionAttribute")
423 version_res.Comments = cb.string_arg ();
428 public void DefineVersionInfoResource (string product, string productVersion,
429 string company, string copyright, string trademark)
431 if (version_res != null)
432 throw new ArgumentException ("Native resource has already been defined.");
435 * We can only create the resource later, when the file name and
436 * the binary version is known.
439 version_res = new Win32VersionResource (1, 0);
440 version_res.ProductName = product;
441 version_res.ProductVersion = productVersion;
442 version_res.CompanyName = company;
443 version_res.LegalCopyright = copyright;
444 version_res.LegalTrademarks = trademark;
448 * Mono extension to support /win32icon in mcs
450 internal void DefineIconResource (string iconFileName)
452 if (iconFileName == null)
453 throw new ArgumentNullException ("iconFileName");
454 if (iconFileName == String.Empty)
455 throw new ArgumentException ("iconFileName");
456 if (!File.Exists (iconFileName) || Directory.Exists (iconFileName))
457 throw new FileNotFoundException ("File '" + iconFileName + "' does not exists or is a directory.");
459 using (FileStream fs = new FileStream (iconFileName, FileMode.Open)) {
460 Win32IconFileReader reader = new Win32IconFileReader (fs);
462 ICONDIRENTRY[] entries = reader.ReadIcons ();
464 Win32IconResource[] icons = new Win32IconResource [entries.Length];
465 for (int i = 0; i < entries.Length; ++i) {
466 icons [i] = new Win32IconResource (i + 1, 0, entries [i]);
467 AddUnmanagedResource (icons [i]);
470 Win32GroupIconResource group = new Win32GroupIconResource (1, 0, icons);
471 AddUnmanagedResource (group);
475 private void DefineVersionInfoResourceImpl (string fileName) {
477 if (version_res.FileVersion == "0.0.0.0")
478 version_res.FileVersion = version;
479 version_res.InternalName = Path.GetFileNameWithoutExtension (fileName);
480 version_res.OriginalFilename = fileName;
482 AddUnmanagedResource (version_res);
485 public ModuleBuilder GetDynamicModule (string name)
488 throw new ArgumentNullException ("name");
490 throw new ArgumentException ("Name can't be null");
493 for (int i = 0; i < modules.Length; ++i)
494 if (modules [i].name == name)
499 public override Type[] GetExportedTypes ()
501 throw not_supported ();
504 public override FileStream GetFile (string name)
506 throw not_supported ();
509 public override FileStream[] GetFiles(bool getResourceModules) {
510 throw not_supported ();
513 public override ManifestResourceInfo GetManifestResourceInfo(string resourceName) {
514 throw not_supported ();
517 public override string[] GetManifestResourceNames() {
518 throw not_supported ();
521 public override Stream GetManifestResourceStream(string name) {
522 throw not_supported ();
524 public override Stream GetManifestResourceStream(Type type, string name) {
525 throw not_supported ();
528 internal bool IsSave {
530 return access != (uint)AssemblyBuilderAccess.Run;
534 internal string AssemblyDir {
541 * Mono extension. If this is set, the assembly can only contain one
542 * module, access should be Save, and the saved image will not contain an
545 internal bool IsModuleOnly {
547 return is_module_only;
550 is_module_only = value;
554 public void Save (string assemblyFileName)
556 if (resource_writers != null) {
557 foreach (IResourceWriter writer in resource_writers) {
563 // Create a main module if not already created
564 ModuleBuilder mainModule = null;
565 if (modules != null) {
566 foreach (ModuleBuilder module in modules)
567 if (module.FullyQualifiedName == assemblyFileName)
570 if (mainModule == null)
571 mainModule = DefineDynamicModule ("RefEmit_OnDiskManifestModule", assemblyFileName);
574 mainModule.IsMain = true;
577 * Create a new entry point if the one specified
578 * by the user is in another module.
580 if ((entry_point != null) && entry_point.DeclaringType.Module != mainModule) {
582 if (entry_point.GetParameters ().Length == 1)
583 paramTypes = new Type [] { typeof (string) };
585 paramTypes = new Type [0];
587 MethodBuilder mb = mainModule.DefineGlobalMethod ("__EntryPoint$", MethodAttributes.Static|MethodAttributes.PrivateScope, entry_point.ReturnType, paramTypes);
588 ILGenerator ilgen = mb.GetILGenerator ();
589 if (paramTypes.Length == 1)
590 ilgen.Emit (OpCodes.Ldarg_0);
591 ilgen.Emit (OpCodes.Tailcall);
592 ilgen.Emit (OpCodes.Call, entry_point);
593 ilgen.Emit (OpCodes.Ret);
598 if (version_res != null)
599 DefineVersionInfoResourceImpl (assemblyFileName);
602 // runtime needs to value to embed it into the assembly
603 public_key = sn.PublicKey;
606 foreach (ModuleBuilder module in modules)
607 if (module != mainModule)
610 // Write out the main module at the end, because it needs to
611 // contain the hash of the other modules
614 if ((sn != null) && (sn.CanSign)) {
615 sn.Sign (System.IO.Path.Combine (this.AssemblyDir, assemblyFileName));
621 public void SetEntryPoint (MethodInfo entryMethod)
623 SetEntryPoint (entryMethod, PEFileKinds.ConsoleApplication);
626 public void SetEntryPoint (MethodInfo entryMethod, PEFileKinds fileKind)
628 if (entryMethod == null)
629 throw new ArgumentNullException ("entryMethod");
630 if (entryMethod.DeclaringType.Assembly != this)
631 throw new InvalidOperationException ("Entry method is not defined in the same assembly.");
633 entry_point = entryMethod;
637 public void SetCustomAttribute( CustomAttributeBuilder customBuilder)
639 if (customBuilder == null)
640 throw new ArgumentNullException ("customBuilder");
642 string attrname = customBuilder.Ctor.ReflectedType.FullName;
646 if (attrname == "System.Reflection.AssemblyVersionAttribute") {
647 version = create_assembly_version (customBuilder.string_arg ());
649 } else if (attrname == "System.Reflection.AssemblyCultureAttribute") {
650 culture = customBuilder.string_arg ();
651 } else if (attrname == "System.Reflection.AssemblyAlgorithmIdAttribute") {
652 data = customBuilder.Data;
654 algid = (uint)data [pos];
655 algid |= ((uint)data [pos + 1]) << 8;
656 algid |= ((uint)data [pos + 2]) << 16;
657 algid |= ((uint)data [pos + 3]) << 24;
658 } else if (attrname == "System.Reflection.AssemblyFlagsAttribute") {
659 data = customBuilder.Data;
661 flags = (uint)data [pos];
662 flags |= ((uint)data [pos + 1]) << 8;
663 flags |= ((uint)data [pos + 2]) << 16;
664 flags |= ((uint)data [pos + 3]) << 24;
668 if (cattrs != null) {
669 CustomAttributeBuilder[] new_array = new CustomAttributeBuilder [cattrs.Length + 1];
670 cattrs.CopyTo (new_array, 0);
671 new_array [cattrs.Length] = customBuilder;
674 cattrs = new CustomAttributeBuilder [1];
675 cattrs [0] = customBuilder;
679 public void SetCustomAttribute ( ConstructorInfo con, byte[] binaryAttribute) {
681 throw new ArgumentNullException ("con");
682 if (binaryAttribute == null)
683 throw new ArgumentNullException ("binaryAttribute");
685 SetCustomAttribute (new CustomAttributeBuilder (con, binaryAttribute));
688 internal void SetCorlibTypeBuilders (Type corlib_object_type, Type corlib_value_type, Type corlib_enum_type) {
689 this.corlib_object_type = corlib_object_type;
690 this.corlib_value_type = corlib_value_type;
691 this.corlib_enum_type = corlib_enum_type;
694 internal void SetCorlibTypeBuilders (Type corlib_object_type, Type corlib_value_type, Type corlib_enum_type, Type corlib_void_type)
696 SetCorlibTypeBuilders (corlib_object_type, corlib_value_type, corlib_enum_type);
697 this.corlib_void_type = corlib_void_type;
700 private Exception not_supported () {
701 // Strange message but this is what MS.NET prints...
702 return new NotSupportedException ("The invoked member is not supported in a dynamic module.");
705 private void check_name_and_filename (string name, string fileName,
706 bool fileNeedsToExists) {
708 throw new ArgumentNullException ("name");
709 if (fileName == null)
710 throw new ArgumentNullException ("fileName");
712 throw new ArgumentException ("name cannot be empty", "name");
714 throw new ArgumentException ("fileName cannot be empty", "fileName");
715 if (Path.GetFileName (fileName) != fileName)
716 throw new ArgumentException ("fileName '" + fileName + "' must not include a path.");
718 // Resource files are created/searched under the assembly storage
720 string fullFileName = fileName;
722 fullFileName = Path.Combine (dir, fileName);
724 if (fileNeedsToExists && !File.Exists (fullFileName))
725 throw new FileNotFoundException ("Could not find file '" + fileName + "'");
727 if (resources != null) {
728 for (int i = 0; i < resources.Length; ++i) {
729 if (resources [i].filename == fullFileName)
730 throw new ArgumentException ("Duplicate file name '" + fileName + "'");
731 if (resources [i].name == name)
732 throw new ArgumentException ("Duplicate name '" + name + "'");
736 if (modules != null) {
737 for (int i = 0; i < modules.Length; ++i) {
738 // Use fileName instead of fullFileName here
739 if (!modules [i].IsTransient () && (modules [i].FileName == fileName))
740 throw new ArgumentException ("Duplicate file name '" + fileName + "'");
741 if (modules [i].Name == name)
742 throw new ArgumentException ("Duplicate name '" + name + "'");
747 private String create_assembly_version (String version) {
748 String[] parts = version.Split ('.');
749 int[] ver = new int [4] { 0, 0, 0, 0 };
751 if ((parts.Length < 0) || (parts.Length > 4))
752 throw new ArgumentException ("The version specified '" + version + "' is invalid");
754 for (int i = 0; i < parts.Length; ++i) {
755 if (parts [i] == "*") {
756 DateTime now = DateTime.Now;
759 ver [2] = (now - new DateTime (2000, 1, 1)).Days;
760 if (parts.Length == 3)
761 ver [3] = (now.Second + (now.Minute * 60) + (now.Hour * 3600)) / 2;
765 ver [3] = (now.Second + (now.Minute * 60) + (now.Hour * 3600)) / 2;
767 throw new ArgumentException ("The version specified '" + version + "' is invalid");
771 ver [i] = Int32.Parse (parts [i]);
773 catch (FormatException) {
774 throw new ArgumentException ("The version specified '" + version + "' is invalid");
779 return ver [0] + "." + ver [1] + "." + ver [2] + "." + ver [3];