2 // System.Reflection.Emit/AssemblyBuilder.cs
5 // Paolo Molaro (lupus@ximian.com)
7 // (C) 2001 Ximian, Inc. http://www.ximian.com
11 using System.Reflection;
12 using System.Resources;
14 using System.Security.Policy;
15 using System.Runtime.Serialization;
16 using System.Globalization;
17 using System.Runtime.CompilerServices;
18 using System.Collections;
19 using System.Runtime.InteropServices;
20 using System.Security.Cryptography;
21 using System.Security.Permissions;
24 using Mono.Security.Cryptography;
26 namespace System.Reflection.Emit {
28 internal struct RefEmitPermissionSet {
29 public SecurityAction action;
32 public RefEmitPermissionSet (SecurityAction action, string pset) {
38 internal struct MonoResource {
41 public string filename;
42 public ResourceAttributes attrs;
46 public sealed class AssemblyBuilder : Assembly {
47 #region Sync with reflection.h
48 private IntPtr dynamic_assembly;
49 private MethodInfo entry_point;
50 private ModuleBuilder[] modules;
53 private CustomAttributeBuilder[] cattrs;
54 private MonoResource[] resources;
60 PEFileKinds pekind = PEFileKinds.Dll;
64 internal Type corlib_object_type = typeof (System.Object);
65 internal Type corlib_value_type = typeof (System.ValueType);
66 internal Type corlib_enum_type = typeof (System.Enum);
67 internal Type corlib_void_type = typeof (void);
68 ArrayList resource_writers = null;
71 [MethodImplAttribute(MethodImplOptions.InternalCall)]
72 private static extern void basic_init (AssemblyBuilder ab);
74 internal AssemblyBuilder (AssemblyName n, string directory, AssemblyBuilderAccess access) {
76 if (directory == null || directory == String.Empty)
77 dir = Directory.GetCurrentDirectory ();
80 this.access = (uint)access;
82 /* Set defaults from n */
83 if (n.CultureInfo != null) {
84 culture = n.CultureInfo.Name;
86 Version v = n.Version;
88 version = v.ToString ();
94 public override string CodeBase {
96 throw not_supported ();
100 public override MethodInfo EntryPoint {
106 public override string Location {
108 throw not_supported ();
113 /* This is to keep signature compatibility with MS.NET */
114 public override string ImageRuntimeVersion {
116 return base.ImageRuntimeVersion;
121 public void AddResourceFile (string name, string fileName)
123 AddResourceFile (name, fileName, ResourceAttributes.Public);
126 public void AddResourceFile (string name, string fileName, ResourceAttributes attribute)
128 AddResourceFile (name, fileName, attribute, true);
131 private void AddResourceFile (string name, string fileName, ResourceAttributes attribute, bool fileNeedsToExists)
133 check_name_and_filename (name, fileName, fileNeedsToExists);
135 // Resource files are created/searched under the assembly storage
138 fileName = Path.Combine (dir, fileName);
140 if (resources != null) {
141 MonoResource[] new_r = new MonoResource [resources.Length + 1];
142 System.Array.Copy(resources, new_r, resources.Length);
145 resources = new MonoResource [1];
147 int p = resources.Length - 1;
148 resources [p].name = name;
149 resources [p].filename = fileName;
150 resources [p].attrs = attribute;
153 public void EmbedResourceFile (string name, string fileName)
155 EmbedResourceFile (name, fileName, ResourceAttributes.Public);
158 public void EmbedResourceFile (string name, string fileName, ResourceAttributes attribute)
160 if (resources != null) {
161 MonoResource[] new_r = new MonoResource [resources.Length + 1];
162 System.Array.Copy(resources, new_r, resources.Length);
165 resources = new MonoResource [1];
167 int p = resources.Length - 1;
168 resources [p].name = name;
169 resources [p].attrs = attribute;
171 FileStream s = new FileStream (fileName, FileMode.Open, FileAccess.Read);
173 resources [p].data = new byte [len];
174 s.Read (resources [p].data, 0, (int)len);
181 internal void EmbedResource (string name, byte[] blob, ResourceAttributes attribute)
183 if (resources != null) {
184 MonoResource[] new_r = new MonoResource [resources.Length + 1];
185 System.Array.Copy(resources, new_r, resources.Length);
188 resources = new MonoResource [1];
190 int p = resources.Length - 1;
191 resources [p].name = name;
192 resources [p].attrs = attribute;
193 resources [p].data = blob;
196 public ModuleBuilder DefineDynamicModule (string name)
198 return DefineDynamicModule (name, name, false, true);
201 public ModuleBuilder DefineDynamicModule (string name, bool emitSymbolInfo)
203 return DefineDynamicModule (name, name, emitSymbolInfo, true);
206 public ModuleBuilder DefineDynamicModule(string name, string fileName)
208 return DefineDynamicModule (name, fileName, false, false);
211 public ModuleBuilder DefineDynamicModule (string name, string fileName,
214 return DefineDynamicModule (name, fileName, emitSymbolInfo, false);
217 private ModuleBuilder DefineDynamicModule (string name, string fileName,
218 bool emitSymbolInfo, bool transient)
220 check_name_and_filename (name, fileName, false);
223 if (Path.GetExtension (fileName) == String.Empty)
224 throw new ArgumentException ("Module file name '" + fileName + "' must have file extension.");
226 throw new NotSupportedException ("Persistable modules are not supported in a dynamic assembly created with AssemblyBuilderAccess.Run");
228 throw new InvalidOperationException ("Assembly was already saved.");
231 ModuleBuilder r = new ModuleBuilder (this, name, fileName, emitSymbolInfo, transient);
233 if (modules != null) {
234 ModuleBuilder[] new_modules = new ModuleBuilder [modules.Length + 1];
235 System.Array.Copy(modules, new_modules, modules.Length);
236 new_modules [modules.Length] = r;
237 modules = new_modules;
239 modules = new ModuleBuilder [1];
245 public IResourceWriter DefineResource (string name, string description, string fileName)
247 return DefineResource (name, description, fileName, ResourceAttributes.Public);
250 public IResourceWriter DefineResource (string name, string description,
251 string fileName, ResourceAttributes attribute)
253 IResourceWriter writer;
255 // description seems to be ignored
256 AddResourceFile (name, fileName, attribute, false);
257 writer = new ResourceWriter (fileName);
258 if (resource_writers == null)
259 resource_writers = new ArrayList ();
260 resource_writers.Add (writer);
265 public void DefineUnmanagedResource (byte[] resource)
267 if (resource == null)
268 throw new ArgumentNullException ("resource");
270 throw new NotImplementedException ();
274 public void DefineUnmanagedResource (string resourceFileName)
276 if (resourceFileName == null)
277 throw new ArgumentNullException ("resourceFileName");
278 if (resourceFileName == String.Empty)
279 throw new ArgumentException ("resourceFileName");
280 if (!File.Exists (resourceFileName) || Directory.Exists (resourceFileName))
281 throw new FileNotFoundException ("File '" + resourceFileName + "' does not exists or is a directory.");
283 throw new NotImplementedException ();
287 public void DefineVersionInfoResource ()
289 throw new NotImplementedException ();
293 public void DefineVersionInfoResource (string product, string productVersion,
294 string company, string copyright, string trademark)
296 throw new NotImplementedException ();
299 public ModuleBuilder GetDynamicModule (string name)
302 throw new ArgumentNullException ("name");
304 throw new ArgumentException ("Name can't be null");
307 for (int i = 0; i < modules.Length; ++i)
308 if (modules [i].name == name)
313 public override Type[] GetExportedTypes ()
315 throw not_supported ();
318 public override FileStream GetFile (string name)
320 throw not_supported ();
323 public override FileStream[] GetFiles(bool getResourceModules) {
324 throw not_supported ();
327 public override ManifestResourceInfo GetManifestResourceInfo(string resourceName) {
328 throw not_supported ();
331 public override string[] GetManifestResourceNames() {
332 throw not_supported ();
335 public override Stream GetManifestResourceStream(string name) {
336 throw not_supported ();
338 public override Stream GetManifestResourceStream(Type type, string name) {
339 throw not_supported ();
342 internal bool IsSave {
344 return access != (uint)AssemblyBuilderAccess.Run;
348 internal string AssemblyDir {
354 public void Save (string assemblyFileName)
356 if (resource_writers != null) {
357 foreach (IResourceWriter writer in resource_writers) {
363 // Create a main module if not already created
364 ModuleBuilder mainModule = null;
365 foreach (ModuleBuilder module in modules)
366 if (module.FullyQualifiedName == assemblyFileName)
368 if (mainModule == null)
369 mainModule = DefineDynamicModule ("RefEmit_OnDiskManifestModule", assemblyFileName);
371 mainModule.IsMain = true;
373 foreach (ModuleBuilder module in modules)
374 if (module != mainModule)
377 // Write out the main module at the end, because it needs to
378 // contain the hash of the other modules
384 public void SetEntryPoint (MethodInfo entryMethod)
386 SetEntryPoint (entryMethod, PEFileKinds.ConsoleApplication);
389 public void SetEntryPoint (MethodInfo entryMethod, PEFileKinds fileKind)
391 if (entryMethod == null)
392 throw new ArgumentNullException ("entryMethod");
393 if (entryMethod.DeclaringType.Assembly != this)
394 throw new InvalidOperationException ("Entry method is not defined in the same assembly.");
396 entry_point = entryMethod;
400 public void SetCustomAttribute( CustomAttributeBuilder customBuilder)
402 if (customBuilder == null)
403 throw new ArgumentNullException ("customBuilder");
405 string attrname = customBuilder.Ctor.ReflectedType.FullName;
408 Mono.Security.StrongName sn;
409 if (attrname == "System.Reflection.AssemblyVersionAttribute") {
410 data = customBuilder.Data;
412 len = CustomAttributeBuilder.decode_len (data, pos, out pos);
413 version = create_assembly_version (CustomAttributeBuilder.string_from_bytes (data, pos, len));
415 } else if (attrname == "System.Reflection.AssemblyKeyFileAttribute") {
416 data = customBuilder.Data;
418 len = CustomAttributeBuilder.decode_len (data, pos, out pos);
419 string keyfile_name = CustomAttributeBuilder.string_from_bytes (data, pos, len);
420 if (keyfile_name == String.Empty)
422 using (FileStream fs = new FileStream (keyfile_name, FileMode.Open)) {
423 byte[] snkeypair = new byte [fs.Length];
424 fs.Read (snkeypair, 0, snkeypair.Length);
426 // this will import public or private/public keys
427 RSA rsa = CryptoConvert.FromCapiKeyBlob (snkeypair);
428 // and export only the public part
429 sn = new Mono.Security.StrongName (rsa);
430 public_key = sn.PublicKey;
433 } else if (attrname == "System.Reflection.AssemblyKeyNameAttribute") {
434 data = customBuilder.Data;
436 len = CustomAttributeBuilder.decode_len (data, pos, out pos);
437 string key_name = CustomAttributeBuilder.string_from_bytes (data, pos, len);
438 if (key_name == String.Empty)
440 CspParameters csparam = new CspParameters ();
441 csparam.KeyContainerName = key_name;
442 RSA rsacsp = new RSACryptoServiceProvider (csparam);
443 sn = new Mono.Security.StrongName (rsacsp);
444 public_key = sn.PublicKey;
446 } else if (attrname == "System.Reflection.AssemblyCultureAttribute") {
447 data = customBuilder.Data;
449 len = CustomAttributeBuilder.decode_len (data, pos, out pos);
450 culture = CustomAttributeBuilder.string_from_bytes (data, pos, len);
451 } else if (attrname == "System.Reflection.AssemblyAlgorithmIdAttribute") {
452 data = customBuilder.Data;
454 algid = (uint)data [pos];
455 algid |= ((uint)data [pos + 1]) << 8;
456 algid |= ((uint)data [pos + 2]) << 16;
457 algid |= ((uint)data [pos + 3]) << 24;
458 } else if (attrname == "System.Reflection.AssemblyFlagsAttribute") {
459 data = customBuilder.Data;
461 flags = (uint)data [pos];
462 flags |= ((uint)data [pos + 1]) << 8;
463 flags |= ((uint)data [pos + 2]) << 16;
464 flags |= ((uint)data [pos + 3]) << 24;
466 } else if (attrname == "System.Reflection.AssemblyDelaySignAttribute") {
467 data = customBuilder.Data;
469 delay_sign = data [2] != 0;
471 if (cattrs != null) {
472 CustomAttributeBuilder[] new_array = new CustomAttributeBuilder [cattrs.Length + 1];
473 cattrs.CopyTo (new_array, 0);
474 new_array [cattrs.Length] = customBuilder;
477 cattrs = new CustomAttributeBuilder [1];
478 cattrs [0] = customBuilder;
481 public void SetCustomAttribute ( ConstructorInfo con, byte[] binaryAttribute) {
483 throw new ArgumentNullException ("con");
484 if (binaryAttribute == null)
485 throw new ArgumentNullException ("binaryAttribute");
487 SetCustomAttribute (new CustomAttributeBuilder (con, binaryAttribute));
490 public void SetCorlibTypeBuilders (Type corlib_object_type, Type corlib_value_type, Type corlib_enum_type) {
491 this.corlib_object_type = corlib_object_type;
492 this.corlib_value_type = corlib_value_type;
493 this.corlib_enum_type = corlib_enum_type;
496 public void SetCorlibTypeBuilders (Type corlib_object_type, Type corlib_value_type, Type corlib_enum_type, Type corlib_void_type)
498 SetCorlibTypeBuilders (corlib_object_type, corlib_value_type, corlib_enum_type);
499 this.corlib_void_type = corlib_void_type;
502 private Exception not_supported () {
503 // Strange message but this is what MS.NET prints...
504 return new NotSupportedException ("The invoked member is not supported in a dynamic module.");
507 private void check_name_and_filename (string name, string fileName,
508 bool fileNeedsToExists) {
510 throw new ArgumentNullException ("name");
511 if (fileName == null)
512 throw new ArgumentNullException ("fileName");
514 throw new ArgumentException ("name cannot be empty", "name");
516 throw new ArgumentException ("fileName cannot be empty", "fileName");
517 if (Path.GetFileName (fileName) != fileName)
518 throw new ArgumentException ("fileName '" + fileName + "' must not include a path.");
520 // Resource files are created/searched under the assembly storage
522 string fullFileName = fileName;
524 fullFileName = Path.Combine (dir, fileName);
526 if (fileNeedsToExists && !File.Exists (fullFileName))
527 throw new FileNotFoundException ("Could not find file '" + fileName + "'");
529 if (resources != null) {
530 for (int i = 0; i < resources.Length; ++i) {
531 if (resources [i].filename == fullFileName)
532 throw new ArgumentException ("Duplicate file name '" + fileName + "'");
533 if (resources [i].name == name)
534 throw new ArgumentException ("Duplicate name '" + name + "'");
538 if (modules != null) {
539 for (int i = 0; i < modules.Length; ++i) {
540 // Use fileName instead of fullFileName here
541 if (!modules [i].IsTransient () && (modules [i].FileName == fileName))
542 throw new ArgumentException ("Duplicate file name '" + fileName + "'");
543 if (modules [i].Name == name)
544 throw new ArgumentException ("Duplicate name '" + name + "'");
549 private String create_assembly_version (String version) {
550 String[] parts = version.Split ('.');
551 int[] ver = new int [4] { 0, 0, 0, 0 };
553 if ((parts.Length < 0) || (parts.Length > 4))
554 throw new ArgumentException ("The version specified '" + version + "' is invalid");
556 for (int i = 0; i < parts.Length; ++i) {
557 if (parts [i] == "*") {
558 DateTime now = DateTime.Now;
561 ver [2] = (now - new DateTime (2000, 1, 1)).Days;
562 if (parts.Length == 3)
563 ver [3] = (now.Second + (now.Minute * 60) + (now.Hour * 3600)) / 2;
567 ver [3] = (now.Second + (now.Minute * 60) + (now.Hour * 3600)) / 2;
569 throw new ArgumentException ("The version specified '" + version + "' is invalid");
573 ver [i] = Int32.Parse (parts [i]);
575 catch (FormatException) {
576 throw new ArgumentException ("The version specified '" + version + "' is invalid");
581 return ver [0] + "." + ver [1] + "." + ver [2] + "." + ver [3];