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 ();
110 if (n.KeyPair != null) {
111 sn = n.KeyPair.StrongName ();
117 public override string CodeBase {
119 throw not_supported ();
123 public override MethodInfo EntryPoint {
129 public override string Location {
131 throw not_supported ();
136 /* This is to keep signature compatibility with MS.NET */
137 public override string ImageRuntimeVersion {
139 return base.ImageRuntimeVersion;
144 public void AddResourceFile (string name, string fileName)
146 AddResourceFile (name, fileName, ResourceAttributes.Public);
149 public void AddResourceFile (string name, string fileName, ResourceAttributes attribute)
151 AddResourceFile (name, fileName, attribute, true);
154 private void AddResourceFile (string name, string fileName, ResourceAttributes attribute, bool fileNeedsToExists)
156 check_name_and_filename (name, fileName, fileNeedsToExists);
158 // Resource files are created/searched under the assembly storage
161 fileName = Path.Combine (dir, fileName);
163 if (resources != null) {
164 MonoResource[] new_r = new MonoResource [resources.Length + 1];
165 System.Array.Copy(resources, new_r, resources.Length);
168 resources = new MonoResource [1];
170 int p = resources.Length - 1;
171 resources [p].name = name;
172 resources [p].filename = fileName;
173 resources [p].attrs = attribute;
176 public void EmbedResourceFile (string name, string fileName)
178 EmbedResourceFile (name, fileName, ResourceAttributes.Public);
181 public void EmbedResourceFile (string name, string fileName, ResourceAttributes attribute)
183 if (resources != null) {
184 MonoResource[] new_r = new MonoResource [resources.Length + 1];
185 System.Array.Copy(resources, new_r, resources.Length);
188 resources = new MonoResource [1];
190 int p = resources.Length - 1;
191 resources [p].name = name;
192 resources [p].attrs = attribute;
194 FileStream s = new FileStream (fileName, FileMode.Open, FileAccess.Read);
196 resources [p].data = new byte [len];
197 s.Read (resources [p].data, 0, (int)len);
204 internal void EmbedResource (string name, byte[] blob, 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;
216 resources [p].data = blob;
219 public ModuleBuilder DefineDynamicModule (string name)
221 return DefineDynamicModule (name, name, false, true);
224 public ModuleBuilder DefineDynamicModule (string name, bool emitSymbolInfo)
226 return DefineDynamicModule (name, name, emitSymbolInfo, true);
229 public ModuleBuilder DefineDynamicModule(string name, string fileName)
231 return DefineDynamicModule (name, fileName, false, false);
234 public ModuleBuilder DefineDynamicModule (string name, string fileName,
237 return DefineDynamicModule (name, fileName, emitSymbolInfo, false);
240 private ModuleBuilder DefineDynamicModule (string name, string fileName,
241 bool emitSymbolInfo, bool transient)
243 check_name_and_filename (name, fileName, false);
246 if (Path.GetExtension (fileName) == String.Empty)
247 throw new ArgumentException ("Module file name '" + fileName + "' must have file extension.");
249 throw new NotSupportedException ("Persistable modules are not supported in a dynamic assembly created with AssemblyBuilderAccess.Run");
251 throw new InvalidOperationException ("Assembly was already saved.");
254 ModuleBuilder r = new ModuleBuilder (this, name, fileName, emitSymbolInfo, transient);
256 if ((modules != null) && is_module_only)
257 throw new InvalidOperationException ("A module-only assembly can only contain one module.");
259 if (modules != null) {
260 ModuleBuilder[] new_modules = new ModuleBuilder [modules.Length + 1];
261 System.Array.Copy(modules, new_modules, modules.Length);
262 modules = new_modules;
264 modules = new ModuleBuilder [1];
266 modules [modules.Length - 1] = r;
270 [MethodImplAttribute(MethodImplOptions.InternalCall)]
271 private extern Module InternalAddModule (string fileName);
274 * Mono extension to support /addmodule in mcs.
276 internal Module AddModule (string fileName)
278 if (fileName == null)
279 throw new ArgumentNullException (fileName);
281 Module m = InternalAddModule (fileName);
283 if (loaded_modules != null) {
284 Module[] new_modules = new Module [loaded_modules.Length + 1];
285 System.Array.Copy (loaded_modules, new_modules, loaded_modules.Length);
286 loaded_modules = new_modules;
288 loaded_modules = new Module [1];
290 loaded_modules [loaded_modules.Length - 1] = m;
295 public IResourceWriter DefineResource (string name, string description, string fileName)
297 return DefineResource (name, description, fileName, ResourceAttributes.Public);
300 public IResourceWriter DefineResource (string name, string description,
301 string fileName, ResourceAttributes attribute)
303 IResourceWriter writer;
305 // description seems to be ignored
306 AddResourceFile (name, fileName, attribute, false);
307 writer = new ResourceWriter (fileName);
308 if (resource_writers == null)
309 resource_writers = new ArrayList ();
310 resource_writers.Add (writer);
314 private void AddUnmanagedResource (Win32Resource res) {
315 MemoryStream ms = new MemoryStream ();
318 if (win32_resources != null) {
319 MonoWin32Resource[] new_res = new MonoWin32Resource [win32_resources.Length + 1];
320 System.Array.Copy (win32_resources, new_res, win32_resources.Length);
321 win32_resources = new_res;
324 win32_resources = new MonoWin32Resource [1];
326 win32_resources [win32_resources.Length - 1] = new MonoWin32Resource (res.Type.Id, res.Name.Id, res.Language, ms.ToArray ());
330 public void DefineUnmanagedResource (byte[] resource)
332 if (resource == null)
333 throw new ArgumentNullException ("resource");
336 * The format of the argument byte array is not documented
337 * so this method is impossible to implement.
340 throw new NotImplementedException ();
343 public void DefineUnmanagedResource (string resourceFileName)
345 if (resourceFileName == null)
346 throw new ArgumentNullException ("resourceFileName");
347 if (resourceFileName == String.Empty)
348 throw new ArgumentException ("resourceFileName");
349 if (!File.Exists (resourceFileName) || Directory.Exists (resourceFileName))
350 throw new FileNotFoundException ("File '" + resourceFileName + "' does not exists or is a directory.");
352 using (FileStream fs = new FileStream (resourceFileName, FileMode.Open)) {
353 Win32ResFileReader reader = new Win32ResFileReader (fs);
355 foreach (Win32EncodedResource res in reader.ReadResources ()) {
356 if (res.Name.IsName || res.Type.IsName)
357 throw new InvalidOperationException ("resource files with named resources or non-default resource types are not supported.");
359 AddUnmanagedResource (res);
364 public void DefineVersionInfoResource ()
366 if (version_res != null)
367 throw new ArgumentException ("Native resource has already been defined.");
369 version_res = new Win32VersionResource (1, 0);
371 if (cattrs != null) {
372 foreach (CustomAttributeBuilder cb in cattrs) {
373 string attrname = cb.Ctor.ReflectedType.FullName;
375 if (attrname == "System.Reflection.AssemblyProductAttribute")
376 version_res.ProductName = cb.string_arg ();
377 else if (attrname == "System.Reflection.AssemblyCompanyAttribute")
378 version_res.CompanyName = cb.string_arg ();
379 else if (attrname == "System.Reflection.AssemblyCopyrightAttribute")
380 version_res.LegalCopyright = cb.string_arg ();
381 else if (attrname == "System.Reflection.AssemblyTrademarkAttribute")
382 version_res.LegalTrademarks = cb.string_arg ();
383 else if (attrname == "System.Reflection.AssemblyCultureAttribute")
384 version_res.FileLanguage = new CultureInfo (cb.string_arg ()).LCID;
385 else if (attrname == "System.Reflection.AssemblyFileVersionAttribute")
386 version_res.FileVersion = cb.string_arg ();
387 else if (attrname == "System.Reflection.AssemblyInformationalVersionAttribute")
388 version_res.ProductVersion = cb.string_arg ();
389 else if (attrname == "System.Reflection.AssemblyTitleAttribute")
390 version_res.FileDescription = cb.string_arg ();
391 else if (attrname == "System.Reflection.AssemblyDescriptionAttribute")
392 version_res.Comments = cb.string_arg ();
397 public void DefineVersionInfoResource (string product, string productVersion,
398 string company, string copyright, string trademark)
400 if (version_res != null)
401 throw new ArgumentException ("Native resource has already been defined.");
404 * We can only create the resource later, when the file name and
405 * the binary version is known.
408 version_res = new Win32VersionResource (1, 0);
409 version_res.ProductName = product;
410 version_res.ProductVersion = productVersion;
411 version_res.CompanyName = company;
412 version_res.LegalCopyright = copyright;
413 version_res.LegalTrademarks = trademark;
417 * Mono extension to support /win32icon in mcs
419 internal void DefineIconResource (string iconFileName)
421 if (iconFileName == null)
422 throw new ArgumentNullException ("iconFileName");
423 if (iconFileName == String.Empty)
424 throw new ArgumentException ("iconFileName");
425 if (!File.Exists (iconFileName) || Directory.Exists (iconFileName))
426 throw new FileNotFoundException ("File '" + iconFileName + "' does not exists or is a directory.");
428 using (FileStream fs = new FileStream (iconFileName, FileMode.Open)) {
429 Win32IconFileReader reader = new Win32IconFileReader (fs);
431 ICONDIRENTRY[] entries = reader.ReadIcons ();
433 Win32IconResource[] icons = new Win32IconResource [entries.Length];
434 for (int i = 0; i < entries.Length; ++i) {
435 icons [i] = new Win32IconResource (i + 1, 0, entries [i]);
436 AddUnmanagedResource (icons [i]);
439 Win32GroupIconResource group = new Win32GroupIconResource (1, 0, icons);
440 AddUnmanagedResource (group);
444 private void DefineVersionInfoResourceImpl (string fileName) {
446 if (version_res.FileVersion == "0.0.0.0")
447 version_res.FileVersion = version;
448 version_res.InternalName = Path.GetFileNameWithoutExtension (fileName);
449 version_res.OriginalFilename = fileName;
451 AddUnmanagedResource (version_res);
454 public ModuleBuilder GetDynamicModule (string name)
457 throw new ArgumentNullException ("name");
459 throw new ArgumentException ("Name can't be null");
462 for (int i = 0; i < modules.Length; ++i)
463 if (modules [i].name == name)
468 public override Type[] GetExportedTypes ()
470 throw not_supported ();
473 public override FileStream GetFile (string name)
475 throw not_supported ();
478 public override FileStream[] GetFiles() {
479 throw not_supported ();
482 public override FileStream[] GetFiles(bool getResourceModules) {
483 throw not_supported ();
486 public override ManifestResourceInfo GetManifestResourceInfo(string resourceName) {
487 throw not_supported ();
490 public override string[] GetManifestResourceNames() {
491 throw not_supported ();
494 public override Stream GetManifestResourceStream(string name) {
495 throw not_supported ();
497 public override Stream GetManifestResourceStream(Type type, string name) {
498 throw not_supported ();
501 internal bool IsSave {
503 return access != (uint)AssemblyBuilderAccess.Run;
507 internal string AssemblyDir {
514 * Mono extension. If this is set, the assembly can only contain one
515 * module, access should be Save, and the saved image will not contain an
518 internal bool IsModuleOnly {
520 return is_module_only;
523 is_module_only = value;
527 public void Save (string assemblyFileName)
529 if (resource_writers != null) {
530 foreach (IResourceWriter writer in resource_writers) {
536 // Create a main module if not already created
537 ModuleBuilder mainModule = null;
538 if (modules != null) {
539 foreach (ModuleBuilder module in modules)
540 if (module.FullyQualifiedName == assemblyFileName)
543 if (mainModule == null)
544 mainModule = DefineDynamicModule ("RefEmit_OnDiskManifestModule", assemblyFileName);
547 mainModule.IsMain = true;
550 * Create a new entry point if the one specified
551 * by the user is in another module.
553 if ((entry_point != null) && entry_point.DeclaringType.Module != mainModule) {
555 if (entry_point.GetParameters ().Length == 1)
556 paramTypes = new Type [] { typeof (string) };
558 paramTypes = new Type [0];
560 MethodBuilder mb = mainModule.DefineGlobalMethod ("__EntryPoint$", MethodAttributes.Static|MethodAttributes.PrivateScope, entry_point.ReturnType, paramTypes);
561 ILGenerator ilgen = mb.GetILGenerator ();
562 if (paramTypes.Length == 1)
563 ilgen.Emit (OpCodes.Ldarg_0);
564 ilgen.Emit (OpCodes.Tailcall);
565 ilgen.Emit (OpCodes.Call, entry_point);
566 ilgen.Emit (OpCodes.Ret);
571 if (version_res != null)
572 DefineVersionInfoResourceImpl (assemblyFileName);
575 // runtime needs to value to embed it into the assembly
576 public_key = sn.PublicKey;
579 foreach (ModuleBuilder module in modules)
580 if (module != mainModule)
583 // Write out the main module at the end, because it needs to
584 // contain the hash of the other modules
587 if ((sn != null) && (sn.CanSign)) {
588 sn.Sign (System.IO.Path.Combine (this.AssemblyDir, assemblyFileName));
594 public void SetEntryPoint (MethodInfo entryMethod)
596 SetEntryPoint (entryMethod, PEFileKinds.ConsoleApplication);
599 public void SetEntryPoint (MethodInfo entryMethod, PEFileKinds fileKind)
601 if (entryMethod == null)
602 throw new ArgumentNullException ("entryMethod");
603 if (entryMethod.DeclaringType.Assembly != this)
604 throw new InvalidOperationException ("Entry method is not defined in the same assembly.");
606 entry_point = entryMethod;
610 public void SetCustomAttribute( CustomAttributeBuilder customBuilder)
612 if (customBuilder == null)
613 throw new ArgumentNullException ("customBuilder");
615 string attrname = customBuilder.Ctor.ReflectedType.FullName;
619 if (attrname == "System.Reflection.AssemblyVersionAttribute") {
620 version = create_assembly_version (customBuilder.string_arg ());
622 } else if (attrname == "System.Reflection.AssemblyCultureAttribute") {
623 culture = customBuilder.string_arg ();
624 } else if (attrname == "System.Reflection.AssemblyAlgorithmIdAttribute") {
625 data = customBuilder.Data;
627 algid = (uint)data [pos];
628 algid |= ((uint)data [pos + 1]) << 8;
629 algid |= ((uint)data [pos + 2]) << 16;
630 algid |= ((uint)data [pos + 3]) << 24;
631 } else if (attrname == "System.Reflection.AssemblyFlagsAttribute") {
632 data = customBuilder.Data;
634 flags = (uint)data [pos];
635 flags |= ((uint)data [pos + 1]) << 8;
636 flags |= ((uint)data [pos + 2]) << 16;
637 flags |= ((uint)data [pos + 3]) << 24;
641 if (cattrs != null) {
642 CustomAttributeBuilder[] new_array = new CustomAttributeBuilder [cattrs.Length + 1];
643 cattrs.CopyTo (new_array, 0);
644 new_array [cattrs.Length] = customBuilder;
647 cattrs = new CustomAttributeBuilder [1];
648 cattrs [0] = customBuilder;
652 public void SetCustomAttribute ( ConstructorInfo con, byte[] binaryAttribute) {
654 throw new ArgumentNullException ("con");
655 if (binaryAttribute == null)
656 throw new ArgumentNullException ("binaryAttribute");
658 SetCustomAttribute (new CustomAttributeBuilder (con, binaryAttribute));
661 public void SetCorlibTypeBuilders (Type corlib_object_type, Type corlib_value_type, Type corlib_enum_type) {
662 this.corlib_object_type = corlib_object_type;
663 this.corlib_value_type = corlib_value_type;
664 this.corlib_enum_type = corlib_enum_type;
667 public void SetCorlibTypeBuilders (Type corlib_object_type, Type corlib_value_type, Type corlib_enum_type, Type corlib_void_type)
669 SetCorlibTypeBuilders (corlib_object_type, corlib_value_type, corlib_enum_type);
670 this.corlib_void_type = corlib_void_type;
673 private Exception not_supported () {
674 // Strange message but this is what MS.NET prints...
675 return new NotSupportedException ("The invoked member is not supported in a dynamic module.");
678 private void check_name_and_filename (string name, string fileName,
679 bool fileNeedsToExists) {
681 throw new ArgumentNullException ("name");
682 if (fileName == null)
683 throw new ArgumentNullException ("fileName");
685 throw new ArgumentException ("name cannot be empty", "name");
687 throw new ArgumentException ("fileName cannot be empty", "fileName");
688 if (Path.GetFileName (fileName) != fileName)
689 throw new ArgumentException ("fileName '" + fileName + "' must not include a path.");
691 // Resource files are created/searched under the assembly storage
693 string fullFileName = fileName;
695 fullFileName = Path.Combine (dir, fileName);
697 if (fileNeedsToExists && !File.Exists (fullFileName))
698 throw new FileNotFoundException ("Could not find file '" + fileName + "'");
700 if (resources != null) {
701 for (int i = 0; i < resources.Length; ++i) {
702 if (resources [i].filename == fullFileName)
703 throw new ArgumentException ("Duplicate file name '" + fileName + "'");
704 if (resources [i].name == name)
705 throw new ArgumentException ("Duplicate name '" + name + "'");
709 if (modules != null) {
710 for (int i = 0; i < modules.Length; ++i) {
711 // Use fileName instead of fullFileName here
712 if (!modules [i].IsTransient () && (modules [i].FileName == fileName))
713 throw new ArgumentException ("Duplicate file name '" + fileName + "'");
714 if (modules [i].Name == name)
715 throw new ArgumentException ("Duplicate name '" + name + "'");
720 private String create_assembly_version (String version) {
721 String[] parts = version.Split ('.');
722 int[] ver = new int [4] { 0, 0, 0, 0 };
724 if ((parts.Length < 0) || (parts.Length > 4))
725 throw new ArgumentException ("The version specified '" + version + "' is invalid");
727 for (int i = 0; i < parts.Length; ++i) {
728 if (parts [i] == "*") {
729 DateTime now = DateTime.Now;
732 ver [2] = (now - new DateTime (2000, 1, 1)).Days;
733 if (parts.Length == 3)
734 ver [3] = (now.Second + (now.Minute * 60) + (now.Hour * 3600)) / 2;
738 ver [3] = (now.Second + (now.Minute * 60) + (now.Hour * 3600)) / 2;
740 throw new ArgumentException ("The version specified '" + version + "' is invalid");
744 ver [i] = Int32.Parse (parts [i]);
746 catch (FormatException) {
747 throw new ArgumentException ("The version specified '" + version + "' is invalid");
752 return ver [0] + "." + ver [1] + "." + ver [2] + "." + ver [3];