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;
44 using System.Security.Cryptography;
45 using System.Security.Permissions;
48 using Mono.Security.Cryptography;
50 namespace System.Reflection.Emit
52 internal enum NativeResourceType
60 internal struct RefEmitPermissionSet {
61 public SecurityAction action;
64 public RefEmitPermissionSet (SecurityAction action, string pset) {
70 internal struct MonoResource {
73 public string filename;
74 public ResourceAttributes attrs;
79 internal struct MonoWin32Resource {
85 public MonoWin32Resource (int res_type, int res_id, int lang_id, byte[] data) {
86 this.res_type = res_type;
88 this.lang_id = lang_id;
94 [ComDefaultInterface (typeof (_AssemblyBuilder))]
95 [ClassInterface (ClassInterfaceType.None)]
96 public sealed class AssemblyBuilder : Assembly, _AssemblyBuilder {
97 #pragma warning disable 169, 414
98 #region Sync with object-internals.h
99 private UIntPtr dynamic_assembly; /* GC-tracked */
100 private MethodInfo entry_point;
101 private ModuleBuilder[] modules;
104 private CustomAttributeBuilder[] cattrs;
105 private MonoResource[] resources;
111 PEFileKinds pekind = PEFileKinds.Dll;
114 Module[] loaded_modules;
115 MonoWin32Resource[] win32_resources;
116 private RefEmitPermissionSet[] permissions_minimum;
117 private RefEmitPermissionSet[] permissions_optional;
118 private RefEmitPermissionSet[] permissions_refused;
119 PortableExecutableKinds peKind;
120 ImageFileMachine machine;
121 bool corlib_internal;
122 Type[] type_forwarders;
125 #pragma warning restore 169, 414
127 internal Type corlib_object_type = typeof (System.Object);
128 internal Type corlib_value_type = typeof (System.ValueType);
129 internal Type corlib_enum_type = typeof (System.Enum);
130 internal Type corlib_void_type = typeof (void);
131 ArrayList resource_writers = null;
132 Win32VersionResource version_res;
135 private Mono.Security.StrongName sn;
136 NativeResourceType native_resource;
137 readonly bool is_compiler_context;
138 string versioninfo_culture;
140 [MethodImplAttribute(MethodImplOptions.InternalCall)]
141 private static extern void basic_init (AssemblyBuilder ab);
143 /* Keep this in sync with codegen.cs in mcs */
144 private const AssemblyBuilderAccess COMPILER_ACCESS = (AssemblyBuilderAccess) 0x800;
146 internal AssemblyBuilder (AssemblyName n, string directory, AssemblyBuilderAccess access, bool corlib_internal)
148 is_compiler_context = (access & COMPILER_ACCESS) != 0;
150 // remove Mono specific flag to allow enum check to pass
151 access &= ~COMPILER_ACCESS;
153 #if NET_2_1 && !MONOTOUCH
154 // only "Run" is supported by Silverlight
155 // however SMCS requires more than this but runs outside the CoreCLR sandbox
156 if (SecurityManager.SecurityEnabled && (access != AssemblyBuilderAccess.Run))
157 throw new ArgumentException ("access");
160 if (!Enum.IsDefined (typeof (AssemblyBuilderAccess), access))
161 throw new ArgumentException (string.Format (CultureInfo.InvariantCulture,
162 "Argument value {0} is not valid.", (int) access),
166 if ((access & AssemblyBuilderAccess.RunAndCollect) == AssemblyBuilderAccess.RunAndCollect)
167 throw new NotSupportedException ("RunAndCollect not yet supported.");
171 this.access = (uint)access;
172 flags = (uint) n.Flags;
174 // don't call GetCurrentDirectory for Run-only builders (CAS may not like that)
175 if (IsSave && (directory == null || directory.Length == 0)) {
176 dir = Directory.GetCurrentDirectory ();
181 /* Set defaults from n */
182 if (n.CultureInfo != null) {
183 culture = n.CultureInfo.Name;
184 versioninfo_culture = n.CultureInfo.Name;
186 Version v = n.Version;
188 version = v.ToString ();
191 if (n.KeyPair != null) {
192 // full keypair is available (for signing)
193 sn = n.KeyPair.StrongName ();
195 // public key is available (for delay-signing)
196 byte[] pk = n.GetPublicKey ();
197 if ((pk != null) && (pk.Length > 0)) {
198 sn = new Mono.Security.StrongName (pk);
203 flags |= (uint) AssemblyNameFlags.PublicKey;
205 this.corlib_internal = corlib_internal;
207 this.pktoken = new byte[sn.PublicKeyToken.Length * 2];
209 foreach (byte pkb in sn.PublicKeyToken) {
210 string part = pkb.ToString("x2");
211 this.pktoken[pkti++] = (byte)part[0];
212 this.pktoken[pkti++] = (byte)part[1];
219 public override string CodeBase {
221 throw not_supported ();
225 public override MethodInfo EntryPoint {
231 public override string Location {
233 throw not_supported ();
237 /* This is to keep signature compatibility with MS.NET */
238 public override string ImageRuntimeVersion {
240 return base.ImageRuntimeVersion;
245 public override bool ReflectionOnly {
246 get { return base.ReflectionOnly; }
249 public void AddResourceFile (string name, string fileName)
251 AddResourceFile (name, fileName, ResourceAttributes.Public);
254 public void AddResourceFile (string name, string fileName, ResourceAttributes attribute)
256 AddResourceFile (name, fileName, attribute, true);
259 private void AddResourceFile (string name, string fileName, ResourceAttributes attribute, bool fileNeedsToExists)
261 check_name_and_filename (name, fileName, fileNeedsToExists);
263 // Resource files are created/searched under the assembly storage
266 fileName = Path.Combine (dir, fileName);
268 if (resources != null) {
269 MonoResource[] new_r = new MonoResource [resources.Length + 1];
270 System.Array.Copy(resources, new_r, resources.Length);
273 resources = new MonoResource [1];
275 int p = resources.Length - 1;
276 resources [p].name = name;
277 resources [p].filename = fileName;
278 resources [p].attrs = attribute;
282 /// Don't change the method name and parameters order. It is used by mcs
284 internal void AddPermissionRequests (PermissionSet required, PermissionSet optional, PermissionSet refused)
288 throw new InvalidOperationException ("Assembly was already saved.");
290 // required for base Assembly class (so the permissions
291 // can be used even if the assembly isn't saved to disk)
293 _optional = optional;
296 // required to reuse AddDeclarativeSecurity support
297 // already present in the runtime
298 if (required != null) {
299 permissions_minimum = new RefEmitPermissionSet [1];
300 permissions_minimum [0] = new RefEmitPermissionSet (
301 SecurityAction.RequestMinimum, required.ToXml ().ToString ());
303 if (optional != null) {
304 permissions_optional = new RefEmitPermissionSet [1];
305 permissions_optional [0] = new RefEmitPermissionSet (
306 SecurityAction.RequestOptional, optional.ToXml ().ToString ());
308 if (refused != null) {
309 permissions_refused = new RefEmitPermissionSet [1];
310 permissions_refused [0] = new RefEmitPermissionSet (
311 SecurityAction.RequestRefuse, refused.ToXml ().ToString ());
316 internal void EmbedResourceFile (string name, string fileName)
318 EmbedResourceFile (name, fileName, ResourceAttributes.Public);
321 internal void EmbedResourceFile (string name, string fileName, ResourceAttributes attribute)
323 if (resources != null) {
324 MonoResource[] new_r = new MonoResource [resources.Length + 1];
325 System.Array.Copy(resources, new_r, resources.Length);
328 resources = new MonoResource [1];
330 int p = resources.Length - 1;
331 resources [p].name = name;
332 resources [p].attrs = attribute;
334 FileStream s = new FileStream (fileName, FileMode.Open, FileAccess.Read);
336 resources [p].data = new byte [len];
337 s.Read (resources [p].data, 0, (int)len);
344 internal void EmbedResource (string name, byte[] blob, ResourceAttributes attribute)
346 if (resources != null) {
347 MonoResource[] new_r = new MonoResource [resources.Length + 1];
348 System.Array.Copy(resources, new_r, resources.Length);
351 resources = new MonoResource [1];
353 int p = resources.Length - 1;
354 resources [p].name = name;
355 resources [p].attrs = attribute;
356 resources [p].data = blob;
359 internal void AddTypeForwarder (Type t) {
361 throw new ArgumentNullException ("t");
363 if (type_forwarders == null) {
364 type_forwarders = new Type [1] { t };
366 Type[] arr = new Type [type_forwarders.Length + 1];
367 Array.Copy (type_forwarders, arr, type_forwarders.Length);
368 arr [type_forwarders.Length] = t;
369 type_forwarders = arr;
373 public ModuleBuilder DefineDynamicModule (string name)
375 return DefineDynamicModule (name, name, false, true);
378 public ModuleBuilder DefineDynamicModule (string name, bool emitSymbolInfo)
380 return DefineDynamicModule (name, name, emitSymbolInfo, true);
383 public ModuleBuilder DefineDynamicModule(string name, string fileName)
385 return DefineDynamicModule (name, fileName, false, false);
388 public ModuleBuilder DefineDynamicModule (string name, string fileName,
391 return DefineDynamicModule (name, fileName, emitSymbolInfo, false);
394 private ModuleBuilder DefineDynamicModule (string name, string fileName, bool emitSymbolInfo, bool transient)
396 check_name_and_filename (name, fileName, false);
399 if (Path.GetExtension (fileName) == String.Empty)
400 throw new ArgumentException ("Module file name '" + fileName + "' must have file extension.");
402 throw new NotSupportedException ("Persistable modules are not supported in a dynamic assembly created with AssemblyBuilderAccess.Run");
404 throw new InvalidOperationException ("Assembly was already saved.");
407 ModuleBuilder r = new ModuleBuilder (this, name, fileName, emitSymbolInfo, transient);
409 if ((modules != null) && is_module_only)
410 throw new InvalidOperationException ("A module-only assembly can only contain one module.");
412 if (modules != null) {
413 ModuleBuilder[] new_modules = new ModuleBuilder [modules.Length + 1];
414 System.Array.Copy(modules, new_modules, modules.Length);
415 modules = new_modules;
417 modules = new ModuleBuilder [1];
419 modules [modules.Length - 1] = r;
423 [MethodImplAttribute(MethodImplOptions.InternalCall)]
424 private extern Module InternalAddModule (string fileName);
427 * Mono extension to support /addmodule in mcs.
429 internal Module AddModule (string fileName)
431 if (fileName == null)
432 throw new ArgumentNullException (fileName);
434 Module m = InternalAddModule (fileName);
436 if (loaded_modules != null) {
437 Module[] new_modules = new Module [loaded_modules.Length + 1];
438 System.Array.Copy (loaded_modules, new_modules, loaded_modules.Length);
439 loaded_modules = new_modules;
441 loaded_modules = new Module [1];
443 loaded_modules [loaded_modules.Length - 1] = m;
448 public IResourceWriter DefineResource (string name, string description, string fileName)
450 return DefineResource (name, description, fileName, ResourceAttributes.Public);
453 public IResourceWriter DefineResource (string name, string description,
454 string fileName, ResourceAttributes attribute)
456 IResourceWriter writer;
458 // description seems to be ignored
459 AddResourceFile (name, fileName, attribute, false);
460 writer = new ResourceWriter (fileName);
461 if (resource_writers == null)
462 resource_writers = new ArrayList ();
463 resource_writers.Add (writer);
467 private void AddUnmanagedResource (Win32Resource res) {
468 MemoryStream ms = new MemoryStream ();
471 if (win32_resources != null) {
472 MonoWin32Resource[] new_res = new MonoWin32Resource [win32_resources.Length + 1];
473 System.Array.Copy (win32_resources, new_res, win32_resources.Length);
474 win32_resources = new_res;
477 win32_resources = new MonoWin32Resource [1];
479 win32_resources [win32_resources.Length - 1] = new MonoWin32Resource (res.Type.Id, res.Name.Id, res.Language, ms.ToArray ());
482 [MonoTODO ("Not currently implemenented")]
483 public void DefineUnmanagedResource (byte[] resource)
485 if (resource == null)
486 throw new ArgumentNullException ("resource");
487 if (native_resource != NativeResourceType.None)
488 throw new ArgumentException ("Native resource has already been defined.");
490 // avoid definition of more than one unmanaged resource
491 native_resource = NativeResourceType.Unmanaged;
494 * The format of the argument byte array is not documented
495 * so this method is impossible to implement.
498 throw new NotImplementedException ();
501 public void DefineUnmanagedResource (string resourceFileName)
503 if (resourceFileName == null)
504 throw new ArgumentNullException ("resourceFileName");
505 if (resourceFileName.Length == 0)
506 throw new ArgumentException ("resourceFileName");
507 if (!File.Exists (resourceFileName) || Directory.Exists (resourceFileName))
508 throw new FileNotFoundException ("File '" + resourceFileName + "' does not exists or is a directory.");
509 if (native_resource != NativeResourceType.None)
510 throw new ArgumentException ("Native resource has already been defined.");
512 // avoid definition of more than one unmanaged resource
513 native_resource = NativeResourceType.Unmanaged;
515 using (FileStream fs = new FileStream (resourceFileName, FileMode.Open, FileAccess.Read)) {
516 Win32ResFileReader reader = new Win32ResFileReader (fs);
518 foreach (Win32EncodedResource res in reader.ReadResources ()) {
519 if (res.Name.IsName || res.Type.IsName)
520 throw new InvalidOperationException ("resource files with named resources or non-default resource types are not supported.");
522 AddUnmanagedResource (res);
527 public void DefineVersionInfoResource ()
529 if (native_resource != NativeResourceType.None)
530 throw new ArgumentException ("Native resource has already been defined.");
532 // avoid definition of more than one unmanaged resource
533 native_resource = NativeResourceType.Assembly;
535 version_res = new Win32VersionResource (1, 0, IsCompilerContext);
538 public void DefineVersionInfoResource (string product, string productVersion,
539 string company, string copyright, string trademark)
541 if (native_resource != NativeResourceType.None)
542 throw new ArgumentException ("Native resource has already been defined.");
544 // avoid definition of more than one unmanaged resource
545 native_resource = NativeResourceType.Explicit;
548 * We can only create the resource later, when the file name and
549 * the binary version is known.
552 version_res = new Win32VersionResource (1, 0, false);
553 version_res.ProductName = product != null ? product : " ";
554 version_res.ProductVersion = productVersion != null ? productVersion : " ";
555 version_res.CompanyName = company != null ? company : " ";
556 version_res.LegalCopyright = copyright != null ? copyright : " ";
557 version_res.LegalTrademarks = trademark != null ? trademark : " ";
561 * Mono extension to support /win32icon in mcs
563 internal void DefineIconResource (string iconFileName)
565 if (iconFileName == null)
566 throw new ArgumentNullException ("iconFileName");
567 if (iconFileName.Length == 0)
568 throw new ArgumentException ("iconFileName");
569 if (!File.Exists (iconFileName) || Directory.Exists (iconFileName))
570 throw new FileNotFoundException ("File '" + iconFileName + "' does not exists or is a directory.");
572 using (FileStream fs = new FileStream (iconFileName, FileMode.Open, FileAccess.Read)) {
573 Win32IconFileReader reader = new Win32IconFileReader (fs);
575 ICONDIRENTRY[] entries = reader.ReadIcons ();
577 Win32IconResource[] icons = new Win32IconResource [entries.Length];
578 for (int i = 0; i < entries.Length; ++i) {
579 icons [i] = new Win32IconResource (i + 1, 0, entries [i]);
580 AddUnmanagedResource (icons [i]);
583 Win32GroupIconResource group = new Win32GroupIconResource (1, 0, icons);
584 AddUnmanagedResource (group);
588 private void DefineVersionInfoResourceImpl (string fileName)
590 if (versioninfo_culture != null)
591 version_res.FileLanguage = new CultureInfo (versioninfo_culture).LCID;
592 version_res.Version = version == null ? "0.0.0.0" : version;
594 if (cattrs != null) {
595 switch (native_resource) {
596 case NativeResourceType.Assembly:
597 foreach (CustomAttributeBuilder cb in cattrs) {
598 string attrname = cb.Ctor.ReflectedType.FullName;
600 if (attrname == "System.Reflection.AssemblyProductAttribute")
601 version_res.ProductName = cb.string_arg ();
602 else if (attrname == "System.Reflection.AssemblyCompanyAttribute")
603 version_res.CompanyName = cb.string_arg ();
604 else if (attrname == "System.Reflection.AssemblyCopyrightAttribute")
605 version_res.LegalCopyright = cb.string_arg ();
606 else if (attrname == "System.Reflection.AssemblyTrademarkAttribute")
607 version_res.LegalTrademarks = cb.string_arg ();
608 else if (attrname == "System.Reflection.AssemblyCultureAttribute") {
609 if (!IsCompilerContext)
610 version_res.FileLanguage = new CultureInfo (cb.string_arg ()).LCID;
611 } else if (attrname == "System.Reflection.AssemblyFileVersionAttribute") {
612 string fileversion = cb.string_arg ();
613 if (!IsCompilerContext || fileversion != null && fileversion.Length != 0)
614 version_res.FileVersion = fileversion;
615 } else if (attrname == "System.Reflection.AssemblyInformationalVersionAttribute")
616 version_res.ProductVersion = cb.string_arg ();
617 else if (attrname == "System.Reflection.AssemblyTitleAttribute")
618 version_res.FileDescription = cb.string_arg ();
619 else if (attrname == "System.Reflection.AssemblyDescriptionAttribute")
620 version_res.Comments = cb.string_arg ();
623 case NativeResourceType.Explicit:
624 foreach (CustomAttributeBuilder cb in cattrs) {
625 string attrname = cb.Ctor.ReflectedType.FullName;
627 if (attrname == "System.Reflection.AssemblyCultureAttribute") {
628 if (!IsCompilerContext)
629 version_res.FileLanguage = new CultureInfo (cb.string_arg ()).LCID;
630 } else if (attrname == "System.Reflection.AssemblyDescriptionAttribute")
631 version_res.Comments = cb.string_arg ();
637 version_res.OriginalFilename = fileName;
639 if (IsCompilerContext) {
640 version_res.InternalName = fileName;
641 if (version_res.ProductVersion.Trim ().Length == 0)
642 version_res.ProductVersion = version_res.FileVersion;
644 version_res.InternalName = Path.GetFileNameWithoutExtension (fileName);
647 AddUnmanagedResource (version_res);
650 public ModuleBuilder GetDynamicModule (string name)
653 throw new ArgumentNullException ("name");
654 if (name.Length == 0)
655 throw new ArgumentException ("Empty name is not legal.", "name");
658 for (int i = 0; i < modules.Length; ++i)
659 if (modules [i].name == name)
664 public override Type[] GetExportedTypes ()
666 throw not_supported ();
669 public override FileStream GetFile (string name)
671 throw not_supported ();
674 public override FileStream[] GetFiles(bool getResourceModules) {
675 throw not_supported ();
678 internal override Module[] GetModulesInternal () {
680 return new Module [0];
682 return (Module[])modules.Clone ();
685 internal override Type[] GetTypes (bool exportedOnly) {
687 if (modules != null) {
688 for (int i = 0; i < modules.Length; ++i) {
689 Type[] types = modules [i].GetTypes ();
693 Type[] tmp = new Type [res.Length + types.Length];
694 Array.Copy (res, 0, tmp, 0, res.Length);
695 Array.Copy (types, 0, tmp, res.Length, types.Length);
699 if (loaded_modules != null) {
700 for (int i = 0; i < loaded_modules.Length; ++i) {
701 Type[] types = loaded_modules [i].GetTypes ();
705 Type[] tmp = new Type [res.Length + types.Length];
706 Array.Copy (res, 0, tmp, 0, res.Length);
707 Array.Copy (types, 0, tmp, res.Length, types.Length);
712 return res == null ? Type.EmptyTypes : res;
715 public override ManifestResourceInfo GetManifestResourceInfo(string resourceName) {
716 throw not_supported ();
719 public override string[] GetManifestResourceNames() {
720 throw not_supported ();
723 public override Stream GetManifestResourceStream(string name) {
724 throw not_supported ();
726 public override Stream GetManifestResourceStream(Type type, string name) {
727 throw not_supported ();
731 * This is set when the the AssemblyBuilder is created by (g)mcs
734 internal bool IsCompilerContext
736 get { return is_compiler_context; }
739 internal bool IsSave {
741 return access != (uint)AssemblyBuilderAccess.Run;
745 internal bool IsRun {
747 return access == (uint)AssemblyBuilderAccess.Run || access == (uint)AssemblyBuilderAccess.RunAndSave
749 || access == (uint)AssemblyBuilderAccess.RunAndCollect
756 internal string AssemblyDir {
763 * Mono extension. If this is set, the assembly can only contain one
764 * module, access should be Save, and the saved image will not contain an
767 internal bool IsModuleOnly {
769 return is_module_only;
772 is_module_only = value;
776 ModuleBuilder manifest_module;
779 // MS.NET seems to return a ModuleBuilder when GetManifestModule () is called
780 // on an assemblybuilder.
782 internal override Module GetManifestModule () {
783 if (manifest_module == null)
784 manifest_module = DefineDynamicModule ("Default Dynamic Module");
785 return manifest_module;
788 [MonoLimitation ("No support for PE32+ assemblies for AMD64 and IA64")]
790 void Save (string assemblyFileName, PortableExecutableKinds portableExecutableKind, ImageFileMachine imageFileMachine)
792 this.peKind = portableExecutableKind;
793 this.machine = imageFileMachine;
795 if ((peKind & PortableExecutableKinds.PE32Plus) != 0 || (peKind & PortableExecutableKinds.Unmanaged32Bit) != 0)
796 throw new NotImplementedException (peKind.ToString ());
797 if (machine == ImageFileMachine.IA64 || machine == ImageFileMachine.AMD64)
798 throw new NotImplementedException (machine.ToString ());
800 if (resource_writers != null) {
801 foreach (IResourceWriter writer in resource_writers) {
807 // Create a main module if not already created
808 ModuleBuilder mainModule = null;
809 if (modules != null) {
810 foreach (ModuleBuilder module in modules)
811 if (module.FullyQualifiedName == assemblyFileName)
814 if (mainModule == null)
815 mainModule = DefineDynamicModule ("RefEmit_OnDiskManifestModule", assemblyFileName);
818 mainModule.IsMain = true;
821 * Create a new entry point if the one specified
822 * by the user is in another module.
824 if ((entry_point != null) && entry_point.DeclaringType.Module != mainModule) {
826 if (entry_point.GetParameters ().Length == 1)
827 paramTypes = new Type [] { typeof (string) };
829 paramTypes = Type.EmptyTypes;
831 MethodBuilder mb = mainModule.DefineGlobalMethod ("__EntryPoint$", MethodAttributes.Static|MethodAttributes.PrivateScope, entry_point.ReturnType, paramTypes);
832 ILGenerator ilgen = mb.GetILGenerator ();
833 if (paramTypes.Length == 1)
834 ilgen.Emit (OpCodes.Ldarg_0);
835 ilgen.Emit (OpCodes.Tailcall);
836 ilgen.Emit (OpCodes.Call, entry_point);
837 ilgen.Emit (OpCodes.Ret);
842 if (version_res != null)
843 DefineVersionInfoResourceImpl (assemblyFileName);
846 // runtime needs to value to embed it into the assembly
847 public_key = sn.PublicKey;
850 foreach (ModuleBuilder module in modules)
851 if (module != mainModule)
854 // Write out the main module at the end, because it needs to
855 // contain the hash of the other modules
858 if ((sn != null) && (sn.CanSign)) {
859 sn.Sign (System.IO.Path.Combine (this.AssemblyDir, assemblyFileName));
865 public void Save (string assemblyFileName)
867 Save (assemblyFileName, PortableExecutableKinds.ILOnly, ImageFileMachine.I386);
870 public void SetEntryPoint (MethodInfo entryMethod)
872 SetEntryPoint (entryMethod, PEFileKinds.ConsoleApplication);
875 public void SetEntryPoint (MethodInfo entryMethod, PEFileKinds fileKind)
877 if (entryMethod == null)
878 throw new ArgumentNullException ("entryMethod");
879 if (entryMethod.DeclaringType.Assembly != this)
880 throw new InvalidOperationException ("Entry method is not defined in the same assembly.");
882 entry_point = entryMethod;
886 public void SetCustomAttribute( CustomAttributeBuilder customBuilder)
888 if (customBuilder == null)
889 throw new ArgumentNullException ("customBuilder");
891 if (IsCompilerContext) {
892 string attrname = customBuilder.Ctor.ReflectedType.FullName;
896 if (attrname == "System.Reflection.AssemblyVersionAttribute") {
897 version = create_assembly_version (customBuilder.string_arg ());
899 } else if (attrname == "System.Reflection.AssemblyCultureAttribute") {
900 culture = GetCultureString (customBuilder.string_arg ());
901 } else if (attrname == "System.Reflection.AssemblyAlgorithmIdAttribute") {
902 data = customBuilder.Data;
904 algid = (uint) data [pos];
905 algid |= ((uint) data [pos + 1]) << 8;
906 algid |= ((uint) data [pos + 2]) << 16;
907 algid |= ((uint) data [pos + 3]) << 24;
908 } else if (attrname == "System.Reflection.AssemblyFlagsAttribute") {
909 data = customBuilder.Data;
911 flags |= (uint) data [pos];
912 flags |= ((uint) data [pos + 1]) << 8;
913 flags |= ((uint) data [pos + 2]) << 16;
914 flags |= ((uint) data [pos + 3]) << 24;
916 // ignore PublicKey flag if assembly is not strongnamed
918 flags &= ~(uint) AssemblyNameFlags.PublicKey;
922 if (cattrs != null) {
923 CustomAttributeBuilder[] new_array = new CustomAttributeBuilder [cattrs.Length + 1];
924 cattrs.CopyTo (new_array, 0);
925 new_array [cattrs.Length] = customBuilder;
928 cattrs = new CustomAttributeBuilder [1];
929 cattrs [0] = customBuilder;
934 public void SetCustomAttribute ( ConstructorInfo con, byte[] binaryAttribute) {
936 throw new ArgumentNullException ("con");
937 if (binaryAttribute == null)
938 throw new ArgumentNullException ("binaryAttribute");
940 SetCustomAttribute (new CustomAttributeBuilder (con, binaryAttribute));
943 internal void SetCorlibTypeBuilders (Type corlib_object_type, Type corlib_value_type, Type corlib_enum_type) {
944 this.corlib_object_type = corlib_object_type;
945 this.corlib_value_type = corlib_value_type;
946 this.corlib_enum_type = corlib_enum_type;
949 internal void SetCorlibTypeBuilders (Type corlib_object_type, Type corlib_value_type, Type corlib_enum_type, Type corlib_void_type)
951 SetCorlibTypeBuilders (corlib_object_type, corlib_value_type, corlib_enum_type);
952 this.corlib_void_type = corlib_void_type;
955 private Exception not_supported () {
956 // Strange message but this is what MS.NET prints...
957 return new NotSupportedException ("The invoked member is not supported in a dynamic module.");
960 private void check_name_and_filename (string name, string fileName,
961 bool fileNeedsToExists) {
963 throw new ArgumentNullException ("name");
964 if (fileName == null)
965 throw new ArgumentNullException ("fileName");
966 if (name.Length == 0)
967 throw new ArgumentException ("Empty name is not legal.", "name");
968 if (fileName.Length == 0)
969 throw new ArgumentException ("Empty file name is not legal.", "fileName");
970 if (Path.GetFileName (fileName) != fileName)
971 throw new ArgumentException ("fileName '" + fileName + "' must not include a path.", "fileName");
973 // Resource files are created/searched under the assembly storage
975 string fullFileName = fileName;
977 fullFileName = Path.Combine (dir, fileName);
979 if (fileNeedsToExists && !File.Exists (fullFileName))
980 throw new FileNotFoundException ("Could not find file '" + fileName + "'");
982 if (resources != null) {
983 for (int i = 0; i < resources.Length; ++i) {
984 if (resources [i].filename == fullFileName)
985 throw new ArgumentException ("Duplicate file name '" + fileName + "'");
986 if (resources [i].name == name)
987 throw new ArgumentException ("Duplicate name '" + name + "'");
991 if (modules != null) {
992 for (int i = 0; i < modules.Length; ++i) {
993 // Use fileName instead of fullFileName here
994 if (!modules [i].IsTransient () && (modules [i].FileName == fileName))
995 throw new ArgumentException ("Duplicate file name '" + fileName + "'");
996 if (modules [i].Name == name)
997 throw new ArgumentException ("Duplicate name '" + name + "'");
1002 private String create_assembly_version (String version) {
1003 String[] parts = version.Split ('.');
1004 int[] ver = new int [4] { 0, 0, 0, 0 };
1006 if ((parts.Length < 0) || (parts.Length > 4))
1007 throw new ArgumentException ("The version specified '" + version + "' is invalid");
1009 for (int i = 0; i < parts.Length; ++i) {
1010 if (parts [i] == "*") {
1011 DateTime now = DateTime.Now;
1014 ver [2] = (now - new DateTime (2000, 1, 1)).Days;
1015 if (parts.Length == 3)
1016 ver [3] = (now.Second + (now.Minute * 60) + (now.Hour * 3600)) / 2;
1020 ver [3] = (now.Second + (now.Minute * 60) + (now.Hour * 3600)) / 2;
1022 throw new ArgumentException ("The version specified '" + version + "' is invalid");
1026 ver [i] = Int32.Parse (parts [i]);
1028 catch (FormatException) {
1029 throw new ArgumentException ("The version specified '" + version + "' is invalid");
1034 return ver [0] + "." + ver [1] + "." + ver [2] + "." + ver [3];
1037 private string GetCultureString (string str)
1039 return (str == "neutral" ? String.Empty : str);
1042 internal override AssemblyName UnprotectedGetName ()
1044 AssemblyName an = base.UnprotectedGetName ();
1046 an.SetPublicKey (sn.PublicKey);
1047 an.SetPublicKeyToken (sn.PublicKeyToken);
1052 void _AssemblyBuilder.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
1054 throw new NotImplementedException ();
1057 void _AssemblyBuilder.GetTypeInfo (uint iTInfo, uint lcid, IntPtr ppTInfo)
1059 throw new NotImplementedException ();
1062 void _AssemblyBuilder.GetTypeInfoCount (out uint pcTInfo)
1064 throw new NotImplementedException ();
1067 void _AssemblyBuilder.Invoke (uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
1069 throw new NotImplementedException ();