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