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