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;
95 [ComDefaultInterface (typeof (_AssemblyBuilder))]
97 [ClassInterface (ClassInterfaceType.None)]
98 public sealed class AssemblyBuilder : Assembly, _AssemblyBuilder {
99 #pragma warning disable 169, 414
100 #region Sync with object-internals.h
101 private UIntPtr dynamic_assembly; /* GC-tracked */
102 private MethodInfo entry_point;
103 private ModuleBuilder[] modules;
106 private CustomAttributeBuilder[] cattrs;
107 private MonoResource[] resources;
113 PEFileKinds pekind = PEFileKinds.Dll;
116 Module[] loaded_modules;
117 MonoWin32Resource[] win32_resources;
118 private RefEmitPermissionSet[] permissions_minimum;
119 private RefEmitPermissionSet[] permissions_optional;
120 private RefEmitPermissionSet[] permissions_refused;
121 PortableExecutableKinds peKind;
122 ImageFileMachine machine;
123 bool corlib_internal;
124 Type[] type_forwarders;
126 #pragma warning restore 169, 414
128 internal Type corlib_object_type = typeof (System.Object);
129 internal Type corlib_value_type = typeof (System.ValueType);
130 internal Type corlib_enum_type = typeof (System.Enum);
131 internal Type corlib_void_type = typeof (void);
132 ArrayList resource_writers = null;
133 Win32VersionResource version_res;
136 private Mono.Security.StrongName sn;
137 NativeResourceType native_resource;
138 readonly bool is_compiler_context;
139 string versioninfo_culture;
141 [MethodImplAttribute(MethodImplOptions.InternalCall)]
142 private static extern void basic_init (AssemblyBuilder ab);
144 /* Keep this in sync with codegen.cs in mcs */
145 private const AssemblyBuilderAccess COMPILER_ACCESS = (AssemblyBuilderAccess) 0x800;
147 internal AssemblyBuilder (AssemblyName n, string directory, AssemblyBuilderAccess access, bool corlib_internal)
149 #if BOOTSTRAP_WITH_OLDLIB
150 is_compiler_context = true;
152 is_compiler_context = (access & COMPILER_ACCESS) != 0;
155 // remove Mono specific flag to allow enum check to pass
156 access &= ~COMPILER_ACCESS;
159 if (!Enum.IsDefined (typeof (AssemblyBuilderAccess), access))
160 throw new ArgumentException (string.Format (CultureInfo.InvariantCulture,
161 "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;
210 public override string CodeBase {
212 throw not_supported ();
216 public override MethodInfo EntryPoint {
222 public override string Location {
224 throw not_supported ();
229 /* This is to keep signature compatibility with MS.NET */
230 public override string ImageRuntimeVersion {
232 return base.ImageRuntimeVersion;
239 public override bool ReflectionOnly {
240 get { return base.ReflectionOnly; }
244 public void AddResourceFile (string name, string fileName)
246 AddResourceFile (name, fileName, ResourceAttributes.Public);
249 public void AddResourceFile (string name, string fileName, ResourceAttributes attribute)
251 AddResourceFile (name, fileName, attribute, true);
254 private void AddResourceFile (string name, string fileName, ResourceAttributes attribute, bool fileNeedsToExists)
256 check_name_and_filename (name, fileName, fileNeedsToExists);
258 // Resource files are created/searched under the assembly storage
261 fileName = Path.Combine (dir, fileName);
263 if (resources != null) {
264 MonoResource[] new_r = new MonoResource [resources.Length + 1];
265 System.Array.Copy(resources, new_r, resources.Length);
268 resources = new MonoResource [1];
270 int p = resources.Length - 1;
271 resources [p].name = name;
272 resources [p].filename = fileName;
273 resources [p].attrs = attribute;
277 /// Don't change the method name and parameters order. It is used by mcs
279 internal void AddPermissionRequests (PermissionSet required, PermissionSet optional, PermissionSet refused)
282 throw new InvalidOperationException ("Assembly was already saved.");
284 // required for base Assembly class (so the permissions
285 // can be used even if the assembly isn't saved to disk)
287 _optional = optional;
290 // required to reuse AddDeclarativeSecurity support
291 // already present in the runtime
292 if (required != null) {
293 permissions_minimum = new RefEmitPermissionSet [1];
294 permissions_minimum [0] = new RefEmitPermissionSet (
295 SecurityAction.RequestMinimum, required.ToXml ().ToString ());
297 if (optional != null) {
298 permissions_optional = new RefEmitPermissionSet [1];
299 permissions_optional [0] = new RefEmitPermissionSet (
300 SecurityAction.RequestOptional, optional.ToXml ().ToString ());
302 if (refused != null) {
303 permissions_refused = new RefEmitPermissionSet [1];
304 permissions_refused [0] = new RefEmitPermissionSet (
305 SecurityAction.RequestRefuse, refused.ToXml ().ToString ());
309 internal void EmbedResourceFile (string name, string fileName)
311 EmbedResourceFile (name, fileName, ResourceAttributes.Public);
314 internal void EmbedResourceFile (string name, string fileName, ResourceAttributes attribute)
316 if (resources != null) {
317 MonoResource[] new_r = new MonoResource [resources.Length + 1];
318 System.Array.Copy(resources, new_r, resources.Length);
321 resources = new MonoResource [1];
323 int p = resources.Length - 1;
324 resources [p].name = name;
325 resources [p].attrs = attribute;
327 FileStream s = new FileStream (fileName, FileMode.Open, FileAccess.Read);
329 resources [p].data = new byte [len];
330 s.Read (resources [p].data, 0, (int)len);
337 internal void EmbedResource (string name, byte[] blob, ResourceAttributes attribute)
339 if (resources != null) {
340 MonoResource[] new_r = new MonoResource [resources.Length + 1];
341 System.Array.Copy(resources, new_r, resources.Length);
344 resources = new MonoResource [1];
346 int p = resources.Length - 1;
347 resources [p].name = name;
348 resources [p].attrs = attribute;
349 resources [p].data = blob;
353 internal void AddTypeForwarder (Type t) {
355 throw new ArgumentNullException ("t");
357 if (type_forwarders == null) {
358 type_forwarders = new Type [1] { t };
360 Type[] arr = new Type [type_forwarders.Length + 1];
361 Array.Copy (type_forwarders, arr, type_forwarders.Length);
362 arr [type_forwarders.Length] = t;
363 type_forwarders = arr;
368 public ModuleBuilder DefineDynamicModule (string name)
370 return DefineDynamicModule (name, name, false, true);
373 public ModuleBuilder DefineDynamicModule (string name, bool emitSymbolInfo)
375 return DefineDynamicModule (name, name, emitSymbolInfo, true);
378 public ModuleBuilder DefineDynamicModule(string name, string fileName)
380 return DefineDynamicModule (name, fileName, false, false);
383 public ModuleBuilder DefineDynamicModule (string name, string fileName,
386 return DefineDynamicModule (name, fileName, emitSymbolInfo, false);
389 private ModuleBuilder DefineDynamicModule (string name, string fileName, bool emitSymbolInfo, bool transient)
391 check_name_and_filename (name, fileName, false);
394 if (Path.GetExtension (fileName) == String.Empty)
395 throw new ArgumentException ("Module file name '" + fileName + "' must have file extension.");
397 throw new NotSupportedException ("Persistable modules are not supported in a dynamic assembly created with AssemblyBuilderAccess.Run");
399 throw new InvalidOperationException ("Assembly was already saved.");
402 ModuleBuilder r = new ModuleBuilder (this, name, fileName, emitSymbolInfo, transient);
404 if ((modules != null) && is_module_only)
405 throw new InvalidOperationException ("A module-only assembly can only contain one module.");
407 if (modules != null) {
408 ModuleBuilder[] new_modules = new ModuleBuilder [modules.Length + 1];
409 System.Array.Copy(modules, new_modules, modules.Length);
410 modules = new_modules;
412 modules = new ModuleBuilder [1];
414 modules [modules.Length - 1] = r;
418 [MethodImplAttribute(MethodImplOptions.InternalCall)]
419 private extern Module InternalAddModule (string fileName);
422 * Mono extension to support /addmodule in mcs.
424 internal Module AddModule (string fileName)
426 if (fileName == null)
427 throw new ArgumentNullException (fileName);
429 Module m = InternalAddModule (fileName);
431 if (loaded_modules != null) {
432 Module[] new_modules = new Module [loaded_modules.Length + 1];
433 System.Array.Copy (loaded_modules, new_modules, loaded_modules.Length);
434 loaded_modules = new_modules;
436 loaded_modules = new Module [1];
438 loaded_modules [loaded_modules.Length - 1] = m;
443 public IResourceWriter DefineResource (string name, string description, string fileName)
445 return DefineResource (name, description, fileName, ResourceAttributes.Public);
448 public IResourceWriter DefineResource (string name, string description,
449 string fileName, ResourceAttributes attribute)
451 IResourceWriter writer;
453 // description seems to be ignored
454 AddResourceFile (name, fileName, attribute, false);
455 writer = new ResourceWriter (fileName);
456 if (resource_writers == null)
457 resource_writers = new ArrayList ();
458 resource_writers.Add (writer);
462 private void AddUnmanagedResource (Win32Resource res) {
463 MemoryStream ms = new MemoryStream ();
466 if (win32_resources != null) {
467 MonoWin32Resource[] new_res = new MonoWin32Resource [win32_resources.Length + 1];
468 System.Array.Copy (win32_resources, new_res, win32_resources.Length);
469 win32_resources = new_res;
472 win32_resources = new MonoWin32Resource [1];
474 win32_resources [win32_resources.Length - 1] = new MonoWin32Resource (res.Type.Id, res.Name.Id, res.Language, ms.ToArray ());
477 [MonoTODO ("Not currently implemenented")]
478 public void DefineUnmanagedResource (byte[] resource)
480 if (resource == null)
481 throw new ArgumentNullException ("resource");
482 if (native_resource != NativeResourceType.None)
483 throw new ArgumentException ("Native resource has already been defined.");
485 // avoid definition of more than one unmanaged resource
486 native_resource = NativeResourceType.Unmanaged;
489 * The format of the argument byte array is not documented
490 * so this method is impossible to implement.
493 throw new NotImplementedException ();
496 public void DefineUnmanagedResource (string resourceFileName)
498 if (resourceFileName == null)
499 throw new ArgumentNullException ("resourceFileName");
500 if (resourceFileName.Length == 0)
501 throw new ArgumentException ("resourceFileName");
502 if (!File.Exists (resourceFileName) || Directory.Exists (resourceFileName))
503 throw new FileNotFoundException ("File '" + resourceFileName + "' does not exists or is a directory.");
504 if (native_resource != NativeResourceType.None)
505 throw new ArgumentException ("Native resource has already been defined.");
507 // avoid definition of more than one unmanaged resource
508 native_resource = NativeResourceType.Unmanaged;
510 using (FileStream fs = new FileStream (resourceFileName, FileMode.Open, FileAccess.Read)) {
511 Win32ResFileReader reader = new Win32ResFileReader (fs);
513 foreach (Win32EncodedResource res in reader.ReadResources ()) {
514 if (res.Name.IsName || res.Type.IsName)
515 throw new InvalidOperationException ("resource files with named resources or non-default resource types are not supported.");
517 AddUnmanagedResource (res);
522 public void DefineVersionInfoResource ()
524 if (native_resource != NativeResourceType.None)
525 throw new ArgumentException ("Native resource has already been defined.");
527 // avoid definition of more than one unmanaged resource
528 native_resource = NativeResourceType.Assembly;
530 version_res = new Win32VersionResource (1, 0, IsCompilerContext);
533 public void DefineVersionInfoResource (string product, string productVersion,
534 string company, string copyright, string trademark)
536 if (native_resource != NativeResourceType.None)
537 throw new ArgumentException ("Native resource has already been defined.");
539 // avoid definition of more than one unmanaged resource
540 native_resource = NativeResourceType.Explicit;
543 * We can only create the resource later, when the file name and
544 * the binary version is known.
547 version_res = new Win32VersionResource (1, 0, false);
548 version_res.ProductName = product != null ? product : " ";
549 version_res.ProductVersion = productVersion != null ? productVersion : " ";
550 version_res.CompanyName = company != null ? company : " ";
551 version_res.LegalCopyright = copyright != null ? copyright : " ";
552 version_res.LegalTrademarks = trademark != null ? trademark : " ";
556 * Mono extension to support /win32icon in mcs
558 internal void DefineIconResource (string iconFileName)
560 if (iconFileName == null)
561 throw new ArgumentNullException ("iconFileName");
562 if (iconFileName.Length == 0)
563 throw new ArgumentException ("iconFileName");
564 if (!File.Exists (iconFileName) || Directory.Exists (iconFileName))
565 throw new FileNotFoundException ("File '" + iconFileName + "' does not exists or is a directory.");
567 using (FileStream fs = new FileStream (iconFileName, FileMode.Open, FileAccess.Read)) {
568 Win32IconFileReader reader = new Win32IconFileReader (fs);
570 ICONDIRENTRY[] entries = reader.ReadIcons ();
572 Win32IconResource[] icons = new Win32IconResource [entries.Length];
573 for (int i = 0; i < entries.Length; ++i) {
574 icons [i] = new Win32IconResource (i + 1, 0, entries [i]);
575 AddUnmanagedResource (icons [i]);
578 Win32GroupIconResource group = new Win32GroupIconResource (1, 0, icons);
579 AddUnmanagedResource (group);
583 private void DefineVersionInfoResourceImpl (string fileName)
585 if (versioninfo_culture != null)
586 version_res.FileLanguage = new CultureInfo (versioninfo_culture).LCID;
587 version_res.Version = version == null ? "0.0.0.0" : version;
589 if (cattrs != null) {
590 switch (native_resource) {
591 case NativeResourceType.Assembly:
592 foreach (CustomAttributeBuilder cb in cattrs) {
593 string attrname = cb.Ctor.ReflectedType.FullName;
595 if (attrname == "System.Reflection.AssemblyProductAttribute")
596 version_res.ProductName = cb.string_arg ();
597 else if (attrname == "System.Reflection.AssemblyCompanyAttribute")
598 version_res.CompanyName = cb.string_arg ();
599 else if (attrname == "System.Reflection.AssemblyCopyrightAttribute")
600 version_res.LegalCopyright = cb.string_arg ();
601 else if (attrname == "System.Reflection.AssemblyTrademarkAttribute")
602 version_res.LegalTrademarks = cb.string_arg ();
603 else if (attrname == "System.Reflection.AssemblyCultureAttribute") {
604 if (!IsCompilerContext)
605 version_res.FileLanguage = new CultureInfo (cb.string_arg ()).LCID;
606 } else if (attrname == "System.Reflection.AssemblyFileVersionAttribute") {
607 string fileversion = cb.string_arg ();
608 if (!IsCompilerContext || fileversion != null && fileversion.Length != 0)
609 version_res.FileVersion = fileversion;
610 } else if (attrname == "System.Reflection.AssemblyInformationalVersionAttribute")
611 version_res.ProductVersion = cb.string_arg ();
612 else if (attrname == "System.Reflection.AssemblyTitleAttribute")
613 version_res.FileDescription = cb.string_arg ();
614 else if (attrname == "System.Reflection.AssemblyDescriptionAttribute")
615 version_res.Comments = cb.string_arg ();
618 case NativeResourceType.Explicit:
619 foreach (CustomAttributeBuilder cb in cattrs) {
620 string attrname = cb.Ctor.ReflectedType.FullName;
622 if (attrname == "System.Reflection.AssemblyCultureAttribute") {
623 if (!IsCompilerContext)
624 version_res.FileLanguage = new CultureInfo (cb.string_arg ()).LCID;
625 } else if (attrname == "System.Reflection.AssemblyDescriptionAttribute")
626 version_res.Comments = cb.string_arg ();
632 version_res.OriginalFilename = fileName;
634 if (IsCompilerContext) {
635 version_res.InternalName = fileName;
636 if (version_res.ProductVersion.Trim ().Length == 0)
637 version_res.ProductVersion = version_res.FileVersion;
639 version_res.InternalName = Path.GetFileNameWithoutExtension (fileName);
642 AddUnmanagedResource (version_res);
645 public ModuleBuilder GetDynamicModule (string name)
648 throw new ArgumentNullException ("name");
649 if (name.Length == 0)
650 throw new ArgumentException ("Empty name is not legal.", "name");
653 for (int i = 0; i < modules.Length; ++i)
654 if (modules [i].name == name)
659 public override Type[] GetExportedTypes ()
661 throw not_supported ();
664 public override FileStream GetFile (string name)
666 throw not_supported ();
669 public override FileStream[] GetFiles(bool getResourceModules) {
670 throw not_supported ();
673 internal override Module[] GetModulesInternal () {
675 return new Module [0];
677 return (Module[])modules.Clone ();
680 internal override Type[] GetTypes (bool exportedOnly) {
682 if (modules != null) {
683 for (int i = 0; i < modules.Length; ++i) {
684 Type[] types = modules [i].GetTypes ();
688 Type[] tmp = new Type [res.Length + types.Length];
689 Array.Copy (res, 0, tmp, 0, res.Length);
690 Array.Copy (types, 0, tmp, res.Length, types.Length);
694 if (loaded_modules != null) {
695 for (int i = 0; i < loaded_modules.Length; ++i) {
696 Type[] types = loaded_modules [i].GetTypes ();
700 Type[] tmp = new Type [res.Length + types.Length];
701 Array.Copy (res, 0, tmp, 0, res.Length);
702 Array.Copy (types, 0, tmp, res.Length, types.Length);
707 return res == null ? Type.EmptyTypes : res;
710 public override ManifestResourceInfo GetManifestResourceInfo(string resourceName) {
711 throw not_supported ();
714 public override string[] GetManifestResourceNames() {
715 throw not_supported ();
718 public override Stream GetManifestResourceStream(string name) {
719 throw not_supported ();
721 public override Stream GetManifestResourceStream(Type type, string name) {
722 throw not_supported ();
726 * This is set when the the AssemblyBuilder is created by (g)mcs
729 internal bool IsCompilerContext
731 get { return is_compiler_context; }
734 internal bool IsSave {
736 return access != (uint)AssemblyBuilderAccess.Run;
740 internal string AssemblyDir {
747 * Mono extension. If this is set, the assembly can only contain one
748 * module, access should be Save, and the saved image will not contain an
751 internal bool IsModuleOnly {
753 return is_module_only;
756 is_module_only = value;
760 #if NET_2_0 || BOOTSTRAP_NET_2_0
761 ModuleBuilder manifest_module;
764 // MS.NET seems to return a ModuleBuilder when GetManifestModule () is called
765 // on an assemblybuilder.
767 internal override Module GetManifestModule () {
768 if (manifest_module == null)
769 manifest_module = DefineDynamicModule ("Default Dynamic Module");
770 return manifest_module;
779 void Save (string assemblyFileName, PortableExecutableKinds portableExecutableKind, ImageFileMachine imageFileMachine)
781 this.peKind = portableExecutableKind;
782 this.machine = imageFileMachine;
784 if (resource_writers != null) {
785 foreach (IResourceWriter writer in resource_writers) {
791 // Create a main module if not already created
792 ModuleBuilder mainModule = null;
793 if (modules != null) {
794 foreach (ModuleBuilder module in modules)
795 if (module.FullyQualifiedName == assemblyFileName)
798 if (mainModule == null)
799 mainModule = DefineDynamicModule ("RefEmit_OnDiskManifestModule", assemblyFileName);
802 mainModule.IsMain = true;
805 * Create a new entry point if the one specified
806 * by the user is in another module.
808 if ((entry_point != null) && entry_point.DeclaringType.Module != mainModule) {
810 if (entry_point.GetParameters ().Length == 1)
811 paramTypes = new Type [] { typeof (string) };
813 paramTypes = Type.EmptyTypes;
815 MethodBuilder mb = mainModule.DefineGlobalMethod ("__EntryPoint$", MethodAttributes.Static|MethodAttributes.PrivateScope, entry_point.ReturnType, paramTypes);
816 ILGenerator ilgen = mb.GetILGenerator ();
817 if (paramTypes.Length == 1)
818 ilgen.Emit (OpCodes.Ldarg_0);
819 ilgen.Emit (OpCodes.Tailcall);
820 ilgen.Emit (OpCodes.Call, entry_point);
821 ilgen.Emit (OpCodes.Ret);
826 if (version_res != null)
827 DefineVersionInfoResourceImpl (assemblyFileName);
830 // runtime needs to value to embed it into the assembly
831 public_key = sn.PublicKey;
834 foreach (ModuleBuilder module in modules)
835 if (module != mainModule)
838 // Write out the main module at the end, because it needs to
839 // contain the hash of the other modules
842 if ((sn != null) && (sn.CanSign)) {
843 sn.Sign (System.IO.Path.Combine (this.AssemblyDir, assemblyFileName));
849 public void Save (string assemblyFileName)
851 Save (assemblyFileName, PortableExecutableKinds.ILOnly, ImageFileMachine.I386);
854 public void SetEntryPoint (MethodInfo entryMethod)
856 SetEntryPoint (entryMethod, PEFileKinds.ConsoleApplication);
859 public void SetEntryPoint (MethodInfo entryMethod, PEFileKinds fileKind)
861 if (entryMethod == null)
862 throw new ArgumentNullException ("entryMethod");
863 if (entryMethod.DeclaringType.Assembly != this)
864 throw new InvalidOperationException ("Entry method is not defined in the same assembly.");
866 entry_point = entryMethod;
870 public void SetCustomAttribute( CustomAttributeBuilder customBuilder)
872 if (customBuilder == null)
873 throw new ArgumentNullException ("customBuilder");
875 if (IsCompilerContext) {
876 string attrname = customBuilder.Ctor.ReflectedType.FullName;
880 if (attrname == "System.Reflection.AssemblyVersionAttribute") {
881 version = create_assembly_version (customBuilder.string_arg ());
883 } else if (attrname == "System.Reflection.AssemblyCultureAttribute") {
884 culture = GetCultureString (customBuilder.string_arg ());
885 } else if (attrname == "System.Reflection.AssemblyAlgorithmIdAttribute") {
886 data = customBuilder.Data;
888 algid = (uint) data [pos];
889 algid |= ((uint) data [pos + 1]) << 8;
890 algid |= ((uint) data [pos + 2]) << 16;
891 algid |= ((uint) data [pos + 3]) << 24;
892 } else if (attrname == "System.Reflection.AssemblyFlagsAttribute") {
893 data = customBuilder.Data;
895 flags |= (uint) data [pos];
896 flags |= ((uint) data [pos + 1]) << 8;
897 flags |= ((uint) data [pos + 2]) << 16;
898 flags |= ((uint) data [pos + 3]) << 24;
901 // ignore PublicKey flag if assembly is not strongnamed
903 flags &= ~(uint) AssemblyNameFlags.PublicKey;
908 if (cattrs != null) {
909 CustomAttributeBuilder[] new_array = new CustomAttributeBuilder [cattrs.Length + 1];
910 cattrs.CopyTo (new_array, 0);
911 new_array [cattrs.Length] = customBuilder;
914 cattrs = new CustomAttributeBuilder [1];
915 cattrs [0] = customBuilder;
922 public void SetCustomAttribute ( ConstructorInfo con, byte[] binaryAttribute) {
924 throw new ArgumentNullException ("con");
925 if (binaryAttribute == null)
926 throw new ArgumentNullException ("binaryAttribute");
928 SetCustomAttribute (new CustomAttributeBuilder (con, binaryAttribute));
931 internal void SetCorlibTypeBuilders (Type corlib_object_type, Type corlib_value_type, Type corlib_enum_type) {
932 this.corlib_object_type = corlib_object_type;
933 this.corlib_value_type = corlib_value_type;
934 this.corlib_enum_type = corlib_enum_type;
937 internal void SetCorlibTypeBuilders (Type corlib_object_type, Type corlib_value_type, Type corlib_enum_type, Type corlib_void_type)
939 SetCorlibTypeBuilders (corlib_object_type, corlib_value_type, corlib_enum_type);
940 this.corlib_void_type = corlib_void_type;
943 private Exception not_supported () {
944 // Strange message but this is what MS.NET prints...
945 return new NotSupportedException ("The invoked member is not supported in a dynamic module.");
948 private void check_name_and_filename (string name, string fileName,
949 bool fileNeedsToExists) {
951 throw new ArgumentNullException ("name");
952 if (fileName == null)
953 throw new ArgumentNullException ("fileName");
954 if (name.Length == 0)
955 throw new ArgumentException ("Empty name is not legal.", "name");
956 if (fileName.Length == 0)
957 throw new ArgumentException ("Empty file name is not legal.", "fileName");
958 if (Path.GetFileName (fileName) != fileName)
959 throw new ArgumentException ("fileName '" + fileName + "' must not include a path.", "fileName");
961 // Resource files are created/searched under the assembly storage
963 string fullFileName = fileName;
965 fullFileName = Path.Combine (dir, fileName);
967 if (fileNeedsToExists && !File.Exists (fullFileName))
968 throw new FileNotFoundException ("Could not find file '" + fileName + "'");
970 if (resources != null) {
971 for (int i = 0; i < resources.Length; ++i) {
972 if (resources [i].filename == fullFileName)
973 throw new ArgumentException ("Duplicate file name '" + fileName + "'");
974 if (resources [i].name == name)
975 throw new ArgumentException ("Duplicate name '" + name + "'");
979 if (modules != null) {
980 for (int i = 0; i < modules.Length; ++i) {
981 // Use fileName instead of fullFileName here
982 if (!modules [i].IsTransient () && (modules [i].FileName == fileName))
983 throw new ArgumentException ("Duplicate file name '" + fileName + "'");
984 if (modules [i].Name == name)
985 throw new ArgumentException ("Duplicate name '" + name + "'");
990 private String create_assembly_version (String version) {
991 String[] parts = version.Split ('.');
992 int[] ver = new int [4] { 0, 0, 0, 0 };
994 if ((parts.Length < 0) || (parts.Length > 4))
995 throw new ArgumentException ("The version specified '" + version + "' is invalid");
997 for (int i = 0; i < parts.Length; ++i) {
998 if (parts [i] == "*") {
999 DateTime now = DateTime.Now;
1002 ver [2] = (now - new DateTime (2000, 1, 1)).Days;
1003 if (parts.Length == 3)
1004 ver [3] = (now.Second + (now.Minute * 60) + (now.Hour * 3600)) / 2;
1008 ver [3] = (now.Second + (now.Minute * 60) + (now.Hour * 3600)) / 2;
1010 throw new ArgumentException ("The version specified '" + version + "' is invalid");
1014 ver [i] = Int32.Parse (parts [i]);
1016 catch (FormatException) {
1017 throw new ArgumentException ("The version specified '" + version + "' is invalid");
1022 return ver [0] + "." + ver [1] + "." + ver [2] + "." + ver [3];
1025 private string GetCultureString (string str)
1027 return (str == "neutral" ? String.Empty : str);
1030 internal override AssemblyName UnprotectedGetName ()
1032 AssemblyName an = base.UnprotectedGetName ();
1034 an.SetPublicKey (sn.PublicKey);
1035 an.SetPublicKeyToken (sn.PublicKeyToken);
1040 void _AssemblyBuilder.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
1042 throw new NotImplementedException ();
1045 void _AssemblyBuilder.GetTypeInfo (uint iTInfo, uint lcid, IntPtr ppTInfo)
1047 throw new NotImplementedException ();
1050 void _AssemblyBuilder.GetTypeInfoCount (out uint pcTInfo)
1052 throw new NotImplementedException ();
1055 void _AssemblyBuilder.Invoke (uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
1057 throw new NotImplementedException ();