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 this.access = (uint)access;
167 flags = (uint) n.Flags;
169 // don't call GetCurrentDirectory for Run-only builders (CAS may not like that)
170 if (IsSave && (directory == null || directory.Length == 0)) {
171 dir = Directory.GetCurrentDirectory ();
176 /* Set defaults from n */
177 if (n.CultureInfo != null) {
178 culture = n.CultureInfo.Name;
179 versioninfo_culture = n.CultureInfo.Name;
181 Version v = n.Version;
183 version = v.ToString ();
186 if (n.KeyPair != null) {
187 // full keypair is available (for signing)
188 sn = n.KeyPair.StrongName ();
190 // public key is available (for delay-signing)
191 byte[] pk = n.GetPublicKey ();
192 if ((pk != null) && (pk.Length > 0)) {
193 sn = new Mono.Security.StrongName (pk);
198 flags |= (uint) AssemblyNameFlags.PublicKey;
200 this.corlib_internal = corlib_internal;
205 public override string CodeBase {
207 throw not_supported ();
211 public override MethodInfo EntryPoint {
217 public override string Location {
219 throw not_supported ();
224 /* This is to keep signature compatibility with MS.NET */
225 public override string ImageRuntimeVersion {
227 return base.ImageRuntimeVersion;
234 public override bool ReflectionOnly {
235 get { return base.ReflectionOnly; }
239 public void AddResourceFile (string name, string fileName)
241 AddResourceFile (name, fileName, ResourceAttributes.Public);
244 public void AddResourceFile (string name, string fileName, ResourceAttributes attribute)
246 AddResourceFile (name, fileName, attribute, true);
249 private void AddResourceFile (string name, string fileName, ResourceAttributes attribute, bool fileNeedsToExists)
251 check_name_and_filename (name, fileName, fileNeedsToExists);
253 // Resource files are created/searched under the assembly storage
256 fileName = Path.Combine (dir, fileName);
258 if (resources != null) {
259 MonoResource[] new_r = new MonoResource [resources.Length + 1];
260 System.Array.Copy(resources, new_r, resources.Length);
263 resources = new MonoResource [1];
265 int p = resources.Length - 1;
266 resources [p].name = name;
267 resources [p].filename = fileName;
268 resources [p].attrs = attribute;
272 /// Don't change the method name and parameters order. It is used by mcs
274 internal void AddPermissionRequests (PermissionSet required, PermissionSet optional, PermissionSet refused)
277 throw new InvalidOperationException ("Assembly was already saved.");
279 // required for base Assembly class (so the permissions
280 // can be used even if the assembly isn't saved to disk)
282 _optional = optional;
285 // required to reuse AddDeclarativeSecurity support
286 // already present in the runtime
287 if (required != null) {
288 permissions_minimum = new RefEmitPermissionSet [1];
289 permissions_minimum [0] = new RefEmitPermissionSet (
290 SecurityAction.RequestMinimum, required.ToXml ().ToString ());
292 if (optional != null) {
293 permissions_optional = new RefEmitPermissionSet [1];
294 permissions_optional [0] = new RefEmitPermissionSet (
295 SecurityAction.RequestOptional, optional.ToXml ().ToString ());
297 if (refused != null) {
298 permissions_refused = new RefEmitPermissionSet [1];
299 permissions_refused [0] = new RefEmitPermissionSet (
300 SecurityAction.RequestRefuse, refused.ToXml ().ToString ());
304 internal void EmbedResourceFile (string name, string fileName)
306 EmbedResourceFile (name, fileName, ResourceAttributes.Public);
309 internal void EmbedResourceFile (string name, string fileName, ResourceAttributes attribute)
311 if (resources != null) {
312 MonoResource[] new_r = new MonoResource [resources.Length + 1];
313 System.Array.Copy(resources, new_r, resources.Length);
316 resources = new MonoResource [1];
318 int p = resources.Length - 1;
319 resources [p].name = name;
320 resources [p].attrs = attribute;
322 FileStream s = new FileStream (fileName, FileMode.Open, FileAccess.Read);
324 resources [p].data = new byte [len];
325 s.Read (resources [p].data, 0, (int)len);
332 internal void EmbedResource (string name, byte[] blob, ResourceAttributes attribute)
334 if (resources != null) {
335 MonoResource[] new_r = new MonoResource [resources.Length + 1];
336 System.Array.Copy(resources, new_r, resources.Length);
339 resources = new MonoResource [1];
341 int p = resources.Length - 1;
342 resources [p].name = name;
343 resources [p].attrs = attribute;
344 resources [p].data = blob;
348 internal void AddTypeForwarder (Type t) {
350 throw new ArgumentNullException ("t");
352 if (type_forwarders == null) {
353 type_forwarders = new Type [1] { t };
355 Type[] arr = new Type [type_forwarders.Length + 1];
356 Array.Copy (type_forwarders, arr, type_forwarders.Length);
357 arr [type_forwarders.Length] = t;
358 type_forwarders = arr;
363 public ModuleBuilder DefineDynamicModule (string name)
365 return DefineDynamicModule (name, name, false, true);
368 public ModuleBuilder DefineDynamicModule (string name, bool emitSymbolInfo)
370 return DefineDynamicModule (name, name, emitSymbolInfo, true);
373 public ModuleBuilder DefineDynamicModule(string name, string fileName)
375 return DefineDynamicModule (name, fileName, false, false);
378 public ModuleBuilder DefineDynamicModule (string name, string fileName,
381 return DefineDynamicModule (name, fileName, emitSymbolInfo, false);
384 private ModuleBuilder DefineDynamicModule (string name, string fileName, bool emitSymbolInfo, bool transient)
386 check_name_and_filename (name, fileName, false);
389 if (Path.GetExtension (fileName) == String.Empty)
390 throw new ArgumentException ("Module file name '" + fileName + "' must have file extension.");
392 throw new NotSupportedException ("Persistable modules are not supported in a dynamic assembly created with AssemblyBuilderAccess.Run");
394 throw new InvalidOperationException ("Assembly was already saved.");
397 ModuleBuilder r = new ModuleBuilder (this, name, fileName, emitSymbolInfo, transient);
399 if ((modules != null) && is_module_only)
400 throw new InvalidOperationException ("A module-only assembly can only contain one module.");
402 if (modules != null) {
403 ModuleBuilder[] new_modules = new ModuleBuilder [modules.Length + 1];
404 System.Array.Copy(modules, new_modules, modules.Length);
405 modules = new_modules;
407 modules = new ModuleBuilder [1];
409 modules [modules.Length - 1] = r;
413 [MethodImplAttribute(MethodImplOptions.InternalCall)]
414 private extern Module InternalAddModule (string fileName);
417 * Mono extension to support /addmodule in mcs.
419 internal Module AddModule (string fileName)
421 if (fileName == null)
422 throw new ArgumentNullException (fileName);
424 Module m = InternalAddModule (fileName);
426 if (loaded_modules != null) {
427 Module[] new_modules = new Module [loaded_modules.Length + 1];
428 System.Array.Copy (loaded_modules, new_modules, loaded_modules.Length);
429 loaded_modules = new_modules;
431 loaded_modules = new Module [1];
433 loaded_modules [loaded_modules.Length - 1] = m;
438 public IResourceWriter DefineResource (string name, string description, string fileName)
440 return DefineResource (name, description, fileName, ResourceAttributes.Public);
443 public IResourceWriter DefineResource (string name, string description,
444 string fileName, ResourceAttributes attribute)
446 IResourceWriter writer;
448 // description seems to be ignored
449 AddResourceFile (name, fileName, attribute, false);
450 writer = new ResourceWriter (fileName);
451 if (resource_writers == null)
452 resource_writers = new ArrayList ();
453 resource_writers.Add (writer);
457 private void AddUnmanagedResource (Win32Resource res) {
458 MemoryStream ms = new MemoryStream ();
461 if (win32_resources != null) {
462 MonoWin32Resource[] new_res = new MonoWin32Resource [win32_resources.Length + 1];
463 System.Array.Copy (win32_resources, new_res, win32_resources.Length);
464 win32_resources = new_res;
467 win32_resources = new MonoWin32Resource [1];
469 win32_resources [win32_resources.Length - 1] = new MonoWin32Resource (res.Type.Id, res.Name.Id, res.Language, ms.ToArray ());
472 [MonoTODO ("Not currently implemenented")]
473 public void DefineUnmanagedResource (byte[] resource)
475 if (resource == null)
476 throw new ArgumentNullException ("resource");
477 if (native_resource != NativeResourceType.None)
478 throw new ArgumentException ("Native resource has already been defined.");
480 // avoid definition of more than one unmanaged resource
481 native_resource = NativeResourceType.Unmanaged;
484 * The format of the argument byte array is not documented
485 * so this method is impossible to implement.
488 throw new NotImplementedException ();
491 public void DefineUnmanagedResource (string resourceFileName)
493 if (resourceFileName == null)
494 throw new ArgumentNullException ("resourceFileName");
495 if (resourceFileName.Length == 0)
496 throw new ArgumentException ("resourceFileName");
497 if (!File.Exists (resourceFileName) || Directory.Exists (resourceFileName))
498 throw new FileNotFoundException ("File '" + resourceFileName + "' does not exists or is a directory.");
499 if (native_resource != NativeResourceType.None)
500 throw new ArgumentException ("Native resource has already been defined.");
502 // avoid definition of more than one unmanaged resource
503 native_resource = NativeResourceType.Unmanaged;
505 using (FileStream fs = new FileStream (resourceFileName, FileMode.Open, FileAccess.Read)) {
506 Win32ResFileReader reader = new Win32ResFileReader (fs);
508 foreach (Win32EncodedResource res in reader.ReadResources ()) {
509 if (res.Name.IsName || res.Type.IsName)
510 throw new InvalidOperationException ("resource files with named resources or non-default resource types are not supported.");
512 AddUnmanagedResource (res);
517 public void DefineVersionInfoResource ()
519 if (native_resource != NativeResourceType.None)
520 throw new ArgumentException ("Native resource has already been defined.");
522 // avoid definition of more than one unmanaged resource
523 native_resource = NativeResourceType.Assembly;
525 version_res = new Win32VersionResource (1, 0, IsCompilerContext);
528 public void DefineVersionInfoResource (string product, string productVersion,
529 string company, string copyright, string trademark)
531 if (native_resource != NativeResourceType.None)
532 throw new ArgumentException ("Native resource has already been defined.");
534 // avoid definition of more than one unmanaged resource
535 native_resource = NativeResourceType.Explicit;
538 * We can only create the resource later, when the file name and
539 * the binary version is known.
542 version_res = new Win32VersionResource (1, 0, false);
543 version_res.ProductName = product != null ? product : " ";
544 version_res.ProductVersion = productVersion != null ? productVersion : " ";
545 version_res.CompanyName = company != null ? company : " ";
546 version_res.LegalCopyright = copyright != null ? copyright : " ";
547 version_res.LegalTrademarks = trademark != null ? trademark : " ";
551 * Mono extension to support /win32icon in mcs
553 internal void DefineIconResource (string iconFileName)
555 if (iconFileName == null)
556 throw new ArgumentNullException ("iconFileName");
557 if (iconFileName.Length == 0)
558 throw new ArgumentException ("iconFileName");
559 if (!File.Exists (iconFileName) || Directory.Exists (iconFileName))
560 throw new FileNotFoundException ("File '" + iconFileName + "' does not exists or is a directory.");
562 using (FileStream fs = new FileStream (iconFileName, FileMode.Open, FileAccess.Read)) {
563 Win32IconFileReader reader = new Win32IconFileReader (fs);
565 ICONDIRENTRY[] entries = reader.ReadIcons ();
567 Win32IconResource[] icons = new Win32IconResource [entries.Length];
568 for (int i = 0; i < entries.Length; ++i) {
569 icons [i] = new Win32IconResource (i + 1, 0, entries [i]);
570 AddUnmanagedResource (icons [i]);
573 Win32GroupIconResource group = new Win32GroupIconResource (1, 0, icons);
574 AddUnmanagedResource (group);
578 private void DefineVersionInfoResourceImpl (string fileName)
580 if (versioninfo_culture != null)
581 version_res.FileLanguage = new CultureInfo (versioninfo_culture).LCID;
582 version_res.Version = version == null ? "0.0.0.0" : version;
584 if (cattrs != null) {
585 switch (native_resource) {
586 case NativeResourceType.Assembly:
587 foreach (CustomAttributeBuilder cb in cattrs) {
588 string attrname = cb.Ctor.ReflectedType.FullName;
590 if (attrname == "System.Reflection.AssemblyProductAttribute")
591 version_res.ProductName = cb.string_arg ();
592 else if (attrname == "System.Reflection.AssemblyCompanyAttribute")
593 version_res.CompanyName = cb.string_arg ();
594 else if (attrname == "System.Reflection.AssemblyCopyrightAttribute")
595 version_res.LegalCopyright = cb.string_arg ();
596 else if (attrname == "System.Reflection.AssemblyTrademarkAttribute")
597 version_res.LegalTrademarks = cb.string_arg ();
598 else if (attrname == "System.Reflection.AssemblyCultureAttribute") {
599 if (!IsCompilerContext)
600 version_res.FileLanguage = new CultureInfo (cb.string_arg ()).LCID;
601 } else if (attrname == "System.Reflection.AssemblyFileVersionAttribute") {
602 string fileversion = cb.string_arg ();
603 if (!IsCompilerContext || fileversion != null && fileversion.Length != 0)
604 version_res.FileVersion = fileversion;
605 } else if (attrname == "System.Reflection.AssemblyInformationalVersionAttribute")
606 version_res.ProductVersion = cb.string_arg ();
607 else if (attrname == "System.Reflection.AssemblyTitleAttribute")
608 version_res.FileDescription = cb.string_arg ();
609 else if (attrname == "System.Reflection.AssemblyDescriptionAttribute")
610 version_res.Comments = cb.string_arg ();
613 case NativeResourceType.Explicit:
614 foreach (CustomAttributeBuilder cb in cattrs) {
615 string attrname = cb.Ctor.ReflectedType.FullName;
617 if (attrname == "System.Reflection.AssemblyCultureAttribute") {
618 if (!IsCompilerContext)
619 version_res.FileLanguage = new CultureInfo (cb.string_arg ()).LCID;
620 } else if (attrname == "System.Reflection.AssemblyDescriptionAttribute")
621 version_res.Comments = cb.string_arg ();
627 version_res.OriginalFilename = fileName;
629 if (IsCompilerContext) {
630 version_res.InternalName = fileName;
631 if (version_res.ProductVersion.Trim ().Length == 0)
632 version_res.ProductVersion = version_res.FileVersion;
634 version_res.InternalName = Path.GetFileNameWithoutExtension (fileName);
637 AddUnmanagedResource (version_res);
640 public ModuleBuilder GetDynamicModule (string name)
643 throw new ArgumentNullException ("name");
644 if (name.Length == 0)
645 throw new ArgumentException ("Empty name is not legal.", "name");
648 for (int i = 0; i < modules.Length; ++i)
649 if (modules [i].name == name)
654 public override Type[] GetExportedTypes ()
656 throw not_supported ();
659 public override FileStream GetFile (string name)
661 throw not_supported ();
664 public override FileStream[] GetFiles(bool getResourceModules) {
665 throw not_supported ();
668 internal override Module[] GetModulesInternal () {
670 return new Module [0];
672 return (Module[])modules.Clone ();
675 internal override Type[] GetTypes (bool exportedOnly) {
677 if (modules != null) {
678 for (int i = 0; i < modules.Length; ++i) {
679 Type[] types = modules [i].GetTypes ();
683 Type[] tmp = new Type [res.Length + types.Length];
684 Array.Copy (res, 0, tmp, 0, res.Length);
685 Array.Copy (types, 0, tmp, res.Length, types.Length);
689 if (loaded_modules != null) {
690 for (int i = 0; i < loaded_modules.Length; ++i) {
691 Type[] types = loaded_modules [i].GetTypes ();
695 Type[] tmp = new Type [res.Length + types.Length];
696 Array.Copy (res, 0, tmp, 0, res.Length);
697 Array.Copy (types, 0, tmp, res.Length, types.Length);
702 return res == null ? Type.EmptyTypes : res;
705 public override ManifestResourceInfo GetManifestResourceInfo(string resourceName) {
706 throw not_supported ();
709 public override string[] GetManifestResourceNames() {
710 throw not_supported ();
713 public override Stream GetManifestResourceStream(string name) {
714 throw not_supported ();
716 public override Stream GetManifestResourceStream(Type type, string name) {
717 throw not_supported ();
721 * This is set when the the AssemblyBuilder is created by (g)mcs
724 internal bool IsCompilerContext
726 get { return is_compiler_context; }
729 internal bool IsSave {
731 return access != (uint)AssemblyBuilderAccess.Run;
735 internal string AssemblyDir {
742 * Mono extension. If this is set, the assembly can only contain one
743 * module, access should be Save, and the saved image will not contain an
746 internal bool IsModuleOnly {
748 return is_module_only;
751 is_module_only = value;
755 #if NET_2_0 || BOOTSTRAP_NET_2_0
756 ModuleBuilder manifest_module;
759 // MS.NET seems to return a ModuleBuilder when GetManifestModule () is called
760 // on an assemblybuilder.
762 internal override Module GetManifestModule () {
763 if (manifest_module == null)
764 manifest_module = DefineDynamicModule ("Default Dynamic Module");
765 return manifest_module;
774 void Save (string assemblyFileName, PortableExecutableKinds portableExecutableKind, ImageFileMachine imageFileMachine)
776 this.peKind = portableExecutableKind;
777 this.machine = imageFileMachine;
779 if (resource_writers != null) {
780 foreach (IResourceWriter writer in resource_writers) {
786 // Create a main module if not already created
787 ModuleBuilder mainModule = null;
788 if (modules != null) {
789 foreach (ModuleBuilder module in modules)
790 if (module.FullyQualifiedName == assemblyFileName)
793 if (mainModule == null)
794 mainModule = DefineDynamicModule ("RefEmit_OnDiskManifestModule", assemblyFileName);
797 mainModule.IsMain = true;
800 * Create a new entry point if the one specified
801 * by the user is in another module.
803 if ((entry_point != null) && entry_point.DeclaringType.Module != mainModule) {
805 if (entry_point.GetParameters ().Length == 1)
806 paramTypes = new Type [] { typeof (string) };
808 paramTypes = Type.EmptyTypes;
810 MethodBuilder mb = mainModule.DefineGlobalMethod ("__EntryPoint$", MethodAttributes.Static|MethodAttributes.PrivateScope, entry_point.ReturnType, paramTypes);
811 ILGenerator ilgen = mb.GetILGenerator ();
812 if (paramTypes.Length == 1)
813 ilgen.Emit (OpCodes.Ldarg_0);
814 ilgen.Emit (OpCodes.Tailcall);
815 ilgen.Emit (OpCodes.Call, entry_point);
816 ilgen.Emit (OpCodes.Ret);
821 if (version_res != null)
822 DefineVersionInfoResourceImpl (assemblyFileName);
825 // runtime needs to value to embed it into the assembly
826 public_key = sn.PublicKey;
829 foreach (ModuleBuilder module in modules)
830 if (module != mainModule)
833 // Write out the main module at the end, because it needs to
834 // contain the hash of the other modules
837 if ((sn != null) && (sn.CanSign)) {
838 sn.Sign (System.IO.Path.Combine (this.AssemblyDir, assemblyFileName));
844 public void Save (string assemblyFileName)
846 Save (assemblyFileName, PortableExecutableKinds.ILOnly, ImageFileMachine.I386);
849 public void SetEntryPoint (MethodInfo entryMethod)
851 SetEntryPoint (entryMethod, PEFileKinds.ConsoleApplication);
854 public void SetEntryPoint (MethodInfo entryMethod, PEFileKinds fileKind)
856 if (entryMethod == null)
857 throw new ArgumentNullException ("entryMethod");
858 if (entryMethod.DeclaringType.Assembly != this)
859 throw new InvalidOperationException ("Entry method is not defined in the same assembly.");
861 entry_point = entryMethod;
865 public void SetCustomAttribute( CustomAttributeBuilder customBuilder)
867 if (customBuilder == null)
868 throw new ArgumentNullException ("customBuilder");
870 if (IsCompilerContext) {
871 string attrname = customBuilder.Ctor.ReflectedType.FullName;
875 if (attrname == "System.Reflection.AssemblyVersionAttribute") {
876 version = create_assembly_version (customBuilder.string_arg ());
878 } else if (attrname == "System.Reflection.AssemblyCultureAttribute") {
879 culture = GetCultureString (customBuilder.string_arg ());
880 } else if (attrname == "System.Reflection.AssemblyAlgorithmIdAttribute") {
881 data = customBuilder.Data;
883 algid = (uint) data [pos];
884 algid |= ((uint) data [pos + 1]) << 8;
885 algid |= ((uint) data [pos + 2]) << 16;
886 algid |= ((uint) data [pos + 3]) << 24;
887 } else if (attrname == "System.Reflection.AssemblyFlagsAttribute") {
888 data = customBuilder.Data;
890 flags |= (uint) data [pos];
891 flags |= ((uint) data [pos + 1]) << 8;
892 flags |= ((uint) data [pos + 2]) << 16;
893 flags |= ((uint) data [pos + 3]) << 24;
896 // ignore PublicKey flag if assembly is not strongnamed
898 flags &= ~(uint) AssemblyNameFlags.PublicKey;
903 if (cattrs != null) {
904 CustomAttributeBuilder[] new_array = new CustomAttributeBuilder [cattrs.Length + 1];
905 cattrs.CopyTo (new_array, 0);
906 new_array [cattrs.Length] = customBuilder;
909 cattrs = new CustomAttributeBuilder [1];
910 cattrs [0] = customBuilder;
917 public void SetCustomAttribute ( ConstructorInfo con, byte[] binaryAttribute) {
919 throw new ArgumentNullException ("con");
920 if (binaryAttribute == null)
921 throw new ArgumentNullException ("binaryAttribute");
923 SetCustomAttribute (new CustomAttributeBuilder (con, binaryAttribute));
926 internal void SetCorlibTypeBuilders (Type corlib_object_type, Type corlib_value_type, Type corlib_enum_type) {
927 this.corlib_object_type = corlib_object_type;
928 this.corlib_value_type = corlib_value_type;
929 this.corlib_enum_type = corlib_enum_type;
932 internal void SetCorlibTypeBuilders (Type corlib_object_type, Type corlib_value_type, Type corlib_enum_type, Type corlib_void_type)
934 SetCorlibTypeBuilders (corlib_object_type, corlib_value_type, corlib_enum_type);
935 this.corlib_void_type = corlib_void_type;
938 private Exception not_supported () {
939 // Strange message but this is what MS.NET prints...
940 return new NotSupportedException ("The invoked member is not supported in a dynamic module.");
943 private void check_name_and_filename (string name, string fileName,
944 bool fileNeedsToExists) {
946 throw new ArgumentNullException ("name");
947 if (fileName == null)
948 throw new ArgumentNullException ("fileName");
949 if (name.Length == 0)
950 throw new ArgumentException ("Empty name is not legal.", "name");
951 if (fileName.Length == 0)
952 throw new ArgumentException ("Empty file name is not legal.", "fileName");
953 if (Path.GetFileName (fileName) != fileName)
954 throw new ArgumentException ("fileName '" + fileName + "' must not include a path.", "fileName");
956 // Resource files are created/searched under the assembly storage
958 string fullFileName = fileName;
960 fullFileName = Path.Combine (dir, fileName);
962 if (fileNeedsToExists && !File.Exists (fullFileName))
963 throw new FileNotFoundException ("Could not find file '" + fileName + "'");
965 if (resources != null) {
966 for (int i = 0; i < resources.Length; ++i) {
967 if (resources [i].filename == fullFileName)
968 throw new ArgumentException ("Duplicate file name '" + fileName + "'");
969 if (resources [i].name == name)
970 throw new ArgumentException ("Duplicate name '" + name + "'");
974 if (modules != null) {
975 for (int i = 0; i < modules.Length; ++i) {
976 // Use fileName instead of fullFileName here
977 if (!modules [i].IsTransient () && (modules [i].FileName == fileName))
978 throw new ArgumentException ("Duplicate file name '" + fileName + "'");
979 if (modules [i].Name == name)
980 throw new ArgumentException ("Duplicate name '" + name + "'");
985 private String create_assembly_version (String version) {
986 String[] parts = version.Split ('.');
987 int[] ver = new int [4] { 0, 0, 0, 0 };
989 if ((parts.Length < 0) || (parts.Length > 4))
990 throw new ArgumentException ("The version specified '" + version + "' is invalid");
992 for (int i = 0; i < parts.Length; ++i) {
993 if (parts [i] == "*") {
994 DateTime now = DateTime.Now;
997 ver [2] = (now - new DateTime (2000, 1, 1)).Days;
998 if (parts.Length == 3)
999 ver [3] = (now.Second + (now.Minute * 60) + (now.Hour * 3600)) / 2;
1003 ver [3] = (now.Second + (now.Minute * 60) + (now.Hour * 3600)) / 2;
1005 throw new ArgumentException ("The version specified '" + version + "' is invalid");
1009 ver [i] = Int32.Parse (parts [i]);
1011 catch (FormatException) {
1012 throw new ArgumentException ("The version specified '" + version + "' is invalid");
1017 return ver [0] + "." + ver [1] + "." + ver [2] + "." + ver [3];
1020 private string GetCultureString (string str)
1022 return (str == "neutral" ? String.Empty : str);
1025 internal override AssemblyName UnprotectedGetName ()
1027 AssemblyName an = base.UnprotectedGetName ();
1029 an.SetPublicKey (sn.PublicKey);
1030 an.SetPublicKeyToken (sn.PublicKeyToken);
1035 void _AssemblyBuilder.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
1037 throw new NotImplementedException ();
1040 void _AssemblyBuilder.GetTypeInfo (uint iTInfo, uint lcid, IntPtr ppTInfo)
1042 throw new NotImplementedException ();
1045 void _AssemblyBuilder.GetTypeInfoCount (out uint pcTInfo)
1047 throw new NotImplementedException ();
1050 void _AssemblyBuilder.Invoke (uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
1052 throw new NotImplementedException ();