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 [MethodImplAttribute(MethodImplOptions.InternalCall)]
90 private static extern void basic_init (AssemblyBuilder ab);
92 internal AssemblyBuilder (AssemblyName n, string directory, AssemblyBuilderAccess access) {
94 if (directory == null || directory == String.Empty)
95 dir = Directory.GetCurrentDirectory ();
98 this.access = (uint)access;
100 /* Set defaults from n */
101 if (n.CultureInfo != null) {
102 culture = n.CultureInfo.Name;
104 Version v = n.Version;
106 version = v.ToString ();
112 public override string CodeBase {
114 throw not_supported ();
118 public override MethodInfo EntryPoint {
124 public override string Location {
126 throw not_supported ();
131 /* This is to keep signature compatibility with MS.NET */
132 public override string ImageRuntimeVersion {
134 return base.ImageRuntimeVersion;
139 public void AddResourceFile (string name, string fileName)
141 AddResourceFile (name, fileName, ResourceAttributes.Public);
144 public void AddResourceFile (string name, string fileName, ResourceAttributes attribute)
146 AddResourceFile (name, fileName, attribute, true);
149 private void AddResourceFile (string name, string fileName, ResourceAttributes attribute, bool fileNeedsToExists)
151 check_name_and_filename (name, fileName, fileNeedsToExists);
153 // Resource files are created/searched under the assembly storage
156 fileName = Path.Combine (dir, fileName);
158 if (resources != null) {
159 MonoResource[] new_r = new MonoResource [resources.Length + 1];
160 System.Array.Copy(resources, new_r, resources.Length);
163 resources = new MonoResource [1];
165 int p = resources.Length - 1;
166 resources [p].name = name;
167 resources [p].filename = fileName;
168 resources [p].attrs = attribute;
171 public void EmbedResourceFile (string name, string fileName)
173 EmbedResourceFile (name, fileName, ResourceAttributes.Public);
176 public void EmbedResourceFile (string name, string fileName, ResourceAttributes attribute)
178 if (resources != null) {
179 MonoResource[] new_r = new MonoResource [resources.Length + 1];
180 System.Array.Copy(resources, new_r, resources.Length);
183 resources = new MonoResource [1];
185 int p = resources.Length - 1;
186 resources [p].name = name;
187 resources [p].attrs = attribute;
189 FileStream s = new FileStream (fileName, FileMode.Open, FileAccess.Read);
191 resources [p].data = new byte [len];
192 s.Read (resources [p].data, 0, (int)len);
199 internal void EmbedResource (string name, byte[] blob, ResourceAttributes attribute)
201 if (resources != null) {
202 MonoResource[] new_r = new MonoResource [resources.Length + 1];
203 System.Array.Copy(resources, new_r, resources.Length);
206 resources = new MonoResource [1];
208 int p = resources.Length - 1;
209 resources [p].name = name;
210 resources [p].attrs = attribute;
211 resources [p].data = blob;
214 public ModuleBuilder DefineDynamicModule (string name)
216 return DefineDynamicModule (name, name, false, true);
219 public ModuleBuilder DefineDynamicModule (string name, bool emitSymbolInfo)
221 return DefineDynamicModule (name, name, emitSymbolInfo, true);
224 public ModuleBuilder DefineDynamicModule(string name, string fileName)
226 return DefineDynamicModule (name, fileName, false, false);
229 public ModuleBuilder DefineDynamicModule (string name, string fileName,
232 return DefineDynamicModule (name, fileName, emitSymbolInfo, false);
235 private ModuleBuilder DefineDynamicModule (string name, string fileName,
236 bool emitSymbolInfo, bool transient)
238 check_name_and_filename (name, fileName, false);
241 if (Path.GetExtension (fileName) == String.Empty)
242 throw new ArgumentException ("Module file name '" + fileName + "' must have file extension.");
244 throw new NotSupportedException ("Persistable modules are not supported in a dynamic assembly created with AssemblyBuilderAccess.Run");
246 throw new InvalidOperationException ("Assembly was already saved.");
249 ModuleBuilder r = new ModuleBuilder (this, name, fileName, emitSymbolInfo, transient);
251 if ((modules != null) && is_module_only)
252 throw new InvalidOperationException ("A module-only assembly can only contain one module.");
254 if (modules != null) {
255 ModuleBuilder[] new_modules = new ModuleBuilder [modules.Length + 1];
256 System.Array.Copy(modules, new_modules, modules.Length);
257 modules = new_modules;
259 modules = new ModuleBuilder [1];
261 modules [modules.Length - 1] = r;
265 [MethodImplAttribute(MethodImplOptions.InternalCall)]
266 private extern Module InternalAddModule (string fileName);
269 * Mono extension to support /addmodule in mcs.
271 internal Module AddModule (string fileName)
273 if (fileName == null)
274 throw new ArgumentNullException (fileName);
276 Module m = InternalAddModule (fileName);
278 if (loaded_modules != null) {
279 Module[] new_modules = new Module [loaded_modules.Length + 1];
280 System.Array.Copy (loaded_modules, new_modules, loaded_modules.Length);
281 loaded_modules = new_modules;
283 loaded_modules = new Module [1];
285 loaded_modules [loaded_modules.Length - 1] = m;
290 public IResourceWriter DefineResource (string name, string description, string fileName)
292 return DefineResource (name, description, fileName, ResourceAttributes.Public);
295 public IResourceWriter DefineResource (string name, string description,
296 string fileName, ResourceAttributes attribute)
298 IResourceWriter writer;
300 // description seems to be ignored
301 AddResourceFile (name, fileName, attribute, false);
302 writer = new ResourceWriter (fileName);
303 if (resource_writers == null)
304 resource_writers = new ArrayList ();
305 resource_writers.Add (writer);
309 private void AddUnmanagedResource (Win32Resource res) {
310 MemoryStream ms = new MemoryStream ();
313 if (win32_resources != null) {
314 MonoWin32Resource[] new_res = new MonoWin32Resource [win32_resources.Length + 1];
315 System.Array.Copy (win32_resources, new_res, win32_resources.Length);
316 win32_resources = new_res;
319 win32_resources = new MonoWin32Resource [1];
321 win32_resources [win32_resources.Length - 1] = new MonoWin32Resource (res.Type.Id, res.Name.Id, res.Language, ms.ToArray ());
325 public void DefineUnmanagedResource (byte[] resource)
327 if (resource == null)
328 throw new ArgumentNullException ("resource");
331 * The format of the argument byte array is not documented
332 * so this method is impossible to implement.
335 throw new NotImplementedException ();
338 public void DefineUnmanagedResource (string resourceFileName)
340 if (resourceFileName == null)
341 throw new ArgumentNullException ("resourceFileName");
342 if (resourceFileName == String.Empty)
343 throw new ArgumentException ("resourceFileName");
344 if (!File.Exists (resourceFileName) || Directory.Exists (resourceFileName))
345 throw new FileNotFoundException ("File '" + resourceFileName + "' does not exists or is a directory.");
347 using (FileStream fs = new FileStream (resourceFileName, FileMode.Open)) {
348 Win32ResFileReader reader = new Win32ResFileReader (fs);
350 foreach (Win32EncodedResource res in reader.ReadResources ()) {
351 if (res.Name.IsName || res.Type.IsName)
352 throw new InvalidOperationException ("resource files with named resources or non-default resource types are not supported.");
354 AddUnmanagedResource (res);
359 public void DefineVersionInfoResource ()
361 if (version_res != null)
362 throw new ArgumentException ("Native resource has already been defined.");
364 version_res = new Win32VersionResource (1, 0);
366 if (cattrs != null) {
367 foreach (CustomAttributeBuilder cb in cattrs) {
368 string attrname = cb.Ctor.ReflectedType.FullName;
370 if (attrname == "System.Reflection.AssemblyProductAttribute")
371 version_res.ProductName = cb.string_arg ();
372 else if (attrname == "System.Reflection.AssemblyCompanyAttribute")
373 version_res.CompanyName = cb.string_arg ();
374 else if (attrname == "System.Reflection.AssemblyCopyrightAttribute")
375 version_res.LegalCopyright = cb.string_arg ();
376 else if (attrname == "System.Reflection.AssemblyTrademarkAttribute")
377 version_res.LegalTrademarks = cb.string_arg ();
378 else if (attrname == "System.Reflection.AssemblyCultureAttribute")
379 version_res.FileLanguage = new CultureInfo (cb.string_arg ()).LCID;
380 else if (attrname == "System.Reflection.AssemblyFileVersionAttribute")
381 version_res.FileVersion = cb.string_arg ();
382 else if (attrname == "System.Reflection.AssemblyInformationalVersionAttribute")
383 version_res.ProductVersion = cb.string_arg ();
384 else if (attrname == "System.Reflection.AssemblyTitleAttribute")
385 version_res.FileDescription = cb.string_arg ();
386 else if (attrname == "System.Reflection.AssemblyDescriptionAttribute")
387 version_res.Comments = cb.string_arg ();
392 public void DefineVersionInfoResource (string product, string productVersion,
393 string company, string copyright, string trademark)
395 if (version_res != null)
396 throw new ArgumentException ("Native resource has already been defined.");
399 * We can only create the resource later, when the file name and
400 * the binary version is known.
403 version_res = new Win32VersionResource (1, 0);
404 version_res.ProductName = product;
405 version_res.ProductVersion = productVersion;
406 version_res.CompanyName = company;
407 version_res.LegalCopyright = copyright;
408 version_res.LegalTrademarks = trademark;
412 * Mono extension to support /win32icon in mcs
414 internal void DefineIconResource (string iconFileName)
416 if (iconFileName == null)
417 throw new ArgumentNullException ("iconFileName");
418 if (iconFileName == String.Empty)
419 throw new ArgumentException ("iconFileName");
420 if (!File.Exists (iconFileName) || Directory.Exists (iconFileName))
421 throw new FileNotFoundException ("File '" + iconFileName + "' does not exists or is a directory.");
423 using (FileStream fs = new FileStream (iconFileName, FileMode.Open)) {
424 Win32IconFileReader reader = new Win32IconFileReader (fs);
426 ICONDIRENTRY[] entries = reader.ReadIcons ();
428 Win32IconResource[] icons = new Win32IconResource [entries.Length];
429 for (int i = 0; i < entries.Length; ++i) {
430 icons [i] = new Win32IconResource (i + 1, 0, entries [i]);
431 AddUnmanagedResource (icons [i]);
434 Win32GroupIconResource group = new Win32GroupIconResource (1, 0, icons);
435 AddUnmanagedResource (group);
439 private void DefineVersionInfoResourceImpl (string fileName) {
441 if (version_res.FileVersion == "0.0.0.0")
442 version_res.FileVersion = version;
443 version_res.InternalName = Path.GetFileNameWithoutExtension (fileName);
444 version_res.OriginalFilename = fileName;
446 AddUnmanagedResource (version_res);
449 public ModuleBuilder GetDynamicModule (string name)
452 throw new ArgumentNullException ("name");
454 throw new ArgumentException ("Name can't be null");
457 for (int i = 0; i < modules.Length; ++i)
458 if (modules [i].name == name)
463 public override Type[] GetExportedTypes ()
465 throw not_supported ();
468 public override FileStream GetFile (string name)
470 throw not_supported ();
473 public override FileStream[] GetFiles(bool getResourceModules) {
474 throw not_supported ();
477 public override ManifestResourceInfo GetManifestResourceInfo(string resourceName) {
478 throw not_supported ();
481 public override string[] GetManifestResourceNames() {
482 throw not_supported ();
485 public override Stream GetManifestResourceStream(string name) {
486 throw not_supported ();
488 public override Stream GetManifestResourceStream(Type type, string name) {
489 throw not_supported ();
492 internal bool IsSave {
494 return access != (uint)AssemblyBuilderAccess.Run;
498 internal string AssemblyDir {
505 * Mono extension. If this is set, the assembly can only contain one
506 * module, access should be Save, and the saved image will not contain an
509 internal bool IsModuleOnly {
511 return is_module_only;
514 is_module_only = value;
518 public void Save (string assemblyFileName)
520 if (resource_writers != null) {
521 foreach (IResourceWriter writer in resource_writers) {
527 // Create a main module if not already created
528 ModuleBuilder mainModule = null;
529 if (modules != null) {
530 foreach (ModuleBuilder module in modules)
531 if (module.FullyQualifiedName == assemblyFileName)
534 if (mainModule == null)
535 mainModule = DefineDynamicModule ("RefEmit_OnDiskManifestModule", assemblyFileName);
538 mainModule.IsMain = true;
540 if (version_res != null)
541 DefineVersionInfoResourceImpl (assemblyFileName);
543 foreach (ModuleBuilder module in modules)
544 if (module != mainModule)
547 // Write out the main module at the end, because it needs to
548 // contain the hash of the other modules
554 public void SetEntryPoint (MethodInfo entryMethod)
556 SetEntryPoint (entryMethod, PEFileKinds.ConsoleApplication);
559 public void SetEntryPoint (MethodInfo entryMethod, PEFileKinds fileKind)
561 if (entryMethod == null)
562 throw new ArgumentNullException ("entryMethod");
563 if (entryMethod.DeclaringType.Assembly != this)
564 throw new InvalidOperationException ("Entry method is not defined in the same assembly.");
566 entry_point = entryMethod;
570 public void SetCustomAttribute( CustomAttributeBuilder customBuilder)
572 if (customBuilder == null)
573 throw new ArgumentNullException ("customBuilder");
575 string attrname = customBuilder.Ctor.ReflectedType.FullName;
578 Mono.Security.StrongName sn;
579 if (attrname == "System.Reflection.AssemblyVersionAttribute") {
580 version = create_assembly_version (customBuilder.string_arg ());
582 } else if (attrname == "System.Reflection.AssemblyKeyFileAttribute") {
583 string keyfile_name = customBuilder.string_arg ();
584 if (keyfile_name == String.Empty)
586 using (FileStream fs = new FileStream (keyfile_name, 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;
597 } else if (attrname == "System.Reflection.AssemblyKeyNameAttribute") {
598 string key_name = customBuilder.string_arg ();
599 if (key_name == String.Empty)
601 CspParameters csparam = new CspParameters ();
602 csparam.KeyContainerName = key_name;
603 RSA rsacsp = new RSACryptoServiceProvider (csparam);
604 sn = new Mono.Security.StrongName (rsacsp);
605 public_key = sn.PublicKey;
607 } else if (attrname == "System.Reflection.AssemblyCultureAttribute") {
608 culture = customBuilder.string_arg ();
609 } else if (attrname == "System.Reflection.AssemblyAlgorithmIdAttribute") {
610 data = customBuilder.Data;
612 algid = (uint)data [pos];
613 algid |= ((uint)data [pos + 1]) << 8;
614 algid |= ((uint)data [pos + 2]) << 16;
615 algid |= ((uint)data [pos + 3]) << 24;
616 } else if (attrname == "System.Reflection.AssemblyFlagsAttribute") {
617 data = customBuilder.Data;
619 flags = (uint)data [pos];
620 flags |= ((uint)data [pos + 1]) << 8;
621 flags |= ((uint)data [pos + 2]) << 16;
622 flags |= ((uint)data [pos + 3]) << 24;
624 } else if (attrname == "System.Reflection.AssemblyDelaySignAttribute") {
625 data = customBuilder.Data;
627 delay_sign = data [2] != 0;
629 if (cattrs != null) {
630 CustomAttributeBuilder[] new_array = new CustomAttributeBuilder [cattrs.Length + 1];
631 cattrs.CopyTo (new_array, 0);
632 new_array [cattrs.Length] = customBuilder;
635 cattrs = new CustomAttributeBuilder [1];
636 cattrs [0] = customBuilder;
639 public void SetCustomAttribute ( ConstructorInfo con, byte[] binaryAttribute) {
641 throw new ArgumentNullException ("con");
642 if (binaryAttribute == null)
643 throw new ArgumentNullException ("binaryAttribute");
645 SetCustomAttribute (new CustomAttributeBuilder (con, binaryAttribute));
648 public void SetCorlibTypeBuilders (Type corlib_object_type, Type corlib_value_type, Type corlib_enum_type) {
649 this.corlib_object_type = corlib_object_type;
650 this.corlib_value_type = corlib_value_type;
651 this.corlib_enum_type = corlib_enum_type;
654 public void SetCorlibTypeBuilders (Type corlib_object_type, Type corlib_value_type, Type corlib_enum_type, Type corlib_void_type)
656 SetCorlibTypeBuilders (corlib_object_type, corlib_value_type, corlib_enum_type);
657 this.corlib_void_type = corlib_void_type;
660 private Exception not_supported () {
661 // Strange message but this is what MS.NET prints...
662 return new NotSupportedException ("The invoked member is not supported in a dynamic module.");
665 private void check_name_and_filename (string name, string fileName,
666 bool fileNeedsToExists) {
668 throw new ArgumentNullException ("name");
669 if (fileName == null)
670 throw new ArgumentNullException ("fileName");
672 throw new ArgumentException ("name cannot be empty", "name");
674 throw new ArgumentException ("fileName cannot be empty", "fileName");
675 if (Path.GetFileName (fileName) != fileName)
676 throw new ArgumentException ("fileName '" + fileName + "' must not include a path.");
678 // Resource files are created/searched under the assembly storage
680 string fullFileName = fileName;
682 fullFileName = Path.Combine (dir, fileName);
684 if (fileNeedsToExists && !File.Exists (fullFileName))
685 throw new FileNotFoundException ("Could not find file '" + fileName + "'");
687 if (resources != null) {
688 for (int i = 0; i < resources.Length; ++i) {
689 if (resources [i].filename == fullFileName)
690 throw new ArgumentException ("Duplicate file name '" + fileName + "'");
691 if (resources [i].name == name)
692 throw new ArgumentException ("Duplicate name '" + name + "'");
696 if (modules != null) {
697 for (int i = 0; i < modules.Length; ++i) {
698 // Use fileName instead of fullFileName here
699 if (!modules [i].IsTransient () && (modules [i].FileName == fileName))
700 throw new ArgumentException ("Duplicate file name '" + fileName + "'");
701 if (modules [i].Name == name)
702 throw new ArgumentException ("Duplicate name '" + name + "'");
707 private String create_assembly_version (String version) {
708 String[] parts = version.Split ('.');
709 int[] ver = new int [4] { 0, 0, 0, 0 };
711 if ((parts.Length < 0) || (parts.Length > 4))
712 throw new ArgumentException ("The version specified '" + version + "' is invalid");
714 for (int i = 0; i < parts.Length; ++i) {
715 if (parts [i] == "*") {
716 DateTime now = DateTime.Now;
719 ver [2] = (now - new DateTime (2000, 1, 1)).Days;
720 if (parts.Length == 3)
721 ver [3] = (now.Second + (now.Minute * 60) + (now.Hour * 3600)) / 2;
725 ver [3] = (now.Second + (now.Minute * 60) + (now.Hour * 3600)) / 2;
727 throw new ArgumentException ("The version specified '" + version + "' is invalid");
731 ver [i] = Int32.Parse (parts [i]);
733 catch (FormatException) {
734 throw new ArgumentException ("The version specified '" + version + "' is invalid");
739 return ver [0] + "." + ver [1] + "." + ver [2] + "." + ver [3];