2005-06-07 Zoltan Varga <vargaz@freemail.hu>
[mono.git] / mcs / class / corlib / System.Reflection.Emit / AssemblyBuilder.cs
1 //
2 // System.Reflection.Emit/AssemblyBuilder.cs
3 //
4 // Author:
5 //   Paolo Molaro (lupus@ximian.com)
6 //
7 // (C) 2001 Ximian, Inc.  http://www.ximian.com
8 //
9
10 //
11 // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
12 //
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:
20 // 
21 // The above copyright notice and this permission notice shall be
22 // included in all copies or substantial portions of the Software.
23 // 
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.
31 //
32
33 using System;
34 using System.Reflection;
35 using System.Resources;
36 using System.IO;
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;
46
47 using Mono.Security;
48 using Mono.Security.Cryptography;
49
50 namespace System.Reflection.Emit {
51
52         internal struct RefEmitPermissionSet {
53                 public SecurityAction action;
54                 public string pset;
55
56                 public RefEmitPermissionSet (SecurityAction action, string pset) {
57                         this.action = action;
58                         this.pset = pset;
59                 }
60         }
61
62         internal struct MonoResource {
63                 public byte[] data;
64                 public string name;
65                 public string filename;
66                 public ResourceAttributes attrs;
67                 public int offset;
68         }
69
70         internal struct MonoWin32Resource {
71                 public int res_type;
72                 public int res_id;
73                 public int lang_id;
74                 public byte[] data;
75
76                 public MonoWin32Resource (int res_type, int res_id, int lang_id, byte[] data) {
77                         this.res_type = res_type;
78                         this.res_id = res_id;
79                         this.lang_id = lang_id;
80                         this.data = data;
81                 }
82         }
83
84 #if NET_2_0
85         [ComVisible (true)]
86         [ClassInterfaceAttribute (ClassInterfaceType.None)]
87         [ComDefaultInterfaceAttribute (typeof (_AssemblyBuilder))]
88 #endif
89         public sealed class AssemblyBuilder : Assembly {
90                 #region Sync with reflection.h
91                 private IntPtr dynamic_assembly;
92                 private MethodInfo entry_point;
93                 private ModuleBuilder[] modules;
94                 private string name;
95                 private string dir;
96                 private CustomAttributeBuilder[] cattrs;
97                 private MonoResource[] resources;
98                 byte[] public_key;
99                 string version;
100                 string culture;
101                 uint algid;
102                 uint flags;
103                 PEFileKinds pekind = PEFileKinds.Dll;
104                 bool delay_sign;
105                 uint access;
106                 Module[] loaded_modules;
107                 MonoWin32Resource[] win32_resources;
108                 private RefEmitPermissionSet[] permissions_minimum;
109                 private RefEmitPermissionSet[] permissions_optional;
110                 private RefEmitPermissionSet[] permissions_refused;
111                 PortableExecutableKinds peKind;
112                 ImageFileMachine machine;
113                 bool corlib_internal;
114                 #endregion
115                 internal Type corlib_object_type = typeof (System.Object);
116                 internal Type corlib_value_type = typeof (System.ValueType);
117                 internal Type corlib_enum_type = typeof (System.Enum);
118                 internal Type corlib_void_type = typeof (void);
119                 ArrayList resource_writers = null;
120                 Win32VersionResource version_res;
121                 bool created;
122                 bool is_module_only;
123                 private Mono.Security.StrongName sn;
124
125                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
126                 private static extern void basic_init (AssemblyBuilder ab);
127                 
128                 internal AssemblyBuilder (AssemblyName n, string directory, AssemblyBuilderAccess access, bool corlib_internal)
129                 {
130                         name = n.Name;
131                         this.access = (uint)access;
132
133                         // don't call GetCurrentDirectory for Run-only builders (CAS may not like that)
134                         if (IsSave && (directory == null || directory == String.Empty)) {
135                                 dir = Directory.GetCurrentDirectory ();
136                         } else {
137                                 dir = directory;
138                         }
139
140                         /* Set defaults from n */
141                         if (n.CultureInfo != null) {
142                                 culture = n.CultureInfo.Name;
143                         }
144                         Version v = n.Version;
145                         if (v != null) {
146                                 version = v.ToString ();
147                         }
148
149                         if (n.KeyPair != null) {
150                                 // full keypair is available (for signing)
151                                 sn = n.KeyPair.StrongName ();
152                         }
153                         else {
154                                 // public key is available (for delay-signing)
155                                 byte[] pk = n.GetPublicKey ();
156                                 if ((pk != null) && (pk.Length > 0)) {
157                                         sn = new Mono.Security.StrongName (pk);
158                                 }
159                         }
160
161                         this.corlib_internal = corlib_internal;
162
163                         basic_init (this);
164                 }
165
166                 public override string CodeBase {
167                         get {
168                                 throw not_supported ();
169                         }
170                 }
171                 
172                 public override MethodInfo EntryPoint {
173                         get {
174                                 return entry_point;
175                         }
176                 }
177
178                 public override string Location {
179                         get {
180                                 throw not_supported ();
181                         }
182                 }
183
184 #if NET_1_1
185                 /* This is to keep signature compatibility with MS.NET */
186                 public override string ImageRuntimeVersion {
187                         get {
188                                 return base.ImageRuntimeVersion;
189                         }
190                 }
191 #endif
192
193                 public void AddResourceFile (string name, string fileName)
194                 {
195                         AddResourceFile (name, fileName, ResourceAttributes.Public);
196                 }
197
198                 public void AddResourceFile (string name, string fileName, ResourceAttributes attribute)
199                 {
200                         AddResourceFile (name, fileName, attribute, true);
201                 }
202
203                 private void AddResourceFile (string name, string fileName, ResourceAttributes attribute, bool fileNeedsToExists)
204                 {
205                         check_name_and_filename (name, fileName, fileNeedsToExists);
206
207                         // Resource files are created/searched under the assembly storage
208                         // directory
209                         if (dir != null)
210                                 fileName = Path.Combine (dir, fileName);
211
212                         if (resources != null) {
213                                 MonoResource[] new_r = new MonoResource [resources.Length + 1];
214                                 System.Array.Copy(resources, new_r, resources.Length);
215                                 resources = new_r;
216                         } else {
217                                 resources = new MonoResource [1];
218                         }
219                         int p = resources.Length - 1;
220                         resources [p].name = name;
221                         resources [p].filename = fileName;
222                         resources [p].attrs = attribute;
223                 }
224
225                 /// <summary>
226                 /// Don't change the method name and parameters order. It is used by mcs 
227                 /// </summary>
228                 internal void AddPermissionRequests (PermissionSet required, PermissionSet optional, PermissionSet refused)
229                 {
230                         if (created)
231                                 throw new InvalidOperationException ("Assembly was already saved.");
232
233                         // required for base Assembly class (so the permissions
234                         // can be used even if the assembly isn't saved to disk)
235                         _minimum = required;
236                         _optional = optional;
237                         _refuse = refused;
238
239                         // required to reuse AddDeclarativeSecurity support 
240                         // already present in the runtime
241                         if (required != null) {
242                                 permissions_minimum = new RefEmitPermissionSet [1];
243                                 permissions_minimum [0] = new RefEmitPermissionSet (
244                                         SecurityAction.RequestMinimum, required.ToXml ().ToString ());
245                         }
246                         if (optional != null) {
247                                 permissions_optional = new RefEmitPermissionSet [1];
248                                 permissions_optional [0] = new RefEmitPermissionSet (
249                                         SecurityAction.RequestOptional, optional.ToXml ().ToString ());
250                         }
251                         if (refused != null) {
252                                 permissions_refused = new RefEmitPermissionSet [1];
253                                 permissions_refused [0] = new RefEmitPermissionSet (
254                                         SecurityAction.RequestRefuse, refused.ToXml ().ToString ());
255                         }
256                 }
257
258                 internal void EmbedResourceFile (string name, string fileName)
259                 {
260                         EmbedResourceFile (name, fileName, ResourceAttributes.Public);
261                 }
262
263                 internal void EmbedResourceFile (string name, string fileName, ResourceAttributes attribute)
264                 {
265                         if (resources != null) {
266                                 MonoResource[] new_r = new MonoResource [resources.Length + 1];
267                                 System.Array.Copy(resources, new_r, resources.Length);
268                                 resources = new_r;
269                         } else {
270                                 resources = new MonoResource [1];
271                         }
272                         int p = resources.Length - 1;
273                         resources [p].name = name;
274                         resources [p].attrs = attribute;
275                         try {
276                                 FileStream s = new FileStream (fileName, FileMode.Open, FileAccess.Read);
277                                 long len = s.Length;
278                                 resources [p].data = new byte [len];
279                                 s.Read (resources [p].data, 0, (int)len);
280                                 s.Close ();
281                         } catch {
282                                 /* do something */
283                         }
284                 }
285
286                 internal void EmbedResource (string name, byte[] blob, ResourceAttributes attribute)
287                 {
288                         if (resources != null) {
289                                 MonoResource[] new_r = new MonoResource [resources.Length + 1];
290                                 System.Array.Copy(resources, new_r, resources.Length);
291                                 resources = new_r;
292                         } else {
293                                 resources = new MonoResource [1];
294                         }
295                         int p = resources.Length - 1;
296                         resources [p].name = name;
297                         resources [p].attrs = attribute;
298                         resources [p].data = blob;
299                 }
300
301                 public ModuleBuilder DefineDynamicModule (string name)
302                 {
303                         return DefineDynamicModule (name, name, false, true);
304                 }
305
306                 public ModuleBuilder DefineDynamicModule (string name, bool emitSymbolInfo)
307                 {
308                         return DefineDynamicModule (name, name, emitSymbolInfo, true);
309                 }
310
311                 public ModuleBuilder DefineDynamicModule(string name, string fileName)
312                 {
313                         return DefineDynamicModule (name, fileName, false, false);
314                 }
315
316                 public ModuleBuilder DefineDynamicModule (string name, string fileName,
317                                                           bool emitSymbolInfo)
318                 {
319                         return DefineDynamicModule (name, fileName, emitSymbolInfo, false);
320                 }
321
322                 private ModuleBuilder DefineDynamicModule (string name, string fileName,
323                                                                                                    bool emitSymbolInfo, bool transient)
324                 {
325                         check_name_and_filename (name, fileName, false);
326
327                         if (!transient) {
328                                 if (Path.GetExtension (fileName) == String.Empty)
329                                         throw new ArgumentException ("Module file name '" + fileName + "' must have file extension.");
330                                 if (!IsSave)
331                                         throw new NotSupportedException ("Persistable modules are not supported in a dynamic assembly created with AssemblyBuilderAccess.Run");
332                                 if (created)
333                                         throw new InvalidOperationException ("Assembly was already saved.");
334                         }
335
336                         ModuleBuilder r = new ModuleBuilder (this, name, fileName, emitSymbolInfo, transient);
337
338                         if ((modules != null) && is_module_only)
339                                 throw new InvalidOperationException ("A module-only assembly can only contain one module.");
340
341                         if (modules != null) {
342                                 ModuleBuilder[] new_modules = new ModuleBuilder [modules.Length + 1];
343                                 System.Array.Copy(modules, new_modules, modules.Length);
344                                 modules = new_modules;
345                         } else {
346                                 modules = new ModuleBuilder [1];
347                         }
348                         modules [modules.Length - 1] = r;
349                         return r;
350                 }
351
352                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
353                 private extern Module InternalAddModule (string fileName);
354
355                 /*
356                  * Mono extension to support /addmodule in mcs.
357                  */
358                 internal Module AddModule (string fileName)
359                 {
360                         if (fileName == null)
361                                 throw new ArgumentNullException (fileName);
362
363                         Module m = InternalAddModule (fileName);
364
365                         if (loaded_modules != null) {
366                                 Module[] new_modules = new Module [loaded_modules.Length + 1];
367                                 System.Array.Copy (loaded_modules, new_modules, loaded_modules.Length);
368                                 loaded_modules = new_modules;
369                         } else {
370                                 loaded_modules = new Module [1];
371                         }
372                         loaded_modules [loaded_modules.Length - 1] = m;
373
374                         return m;
375                 }
376
377                 public IResourceWriter DefineResource (string name, string description, string fileName)
378                 {
379                         return DefineResource (name, description, fileName, ResourceAttributes.Public);
380                 }
381
382                 public IResourceWriter DefineResource (string name, string description,
383                                                        string fileName, ResourceAttributes attribute)
384                 {
385                         IResourceWriter writer;
386
387                         // description seems to be ignored
388                         AddResourceFile (name, fileName, attribute, false);
389                         writer = new ResourceWriter (fileName);
390                         if (resource_writers == null)
391                                 resource_writers = new ArrayList ();
392                         resource_writers.Add (writer);
393                         return writer;
394                 }
395
396                 private void AddUnmanagedResource (Win32Resource res) {
397                         MemoryStream ms = new MemoryStream ();
398                         res.WriteTo (ms);
399
400                         if (win32_resources != null) {
401                                 MonoWin32Resource[] new_res = new MonoWin32Resource [win32_resources.Length + 1];
402                                 System.Array.Copy (win32_resources, new_res, win32_resources.Length);
403                                 win32_resources = new_res;
404                         }
405                         else
406                                 win32_resources = new MonoWin32Resource [1];
407
408                         win32_resources [win32_resources.Length - 1] = new MonoWin32Resource (res.Type.Id, res.Name.Id, res.Language, ms.ToArray ());
409                 }
410
411                 [MonoTODO]
412                 public void DefineUnmanagedResource (byte[] resource)
413                 {
414                         if (resource == null)
415                                 throw new ArgumentNullException ("resource");
416
417                         /*
418                          * The format of the argument byte array is not documented
419                          * so this method is impossible to implement.
420                          */
421
422                         throw new NotImplementedException ();
423                 }
424
425                 public void DefineUnmanagedResource (string resourceFileName)
426                 {
427                         if (resourceFileName == null)
428                                 throw new ArgumentNullException ("resourceFileName");
429                         if (resourceFileName == String.Empty)
430                                 throw new ArgumentException ("resourceFileName");
431                         if (!File.Exists (resourceFileName) || Directory.Exists (resourceFileName))
432                                 throw new FileNotFoundException ("File '" + resourceFileName + "' does not exists or is a directory.");
433
434                         using (FileStream fs = new FileStream (resourceFileName, FileMode.Open)) {
435                                 Win32ResFileReader reader = new Win32ResFileReader (fs);
436
437                                 foreach (Win32EncodedResource res in reader.ReadResources ()) {
438                                         if (res.Name.IsName || res.Type.IsName)
439                                                 throw new InvalidOperationException ("resource files with named resources or non-default resource types are not supported.");
440
441                                         AddUnmanagedResource (res);
442                                 }
443                         }
444                 }
445
446                 public void DefineVersionInfoResource ()
447                 {
448                         if (version_res != null)
449                                 throw new ArgumentException ("Native resource has already been defined.");                      
450
451                         version_res = new Win32VersionResource (1, 0);
452
453                         if (cattrs != null) {
454                                 foreach (CustomAttributeBuilder cb in cattrs) {
455                                         string attrname = cb.Ctor.ReflectedType.FullName;
456
457                                         if (attrname == "System.Reflection.AssemblyProductAttribute")
458                                                 version_res.ProductName = cb.string_arg ();
459                                         else if (attrname == "System.Reflection.AssemblyCompanyAttribute")
460                                                 version_res.CompanyName = cb.string_arg ();
461                                         else if (attrname == "System.Reflection.AssemblyCopyrightAttribute")
462                                                 version_res.LegalCopyright = cb.string_arg ();
463                                         else if (attrname == "System.Reflection.AssemblyTrademarkAttribute")
464                                                 version_res.LegalTrademarks = cb.string_arg ();
465                                         else if (attrname == "System.Reflection.AssemblyCultureAttribute")
466                                                 version_res.FileLanguage = new CultureInfo (GetCultureString (cb.string_arg ())).LCID;
467                                         else if (attrname == "System.Reflection.AssemblyFileVersionAttribute")
468                                                 version_res.FileVersion = cb.string_arg ();
469                                         else if (attrname == "System.Reflection.AssemblyInformationalVersionAttribute")
470                                                 version_res.ProductVersion = cb.string_arg ();
471                                         else if (attrname == "System.Reflection.AssemblyTitleAttribute")
472                                                 version_res.FileDescription = cb.string_arg ();
473                                         else if (attrname == "System.Reflection.AssemblyDescriptionAttribute")
474                                                 version_res.Comments = cb.string_arg ();
475                                 }
476                         }
477                 }
478
479                 public void DefineVersionInfoResource (string product, string productVersion,
480                                                        string company, string copyright, string trademark)
481                 {
482                         if (version_res != null)
483                                 throw new ArgumentException ("Native resource has already been defined.");
484
485                         /*
486                          * We can only create the resource later, when the file name and
487                          * the binary version is known.
488                          */
489
490                         version_res = new Win32VersionResource (1, 0);
491                         version_res.ProductName = product;
492                         version_res.ProductVersion = productVersion;
493                         version_res.CompanyName = company;
494                         version_res.LegalCopyright = copyright;
495                         version_res.LegalTrademarks = trademark;
496                 }
497
498                 /* 
499                  * Mono extension to support /win32icon in mcs
500                  */
501                 internal void DefineIconResource (string iconFileName)
502                 {
503                         if (iconFileName == null)
504                                 throw new ArgumentNullException ("iconFileName");
505                         if (iconFileName == String.Empty)
506                                 throw new ArgumentException ("iconFileName");
507                         if (!File.Exists (iconFileName) || Directory.Exists (iconFileName))
508                                 throw new FileNotFoundException ("File '" + iconFileName + "' does not exists or is a directory.");
509
510                         using (FileStream fs = new FileStream (iconFileName, FileMode.Open)) {
511                                 Win32IconFileReader reader = new Win32IconFileReader (fs);
512                                 
513                                 ICONDIRENTRY[] entries = reader.ReadIcons ();
514
515                                 Win32IconResource[] icons = new Win32IconResource [entries.Length];
516                                 for (int i = 0; i < entries.Length; ++i) {
517                                         icons [i] = new Win32IconResource (i + 1, 0, entries [i]);
518                                         AddUnmanagedResource (icons [i]);
519                                 }
520
521                                 Win32GroupIconResource group = new Win32GroupIconResource (1, 0, icons);
522                                 AddUnmanagedResource (group);
523                         }
524                 }
525
526                 private void DefineVersionInfoResourceImpl (string fileName) {
527                         // Add missing info
528                         if (version_res.FileVersion == "0.0.0.0")
529                                 version_res.FileVersion = version;
530                         version_res.InternalName = Path.GetFileNameWithoutExtension (fileName);
531                         version_res.OriginalFilename = fileName;
532
533                         AddUnmanagedResource (version_res);
534                 }
535
536                 public ModuleBuilder GetDynamicModule (string name)
537                 {
538                         if (name == null)
539                                 throw new ArgumentNullException ("name");
540                         if (name == "")
541                                 throw new ArgumentException ("Name can't be null");
542
543                         if (modules != null)
544                                 for (int i = 0; i < modules.Length; ++i)
545                                         if (modules [i].name == name)
546                                                 return modules [i];
547                         return null;
548                 }
549
550                 public override Type[] GetExportedTypes ()
551                 {
552                         throw not_supported ();
553                 }
554
555                 public override FileStream GetFile (string name)
556                 {
557                         throw not_supported ();
558                 }
559
560                 public override FileStream[] GetFiles(bool getResourceModules) {
561                         throw not_supported ();
562                 }
563
564                 public override ManifestResourceInfo GetManifestResourceInfo(string resourceName) {
565                         throw not_supported ();
566                 }
567
568                 public override string[] GetManifestResourceNames() {
569                         throw not_supported ();
570                 }
571
572                 public override Stream GetManifestResourceStream(string name) {
573                         throw not_supported ();
574                 }
575                 public override Stream GetManifestResourceStream(Type type, string name) {
576                         throw not_supported ();
577                 }
578
579                 internal bool IsSave {
580                         get {
581                                 return access != (uint)AssemblyBuilderAccess.Run;
582                         }
583                 }
584
585                 internal string AssemblyDir {
586                         get {
587                                 return dir;
588                         }
589                 }
590
591                 /*
592                  * Mono extension. If this is set, the assembly can only contain one
593                  * module, access should be Save, and the saved image will not contain an
594                  * assembly manifest.
595                  */
596                 internal bool IsModuleOnly {
597                         get {
598                                 return is_module_only;
599                         }
600                         set {
601                                 is_module_only = value;
602                         }
603                 }
604
605 #if NET_2_0
606                 public 
607 #else
608                 internal
609 #endif
610                 void Save (string assemblyFileName, PortableExecutableKinds portableExecutableKind, ImageFileMachine imageFileMachine)
611                 {
612                         this.peKind = portableExecutableKind;
613                         this.machine = imageFileMachine;
614
615                         if (resource_writers != null) {
616                                 foreach (IResourceWriter writer in resource_writers) {
617                                         writer.Generate ();
618                                         writer.Close ();
619                                 }
620                         }
621
622                         // Create a main module if not already created
623                         ModuleBuilder mainModule = null;
624                         if (modules != null) {
625                                 foreach (ModuleBuilder module in modules)
626                                         if (module.FullyQualifiedName == assemblyFileName)
627                                                 mainModule = module;
628                         }
629                         if (mainModule == null)
630                                 mainModule = DefineDynamicModule ("RefEmit_OnDiskManifestModule", assemblyFileName);
631
632                         if (!is_module_only)
633                                 mainModule.IsMain = true;
634
635                         /* 
636                          * Create a new entry point if the one specified
637                          * by the user is in another module.
638                          */
639                         if ((entry_point != null) && entry_point.DeclaringType.Module != mainModule) {
640                                 Type[] paramTypes;
641                                 if (entry_point.GetParameters ().Length == 1)
642                                         paramTypes = new Type [] { typeof (string) };
643                                 else
644                                         paramTypes = new Type [0];
645
646                                 MethodBuilder mb = mainModule.DefineGlobalMethod ("__EntryPoint$", MethodAttributes.Static|MethodAttributes.PrivateScope, entry_point.ReturnType, paramTypes);
647                                 ILGenerator ilgen = mb.GetILGenerator ();
648                                 if (paramTypes.Length == 1)
649                                         ilgen.Emit (OpCodes.Ldarg_0);
650                                 ilgen.Emit (OpCodes.Tailcall);
651                                 ilgen.Emit (OpCodes.Call, entry_point);
652                                 ilgen.Emit (OpCodes.Ret);
653
654                                 entry_point = mb;
655                         }
656
657                         if (version_res != null)
658                                 DefineVersionInfoResourceImpl (assemblyFileName);
659
660                         if (sn != null) {
661                                 // runtime needs to value to embed it into the assembly
662                                 public_key = sn.PublicKey;
663                         }
664
665                         foreach (ModuleBuilder module in modules)
666                                 if (module != mainModule)
667                                         module.Save ();
668
669                         // Write out the main module at the end, because it needs to
670                         // contain the hash of the other modules
671                         mainModule.Save ();
672
673                         if ((sn != null) && (sn.CanSign)) {
674                                 sn.Sign (System.IO.Path.Combine (this.AssemblyDir, assemblyFileName));
675                         }
676
677                         created = true;
678                 }
679
680                 public void Save (string assemblyFileName)
681                 {
682                         Save (assemblyFileName, PortableExecutableKinds.ILOnly, ImageFileMachine.I386);
683                 }
684
685                 public void SetEntryPoint (MethodInfo entryMethod)
686                 {
687                         SetEntryPoint (entryMethod, PEFileKinds.ConsoleApplication);
688                 }
689
690                 public void SetEntryPoint (MethodInfo entryMethod, PEFileKinds fileKind)
691                 {
692                         if (entryMethod == null)
693                                 throw new ArgumentNullException ("entryMethod");
694                         if (entryMethod.DeclaringType.Assembly != this)
695                                 throw new InvalidOperationException ("Entry method is not defined in the same assembly.");
696
697                         entry_point = entryMethod;
698                         pekind = fileKind;
699                 }
700
701                 public void SetCustomAttribute( CustomAttributeBuilder customBuilder) 
702                 {
703                         if (customBuilder == null)
704                                 throw new ArgumentNullException ("customBuilder");
705
706                         string attrname = customBuilder.Ctor.ReflectedType.FullName;
707                         byte[] data;
708                         int pos;
709
710                         if (attrname == "System.Reflection.AssemblyVersionAttribute") {
711                                 version = create_assembly_version (customBuilder.string_arg ());
712                                 return;
713                         } else if (attrname == "System.Reflection.AssemblyCultureAttribute") {
714                                 culture = GetCultureString (customBuilder.string_arg ());
715                         } else if (attrname == "System.Reflection.AssemblyAlgorithmIdAttribute") {
716                                 data = customBuilder.Data;
717                                 pos = 2;
718                                 algid = (uint)data [pos];
719                                 algid |= ((uint)data [pos + 1]) << 8;
720                                 algid |= ((uint)data [pos + 2]) << 16;
721                                 algid |= ((uint)data [pos + 3]) << 24;
722                         } else if (attrname == "System.Reflection.AssemblyFlagsAttribute") {
723                                 data = customBuilder.Data;
724                                 pos = 2;
725                                 flags = (uint)data [pos];
726                                 flags |= ((uint)data [pos + 1]) << 8;
727                                 flags |= ((uint)data [pos + 2]) << 16;
728                                 flags |= ((uint)data [pos + 3]) << 24;
729                                 return;
730                         }
731
732                         if (cattrs != null) {
733                                 CustomAttributeBuilder[] new_array = new CustomAttributeBuilder [cattrs.Length + 1];
734                                 cattrs.CopyTo (new_array, 0);
735                                 new_array [cattrs.Length] = customBuilder;
736                                 cattrs = new_array;
737                         } else {
738                                 cattrs = new CustomAttributeBuilder [1];
739                                 cattrs [0] = customBuilder;
740                         }
741                 }
742
743 #if NET_2_0
744                 [ComVisible (true)]
745 #endif
746                 public void SetCustomAttribute ( ConstructorInfo con, byte[] binaryAttribute) {
747                         if (con == null)
748                                 throw new ArgumentNullException ("con");
749                         if (binaryAttribute == null)
750                                 throw new ArgumentNullException ("binaryAttribute");
751
752                         SetCustomAttribute (new CustomAttributeBuilder (con, binaryAttribute));
753                 }
754
755                 internal void SetCorlibTypeBuilders (Type corlib_object_type, Type corlib_value_type, Type corlib_enum_type) {
756                         this.corlib_object_type = corlib_object_type;
757                         this.corlib_value_type = corlib_value_type;
758                         this.corlib_enum_type = corlib_enum_type;
759                 }
760
761                 internal void SetCorlibTypeBuilders (Type corlib_object_type, Type corlib_value_type, Type corlib_enum_type, Type corlib_void_type)
762                 {
763                         SetCorlibTypeBuilders (corlib_object_type, corlib_value_type, corlib_enum_type);
764                         this.corlib_void_type = corlib_void_type;
765                 }
766
767                 private Exception not_supported () {
768                         // Strange message but this is what MS.NET prints...
769                         return new NotSupportedException ("The invoked member is not supported in a dynamic module.");
770                 }
771
772                 private void check_name_and_filename (string name, string fileName,
773                                                                                           bool fileNeedsToExists) {
774                         if (name == null)
775                                 throw new ArgumentNullException ("name");
776                         if (fileName == null)
777                                 throw new ArgumentNullException ("fileName");
778                         if (name == "")
779                                 throw new ArgumentException ("name cannot be empty", "name");
780                         if (fileName == "")
781                                 throw new ArgumentException ("fileName cannot be empty", "fileName");
782                         if (Path.GetFileName (fileName) != fileName)
783                                 throw new ArgumentException ("fileName '" + fileName + "' must not include a path.");
784
785                         // Resource files are created/searched under the assembly storage
786                         // directory
787                         string fullFileName = fileName;
788                         if (dir != null)
789                                 fullFileName = Path.Combine (dir, fileName);
790
791                         if (fileNeedsToExists && !File.Exists (fullFileName))
792                                 throw new FileNotFoundException ("Could not find file '" + fileName + "'");
793
794                         if (resources != null) {
795                                 for (int i = 0; i < resources.Length; ++i) {
796                                         if (resources [i].filename == fullFileName)
797                                                 throw new ArgumentException ("Duplicate file name '" + fileName + "'");
798                                         if (resources [i].name == name)
799                                                 throw new ArgumentException ("Duplicate name '" + name + "'");
800                                 }
801                         }
802
803                         if (modules != null) {
804                                 for (int i = 0; i < modules.Length; ++i) {
805                                         // Use fileName instead of fullFileName here
806                                         if (!modules [i].IsTransient () && (modules [i].FileName == fileName))
807                                                 throw new ArgumentException ("Duplicate file name '" + fileName + "'");
808                                         if (modules [i].Name == name)
809                                                 throw new ArgumentException ("Duplicate name '" + name + "'");
810                                 }
811                         }
812                 }
813
814                 private String create_assembly_version (String version) {
815                         String[] parts = version.Split ('.');
816                         int[] ver = new int [4] { 0, 0, 0, 0 };
817
818                         if ((parts.Length < 0) || (parts.Length > 4))
819                                 throw new ArgumentException ("The version specified '" + version + "' is invalid");
820
821                         for (int i = 0; i < parts.Length; ++i) {
822                                 if (parts [i] == "*") {
823                                         DateTime now = DateTime.Now;
824
825                                         if (i == 2) {
826                                                 ver [2] = (now - new DateTime (2000, 1, 1)).Days;
827                                                 if (parts.Length == 3)
828                                                         ver [3] = (now.Second + (now.Minute * 60) + (now.Hour * 3600)) / 2;
829                                         }
830                                         else
831                                                 if (i == 3)
832                                                         ver [3] = (now.Second + (now.Minute * 60) + (now.Hour * 3600)) / 2;
833                                         else
834                                                 throw new ArgumentException ("The version specified '" + version + "' is invalid");
835                                 }
836                                 else {
837                                         try {
838                                                 ver [i] = Int32.Parse (parts [i]);
839                                         }
840                                         catch (FormatException) {
841                                                 throw new ArgumentException ("The version specified '" + version + "' is invalid");
842                                         }
843                                 }
844                         }
845
846                         return ver [0] + "." + ver [1] + "." + ver [2] + "." + ver [3];
847                 }
848
849                 private string GetCultureString (string str)
850                 {
851                         return (str == "neutral" ? String.Empty : str);
852                 }
853         }
854 }