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