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 sn = n.KeyPair.StrongName ();
140 public override string CodeBase {
142 throw not_supported ();
146 public override MethodInfo EntryPoint {
152 public override string Location {
154 throw not_supported ();
159 /* This is to keep signature compatibility with MS.NET */
160 public override string ImageRuntimeVersion {
162 return base.ImageRuntimeVersion;
167 public void AddResourceFile (string name, string fileName)
169 AddResourceFile (name, fileName, ResourceAttributes.Public);
172 public void AddResourceFile (string name, string fileName, ResourceAttributes attribute)
174 AddResourceFile (name, fileName, attribute, true);
177 private void AddResourceFile (string name, string fileName, ResourceAttributes attribute, bool fileNeedsToExists)
179 check_name_and_filename (name, fileName, fileNeedsToExists);
181 // Resource files are created/searched under the assembly storage
184 fileName = Path.Combine (dir, fileName);
186 if (resources != null) {
187 MonoResource[] new_r = new MonoResource [resources.Length + 1];
188 System.Array.Copy(resources, new_r, resources.Length);
191 resources = new MonoResource [1];
193 int p = resources.Length - 1;
194 resources [p].name = name;
195 resources [p].filename = fileName;
196 resources [p].attrs = attribute;
199 internal void EmbedResourceFile (string name, string fileName)
201 EmbedResourceFile (name, fileName, ResourceAttributes.Public);
204 internal void EmbedResourceFile (string name, string fileName, ResourceAttributes attribute)
206 if (resources != null) {
207 MonoResource[] new_r = new MonoResource [resources.Length + 1];
208 System.Array.Copy(resources, new_r, resources.Length);
211 resources = new MonoResource [1];
213 int p = resources.Length - 1;
214 resources [p].name = name;
215 resources [p].attrs = attribute;
217 FileStream s = new FileStream (fileName, FileMode.Open, FileAccess.Read);
219 resources [p].data = new byte [len];
220 s.Read (resources [p].data, 0, (int)len);
227 internal void EmbedResource (string name, byte[] blob, 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;
239 resources [p].data = blob;
242 public ModuleBuilder DefineDynamicModule (string name)
244 return DefineDynamicModule (name, name, false, true);
247 public ModuleBuilder DefineDynamicModule (string name, bool emitSymbolInfo)
249 return DefineDynamicModule (name, name, emitSymbolInfo, true);
252 public ModuleBuilder DefineDynamicModule(string name, string fileName)
254 return DefineDynamicModule (name, fileName, false, false);
257 public ModuleBuilder DefineDynamicModule (string name, string fileName,
260 return DefineDynamicModule (name, fileName, emitSymbolInfo, false);
263 private ModuleBuilder DefineDynamicModule (string name, string fileName,
264 bool emitSymbolInfo, bool transient)
266 check_name_and_filename (name, fileName, false);
269 if (Path.GetExtension (fileName) == String.Empty)
270 throw new ArgumentException ("Module file name '" + fileName + "' must have file extension.");
272 throw new NotSupportedException ("Persistable modules are not supported in a dynamic assembly created with AssemblyBuilderAccess.Run");
274 throw new InvalidOperationException ("Assembly was already saved.");
277 ModuleBuilder r = new ModuleBuilder (this, name, fileName, emitSymbolInfo, transient);
279 if ((modules != null) && is_module_only)
280 throw new InvalidOperationException ("A module-only assembly can only contain one module.");
282 if (modules != null) {
283 ModuleBuilder[] new_modules = new ModuleBuilder [modules.Length + 1];
284 System.Array.Copy(modules, new_modules, modules.Length);
285 modules = new_modules;
287 modules = new ModuleBuilder [1];
289 modules [modules.Length - 1] = r;
293 [MethodImplAttribute(MethodImplOptions.InternalCall)]
294 private extern Module InternalAddModule (string fileName);
297 * Mono extension to support /addmodule in mcs.
299 internal Module AddModule (string fileName)
301 if (fileName == null)
302 throw new ArgumentNullException (fileName);
304 Module m = InternalAddModule (fileName);
306 if (loaded_modules != null) {
307 Module[] new_modules = new Module [loaded_modules.Length + 1];
308 System.Array.Copy (loaded_modules, new_modules, loaded_modules.Length);
309 loaded_modules = new_modules;
311 loaded_modules = new Module [1];
313 loaded_modules [loaded_modules.Length - 1] = m;
318 public IResourceWriter DefineResource (string name, string description, string fileName)
320 return DefineResource (name, description, fileName, ResourceAttributes.Public);
323 public IResourceWriter DefineResource (string name, string description,
324 string fileName, ResourceAttributes attribute)
326 IResourceWriter writer;
328 // description seems to be ignored
329 AddResourceFile (name, fileName, attribute, false);
330 writer = new ResourceWriter (fileName);
331 if (resource_writers == null)
332 resource_writers = new ArrayList ();
333 resource_writers.Add (writer);
337 private void AddUnmanagedResource (Win32Resource res) {
338 MemoryStream ms = new MemoryStream ();
341 if (win32_resources != null) {
342 MonoWin32Resource[] new_res = new MonoWin32Resource [win32_resources.Length + 1];
343 System.Array.Copy (win32_resources, new_res, win32_resources.Length);
344 win32_resources = new_res;
347 win32_resources = new MonoWin32Resource [1];
349 win32_resources [win32_resources.Length - 1] = new MonoWin32Resource (res.Type.Id, res.Name.Id, res.Language, ms.ToArray ());
353 public void DefineUnmanagedResource (byte[] resource)
355 if (resource == null)
356 throw new ArgumentNullException ("resource");
359 * The format of the argument byte array is not documented
360 * so this method is impossible to implement.
363 throw new NotImplementedException ();
366 public void DefineUnmanagedResource (string resourceFileName)
368 if (resourceFileName == null)
369 throw new ArgumentNullException ("resourceFileName");
370 if (resourceFileName == String.Empty)
371 throw new ArgumentException ("resourceFileName");
372 if (!File.Exists (resourceFileName) || Directory.Exists (resourceFileName))
373 throw new FileNotFoundException ("File '" + resourceFileName + "' does not exists or is a directory.");
375 using (FileStream fs = new FileStream (resourceFileName, FileMode.Open)) {
376 Win32ResFileReader reader = new Win32ResFileReader (fs);
378 foreach (Win32EncodedResource res in reader.ReadResources ()) {
379 if (res.Name.IsName || res.Type.IsName)
380 throw new InvalidOperationException ("resource files with named resources or non-default resource types are not supported.");
382 AddUnmanagedResource (res);
387 public void DefineVersionInfoResource ()
389 if (version_res != null)
390 throw new ArgumentException ("Native resource has already been defined.");
392 version_res = new Win32VersionResource (1, 0);
394 if (cattrs != null) {
395 foreach (CustomAttributeBuilder cb in cattrs) {
396 string attrname = cb.Ctor.ReflectedType.FullName;
398 if (attrname == "System.Reflection.AssemblyProductAttribute")
399 version_res.ProductName = cb.string_arg ();
400 else if (attrname == "System.Reflection.AssemblyCompanyAttribute")
401 version_res.CompanyName = cb.string_arg ();
402 else if (attrname == "System.Reflection.AssemblyCopyrightAttribute")
403 version_res.LegalCopyright = cb.string_arg ();
404 else if (attrname == "System.Reflection.AssemblyTrademarkAttribute")
405 version_res.LegalTrademarks = cb.string_arg ();
406 else if (attrname == "System.Reflection.AssemblyCultureAttribute")
407 version_res.FileLanguage = new CultureInfo (cb.string_arg ()).LCID;
408 else if (attrname == "System.Reflection.AssemblyFileVersionAttribute")
409 version_res.FileVersion = cb.string_arg ();
410 else if (attrname == "System.Reflection.AssemblyInformationalVersionAttribute")
411 version_res.ProductVersion = cb.string_arg ();
412 else if (attrname == "System.Reflection.AssemblyTitleAttribute")
413 version_res.FileDescription = cb.string_arg ();
414 else if (attrname == "System.Reflection.AssemblyDescriptionAttribute")
415 version_res.Comments = cb.string_arg ();
420 public void DefineVersionInfoResource (string product, string productVersion,
421 string company, string copyright, string trademark)
423 if (version_res != null)
424 throw new ArgumentException ("Native resource has already been defined.");
427 * We can only create the resource later, when the file name and
428 * the binary version is known.
431 version_res = new Win32VersionResource (1, 0);
432 version_res.ProductName = product;
433 version_res.ProductVersion = productVersion;
434 version_res.CompanyName = company;
435 version_res.LegalCopyright = copyright;
436 version_res.LegalTrademarks = trademark;
440 * Mono extension to support /win32icon in mcs
442 internal void DefineIconResource (string iconFileName)
444 if (iconFileName == null)
445 throw new ArgumentNullException ("iconFileName");
446 if (iconFileName == String.Empty)
447 throw new ArgumentException ("iconFileName");
448 if (!File.Exists (iconFileName) || Directory.Exists (iconFileName))
449 throw new FileNotFoundException ("File '" + iconFileName + "' does not exists or is a directory.");
451 using (FileStream fs = new FileStream (iconFileName, FileMode.Open)) {
452 Win32IconFileReader reader = new Win32IconFileReader (fs);
454 ICONDIRENTRY[] entries = reader.ReadIcons ();
456 Win32IconResource[] icons = new Win32IconResource [entries.Length];
457 for (int i = 0; i < entries.Length; ++i) {
458 icons [i] = new Win32IconResource (i + 1, 0, entries [i]);
459 AddUnmanagedResource (icons [i]);
462 Win32GroupIconResource group = new Win32GroupIconResource (1, 0, icons);
463 AddUnmanagedResource (group);
467 private void DefineVersionInfoResourceImpl (string fileName) {
469 if (version_res.FileVersion == "0.0.0.0")
470 version_res.FileVersion = version;
471 version_res.InternalName = Path.GetFileNameWithoutExtension (fileName);
472 version_res.OriginalFilename = fileName;
474 AddUnmanagedResource (version_res);
477 public ModuleBuilder GetDynamicModule (string name)
480 throw new ArgumentNullException ("name");
482 throw new ArgumentException ("Name can't be null");
485 for (int i = 0; i < modules.Length; ++i)
486 if (modules [i].name == name)
491 public override Type[] GetExportedTypes ()
493 throw not_supported ();
496 public override FileStream GetFile (string name)
498 throw not_supported ();
501 public override FileStream[] GetFiles(bool getResourceModules) {
502 throw not_supported ();
505 public override ManifestResourceInfo GetManifestResourceInfo(string resourceName) {
506 throw not_supported ();
509 public override string[] GetManifestResourceNames() {
510 throw not_supported ();
513 public override Stream GetManifestResourceStream(string name) {
514 throw not_supported ();
516 public override Stream GetManifestResourceStream(Type type, string name) {
517 throw not_supported ();
520 internal bool IsSave {
522 return access != (uint)AssemblyBuilderAccess.Run;
526 internal string AssemblyDir {
533 * Mono extension. If this is set, the assembly can only contain one
534 * module, access should be Save, and the saved image will not contain an
537 internal bool IsModuleOnly {
539 return is_module_only;
542 is_module_only = value;
546 public void Save (string assemblyFileName)
548 if (resource_writers != null) {
549 foreach (IResourceWriter writer in resource_writers) {
555 // Create a main module if not already created
556 ModuleBuilder mainModule = null;
557 if (modules != null) {
558 foreach (ModuleBuilder module in modules)
559 if (module.FullyQualifiedName == assemblyFileName)
562 if (mainModule == null)
563 mainModule = DefineDynamicModule ("RefEmit_OnDiskManifestModule", assemblyFileName);
566 mainModule.IsMain = true;
569 * Create a new entry point if the one specified
570 * by the user is in another module.
572 if ((entry_point != null) && entry_point.DeclaringType.Module != mainModule) {
574 if (entry_point.GetParameters ().Length == 1)
575 paramTypes = new Type [] { typeof (string) };
577 paramTypes = new Type [0];
579 MethodBuilder mb = mainModule.DefineGlobalMethod ("__EntryPoint$", MethodAttributes.Static|MethodAttributes.PrivateScope, entry_point.ReturnType, paramTypes);
580 ILGenerator ilgen = mb.GetILGenerator ();
581 if (paramTypes.Length == 1)
582 ilgen.Emit (OpCodes.Ldarg_0);
583 ilgen.Emit (OpCodes.Tailcall);
584 ilgen.Emit (OpCodes.Call, entry_point);
585 ilgen.Emit (OpCodes.Ret);
590 if (version_res != null)
591 DefineVersionInfoResourceImpl (assemblyFileName);
594 // runtime needs to value to embed it into the assembly
595 public_key = sn.PublicKey;
598 foreach (ModuleBuilder module in modules)
599 if (module != mainModule)
602 // Write out the main module at the end, because it needs to
603 // contain the hash of the other modules
606 if ((sn != null) && (sn.CanSign)) {
607 sn.Sign (System.IO.Path.Combine (this.AssemblyDir, assemblyFileName));
613 public void SetEntryPoint (MethodInfo entryMethod)
615 SetEntryPoint (entryMethod, PEFileKinds.ConsoleApplication);
618 public void SetEntryPoint (MethodInfo entryMethod, PEFileKinds fileKind)
620 if (entryMethod == null)
621 throw new ArgumentNullException ("entryMethod");
622 if (entryMethod.DeclaringType.Assembly != this)
623 throw new InvalidOperationException ("Entry method is not defined in the same assembly.");
625 entry_point = entryMethod;
629 public void SetCustomAttribute( CustomAttributeBuilder customBuilder)
631 if (customBuilder == null)
632 throw new ArgumentNullException ("customBuilder");
634 string attrname = customBuilder.Ctor.ReflectedType.FullName;
638 if (attrname == "System.Reflection.AssemblyVersionAttribute") {
639 version = create_assembly_version (customBuilder.string_arg ());
641 } else if (attrname == "System.Reflection.AssemblyCultureAttribute") {
642 culture = customBuilder.string_arg ();
643 } else if (attrname == "System.Reflection.AssemblyAlgorithmIdAttribute") {
644 data = customBuilder.Data;
646 algid = (uint)data [pos];
647 algid |= ((uint)data [pos + 1]) << 8;
648 algid |= ((uint)data [pos + 2]) << 16;
649 algid |= ((uint)data [pos + 3]) << 24;
650 } else if (attrname == "System.Reflection.AssemblyFlagsAttribute") {
651 data = customBuilder.Data;
653 flags = (uint)data [pos];
654 flags |= ((uint)data [pos + 1]) << 8;
655 flags |= ((uint)data [pos + 2]) << 16;
656 flags |= ((uint)data [pos + 3]) << 24;
660 if (cattrs != null) {
661 CustomAttributeBuilder[] new_array = new CustomAttributeBuilder [cattrs.Length + 1];
662 cattrs.CopyTo (new_array, 0);
663 new_array [cattrs.Length] = customBuilder;
666 cattrs = new CustomAttributeBuilder [1];
667 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 internal 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 internal 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];