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 ();
386 public void DefineVersionInfoResource (string product, string productVersion,
387 string company, string copyright, string trademark)
389 if (version_res != null)
390 throw new ArgumentException ("Native resource has already been defined.");
393 * We can only create the resource later, when the file name and
394 * the binary version is known.
397 version_res = new Win32VersionResource (1, 0);
398 version_res.ProductName = product;
399 version_res.ProductVersion = productVersion;
400 version_res.CompanyName = company;
401 version_res.LegalCopyright = copyright;
402 version_res.LegalTrademarks = trademark;
406 * Mono extension to support /win32icon in mcs
408 internal void DefineIconResource (string iconFileName)
410 if (iconFileName == null)
411 throw new ArgumentNullException ("iconFileName");
412 if (iconFileName == String.Empty)
413 throw new ArgumentException ("iconFileName");
414 if (!File.Exists (iconFileName) || Directory.Exists (iconFileName))
415 throw new FileNotFoundException ("File '" + iconFileName + "' does not exists or is a directory.");
417 using (FileStream fs = new FileStream (iconFileName, FileMode.Open)) {
418 Win32IconFileReader reader = new Win32IconFileReader (fs);
420 ICONDIRENTRY[] entries = reader.ReadIcons ();
422 Win32IconResource[] icons = new Win32IconResource [entries.Length];
423 for (int i = 0; i < entries.Length; ++i) {
424 icons [i] = new Win32IconResource (i + 1, 0, entries [i]);
425 AddUnmanagedResource (icons [i]);
428 Win32GroupIconResource group = new Win32GroupIconResource (1, 0, icons);
429 AddUnmanagedResource (group);
433 private void DefineVersionInfoResourceImpl (string fileName) {
435 if (version_res.FileVersion == "0.0.0.0")
436 version_res.FileVersion = version;
437 version_res.OriginalFilename = fileName;
439 AddUnmanagedResource (version_res);
442 public ModuleBuilder GetDynamicModule (string name)
445 throw new ArgumentNullException ("name");
447 throw new ArgumentException ("Name can't be null");
450 for (int i = 0; i < modules.Length; ++i)
451 if (modules [i].name == name)
456 public override Type[] GetExportedTypes ()
458 throw not_supported ();
461 public override FileStream GetFile (string name)
463 throw not_supported ();
466 public override FileStream[] GetFiles(bool getResourceModules) {
467 throw not_supported ();
470 public override ManifestResourceInfo GetManifestResourceInfo(string resourceName) {
471 throw not_supported ();
474 public override string[] GetManifestResourceNames() {
475 throw not_supported ();
478 public override Stream GetManifestResourceStream(string name) {
479 throw not_supported ();
481 public override Stream GetManifestResourceStream(Type type, string name) {
482 throw not_supported ();
485 internal bool IsSave {
487 return access != (uint)AssemblyBuilderAccess.Run;
491 internal string AssemblyDir {
498 * Mono extension. If this is set, the assembly can only contain one
499 * module, access should be Save, and the saved image will not contain an
502 internal bool IsModuleOnly {
504 return is_module_only;
507 is_module_only = value;
511 public void Save (string assemblyFileName)
513 if (resource_writers != null) {
514 foreach (IResourceWriter writer in resource_writers) {
520 // Create a main module if not already created
521 ModuleBuilder mainModule = null;
522 if (modules != null) {
523 foreach (ModuleBuilder module in modules)
524 if (module.FullyQualifiedName == assemblyFileName)
527 if (mainModule == null)
528 mainModule = DefineDynamicModule ("RefEmit_OnDiskManifestModule", assemblyFileName);
531 mainModule.IsMain = true;
533 if (version_res != null)
534 DefineVersionInfoResourceImpl (assemblyFileName);
536 foreach (ModuleBuilder module in modules)
537 if (module != mainModule)
540 // Write out the main module at the end, because it needs to
541 // contain the hash of the other modules
547 public void SetEntryPoint (MethodInfo entryMethod)
549 SetEntryPoint (entryMethod, PEFileKinds.ConsoleApplication);
552 public void SetEntryPoint (MethodInfo entryMethod, PEFileKinds fileKind)
554 if (entryMethod == null)
555 throw new ArgumentNullException ("entryMethod");
556 if (entryMethod.DeclaringType.Assembly != this)
557 throw new InvalidOperationException ("Entry method is not defined in the same assembly.");
559 entry_point = entryMethod;
563 public void SetCustomAttribute( CustomAttributeBuilder customBuilder)
565 if (customBuilder == null)
566 throw new ArgumentNullException ("customBuilder");
568 string attrname = customBuilder.Ctor.ReflectedType.FullName;
571 Mono.Security.StrongName sn;
572 if (attrname == "System.Reflection.AssemblyVersionAttribute") {
573 version = create_assembly_version (customBuilder.string_arg ());
575 } else if (attrname == "System.Reflection.AssemblyKeyFileAttribute") {
576 string keyfile_name = customBuilder.string_arg ();
577 if (keyfile_name == String.Empty)
579 using (FileStream fs = new FileStream (keyfile_name, FileMode.Open)) {
580 byte[] snkeypair = new byte [fs.Length];
581 fs.Read (snkeypair, 0, snkeypair.Length);
583 // this will import public or private/public keys
584 RSA rsa = CryptoConvert.FromCapiKeyBlob (snkeypair);
585 // and export only the public part
586 sn = new Mono.Security.StrongName (rsa);
587 public_key = sn.PublicKey;
590 } else if (attrname == "System.Reflection.AssemblyKeyNameAttribute") {
591 string key_name = customBuilder.string_arg ();
592 if (key_name == String.Empty)
594 CspParameters csparam = new CspParameters ();
595 csparam.KeyContainerName = key_name;
596 RSA rsacsp = new RSACryptoServiceProvider (csparam);
597 sn = new Mono.Security.StrongName (rsacsp);
598 public_key = sn.PublicKey;
600 } else if (attrname == "System.Reflection.AssemblyCultureAttribute") {
601 culture = customBuilder.string_arg ();
602 } else if (attrname == "System.Reflection.AssemblyAlgorithmIdAttribute") {
603 data = customBuilder.Data;
605 algid = (uint)data [pos];
606 algid |= ((uint)data [pos + 1]) << 8;
607 algid |= ((uint)data [pos + 2]) << 16;
608 algid |= ((uint)data [pos + 3]) << 24;
609 } else if (attrname == "System.Reflection.AssemblyFlagsAttribute") {
610 data = customBuilder.Data;
612 flags = (uint)data [pos];
613 flags |= ((uint)data [pos + 1]) << 8;
614 flags |= ((uint)data [pos + 2]) << 16;
615 flags |= ((uint)data [pos + 3]) << 24;
617 } else if (attrname == "System.Reflection.AssemblyDelaySignAttribute") {
618 data = customBuilder.Data;
620 delay_sign = data [2] != 0;
622 if (cattrs != null) {
623 CustomAttributeBuilder[] new_array = new CustomAttributeBuilder [cattrs.Length + 1];
624 cattrs.CopyTo (new_array, 0);
625 new_array [cattrs.Length] = customBuilder;
628 cattrs = new CustomAttributeBuilder [1];
629 cattrs [0] = customBuilder;
632 public void SetCustomAttribute ( ConstructorInfo con, byte[] binaryAttribute) {
634 throw new ArgumentNullException ("con");
635 if (binaryAttribute == null)
636 throw new ArgumentNullException ("binaryAttribute");
638 SetCustomAttribute (new CustomAttributeBuilder (con, binaryAttribute));
641 public void SetCorlibTypeBuilders (Type corlib_object_type, Type corlib_value_type, Type corlib_enum_type) {
642 this.corlib_object_type = corlib_object_type;
643 this.corlib_value_type = corlib_value_type;
644 this.corlib_enum_type = corlib_enum_type;
647 public void SetCorlibTypeBuilders (Type corlib_object_type, Type corlib_value_type, Type corlib_enum_type, Type corlib_void_type)
649 SetCorlibTypeBuilders (corlib_object_type, corlib_value_type, corlib_enum_type);
650 this.corlib_void_type = corlib_void_type;
653 private Exception not_supported () {
654 // Strange message but this is what MS.NET prints...
655 return new NotSupportedException ("The invoked member is not supported in a dynamic module.");
658 private void check_name_and_filename (string name, string fileName,
659 bool fileNeedsToExists) {
661 throw new ArgumentNullException ("name");
662 if (fileName == null)
663 throw new ArgumentNullException ("fileName");
665 throw new ArgumentException ("name cannot be empty", "name");
667 throw new ArgumentException ("fileName cannot be empty", "fileName");
668 if (Path.GetFileName (fileName) != fileName)
669 throw new ArgumentException ("fileName '" + fileName + "' must not include a path.");
671 // Resource files are created/searched under the assembly storage
673 string fullFileName = fileName;
675 fullFileName = Path.Combine (dir, fileName);
677 if (fileNeedsToExists && !File.Exists (fullFileName))
678 throw new FileNotFoundException ("Could not find file '" + fileName + "'");
680 if (resources != null) {
681 for (int i = 0; i < resources.Length; ++i) {
682 if (resources [i].filename == fullFileName)
683 throw new ArgumentException ("Duplicate file name '" + fileName + "'");
684 if (resources [i].name == name)
685 throw new ArgumentException ("Duplicate name '" + name + "'");
689 if (modules != null) {
690 for (int i = 0; i < modules.Length; ++i) {
691 // Use fileName instead of fullFileName here
692 if (!modules [i].IsTransient () && (modules [i].FileName == fileName))
693 throw new ArgumentException ("Duplicate file name '" + fileName + "'");
694 if (modules [i].Name == name)
695 throw new ArgumentException ("Duplicate name '" + name + "'");
700 private String create_assembly_version (String version) {
701 String[] parts = version.Split ('.');
702 int[] ver = new int [4] { 0, 0, 0, 0 };
704 if ((parts.Length < 0) || (parts.Length > 4))
705 throw new ArgumentException ("The version specified '" + version + "' is invalid");
707 for (int i = 0; i < parts.Length; ++i) {
708 if (parts [i] == "*") {
709 DateTime now = DateTime.Now;
712 ver [2] = (now - new DateTime (2000, 1, 1)).Days;
713 if (parts.Length == 3)
714 ver [3] = (now.Second + (now.Minute * 60) + (now.Hour * 3600)) / 2;
718 ver [3] = (now.Second + (now.Minute * 60) + (now.Hour * 3600)) / 2;
720 throw new ArgumentException ("The version specified '" + version + "' is invalid");
724 ver [i] = Int32.Parse (parts [i]);
726 catch (FormatException) {
727 throw new ArgumentException ("The version specified '" + version + "' is invalid");
732 return ver [0] + "." + ver [1] + "." + ver [2] + "." + ver [3];