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