3 // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
5 // Permission is hereby granted, free of charge, to any person obtaining
6 // a copy of this software and associated documentation files (the
7 // "Software"), to deal in the Software without restriction, including
8 // without limitation the rights to use, copy, modify, merge, publish,
9 // distribute, sublicense, and/or sell copies of the Software, and to
10 // permit persons to whom the Software is furnished to do so, subject to
11 // the following conditions:
13 // The above copyright notice and this permission notice shall be
14 // included in all copies or substantial portions of the Software.
16 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
19 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
20 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
21 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
22 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
26 // System.Reflection.Emit/ModuleBuilder.cs
29 // Paolo Molaro (lupus@ximian.com)
31 // (C) 2001 Ximian, Inc. http://www.ximian.com
35 using System.Reflection;
36 using System.Collections;
37 using System.Runtime.CompilerServices;
38 using System.Runtime.InteropServices;
39 using System.Diagnostics.SymbolStore;
41 using System.Resources;
42 using System.Globalization;
44 namespace System.Reflection.Emit {
45 public class ModuleBuilder : Module {
46 #region Sync with reflection.h
47 private IntPtr dynamic_image;
48 private int num_types;
49 private TypeBuilder[] types;
50 private CustomAttributeBuilder[] cattrs;
52 private int table_idx;
53 internal AssemblyBuilder assemblyb;
54 private MethodBuilder[] global_methods;
55 private FieldBuilder[] global_fields;
57 private MonoResource[] resources;
59 private TypeBuilder global_type;
60 private Type global_type_created;
62 Hashtable us_string_cache = new Hashtable ();
63 private int[] table_indexes;
65 ModuleBuilderTokenGenerator token_gen;
66 ArrayList resource_writers = null;
68 [MethodImplAttribute(MethodImplOptions.InternalCall)]
69 private static extern void basic_init (ModuleBuilder ab);
71 internal ModuleBuilder (AssemblyBuilder assb, string name, string fullyqname, bool emitSymbolInfo, bool transient) {
72 this.name = this.scopename = name;
73 this.fqname = fullyqname;
74 this.assembly = this.assemblyb = assb;
75 this.transient = transient;
76 // to keep mcs fast we do not want CryptoConfig wo be involved to create the RNG
77 guid = Guid.FastNewGuidArray ();
78 // guid = Guid.NewGuid().ToByteArray ();
79 table_idx = get_next_table_index (this, 0x00, true);
80 name_cache = new Hashtable ();
87 public override string FullyQualifiedName {get { return fqname;}}
89 public bool IsTransient () {
93 public void CreateGlobalFunctions ()
95 if (global_type_created != null)
96 throw new InvalidOperationException ("global methods already created");
97 if (global_type != null)
98 global_type_created = global_type.CreateType ();
101 public FieldBuilder DefineInitializedData( string name, byte[] data, FieldAttributes attributes) {
103 throw new ArgumentNullException ("data");
105 FieldBuilder fb = DefineUninitializedData (name, data.Length,
106 attributes | FieldAttributes.HasFieldRVA);
107 fb.SetRVAData (data);
112 public FieldBuilder DefineUninitializedData( string name, int size, FieldAttributes attributes) {
114 throw new ArgumentNullException ("name");
115 if (global_type_created != null)
116 throw new InvalidOperationException ("global fields already created");
117 if (global_type == null)
118 global_type = new TypeBuilder (this, 0);
120 string typeName = "$ArrayType$" + size;
121 Type datablobtype = GetType (typeName, false, false);
122 if (datablobtype == null) {
123 TypeBuilder tb = DefineType (typeName,
124 TypeAttributes.Public|TypeAttributes.ExplicitLayout|TypeAttributes.Sealed,
125 assemblyb.corlib_value_type, null, PackingSize.Size1, size);
129 FieldBuilder fb = global_type.DefineField (name, datablobtype, attributes|FieldAttributes.Static);
131 if (global_fields != null) {
132 FieldBuilder[] new_fields = new FieldBuilder [global_fields.Length+1];
133 System.Array.Copy (global_fields, new_fields, global_fields.Length);
134 new_fields [global_fields.Length] = fb;
135 global_fields = new_fields;
137 global_fields = new FieldBuilder [1];
138 global_fields [0] = fb;
143 private void addGlobalMethod (MethodBuilder mb) {
144 if (global_methods != null) {
145 MethodBuilder[] new_methods = new MethodBuilder [global_methods.Length+1];
146 System.Array.Copy (global_methods, new_methods, global_methods.Length);
147 new_methods [global_methods.Length] = mb;
148 global_methods = new_methods;
150 global_methods = new MethodBuilder [1];
151 global_methods [0] = mb;
155 public MethodBuilder DefineGlobalMethod (string name, MethodAttributes attributes, Type returnType, Type[] parameterTypes)
157 return DefineGlobalMethod (name, attributes, CallingConventions.Standard, returnType, parameterTypes);
160 public MethodBuilder DefineGlobalMethod (string name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes) {
161 return DefineGlobalMethod (name, attributes, callingConvention, returnType, null, null, parameterTypes, null, null);
164 #if NET_2_0 || BOOTSTRAP_NET_2_0
169 MethodBuilder DefineGlobalMethod (string name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] requiredReturnTypeCustomModifiers, Type[] optionalReturnTypeCustomModifiers, Type[] parameterTypes, Type[][] requiredParameterTypeCustomModifiers, Type[][] optionalParameterTypeCustomModifiers)
172 throw new ArgumentNullException ("name");
173 if ((attributes & MethodAttributes.Static) == 0)
174 throw new ArgumentException ("global methods must be static");
175 if (global_type_created != null)
176 throw new InvalidOperationException ("global methods already created");
177 if (global_type == null)
178 global_type = new TypeBuilder (this, 0);
179 MethodBuilder mb = global_type.DefineMethod (name, attributes, callingConvention, returnType, requiredReturnTypeCustomModifiers, optionalReturnTypeCustomModifiers, parameterTypes, requiredParameterTypeCustomModifiers, optionalParameterTypeCustomModifiers);
181 addGlobalMethod (mb);
185 public MethodBuilder DefinePInvokeMethod (string name, string dllName, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes, CallingConvention nativeCallConv, CharSet nativeCharSet) {
186 return DefinePInvokeMethod (name, dllName, name, attributes, callingConvention, returnType, parameterTypes, nativeCallConv, nativeCharSet);
189 public MethodBuilder DefinePInvokeMethod (string name, string dllName, string entryName, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes, CallingConvention nativeCallConv, CharSet nativeCharSet) {
191 throw new ArgumentNullException ("name");
192 if ((attributes & MethodAttributes.Static) == 0)
193 throw new ArgumentException ("global methods must be static");
194 if (global_type_created != null)
195 throw new InvalidOperationException ("global methods already created");
196 if (global_type == null)
197 global_type = new TypeBuilder (this, 0);
198 MethodBuilder mb = global_type.DefinePInvokeMethod (name, dllName, entryName, attributes, callingConvention, returnType, parameterTypes, nativeCallConv, nativeCharSet);
200 addGlobalMethod (mb);
204 public TypeBuilder DefineType (string name) {
205 return DefineType (name, 0);
208 public TypeBuilder DefineType (string name, TypeAttributes attr) {
209 if ((attr & TypeAttributes.Interface) != 0)
210 return DefineType (name, attr, null, null);
211 return DefineType (name, attr, typeof(object), null);
214 public TypeBuilder DefineType (string name, TypeAttributes attr, Type parent) {
215 return DefineType (name, attr, parent, null);
218 private void AddType (TypeBuilder tb)
221 if (types.Length == num_types) {
222 TypeBuilder[] new_types = new TypeBuilder [types.Length * 2];
223 System.Array.Copy (types, new_types, num_types);
227 types = new TypeBuilder [1];
229 types [num_types] = tb;
233 private TypeBuilder DefineType (string name, TypeAttributes attr, Type parent, Type[] interfaces, PackingSize packsize, int typesize) {
234 if (name_cache.Contains (name))
235 throw new ArgumentException ("Duplicate type name within an assembly.");
237 TypeBuilder res = new TypeBuilder (this, name, attr, parent, interfaces, packsize, typesize, null);
239 name_cache.Add (name, res);
243 internal void RegisterTypeName (TypeBuilder tb, string name) {
244 name_cache.Add (name, tb);
247 public TypeBuilder DefineType (string name, TypeAttributes attr, Type parent, Type[] interfaces) {
248 return DefineType (name, attr, parent, interfaces, PackingSize.Unspecified, TypeBuilder.UnspecifiedTypeSize);
251 public TypeBuilder DefineType (string name, TypeAttributes attr, Type parent, int typesize) {
252 return DefineType (name, attr, parent, null, PackingSize.Unspecified, TypeBuilder.UnspecifiedTypeSize);
255 public TypeBuilder DefineType (string name, TypeAttributes attr, Type parent, PackingSize packsize) {
256 return DefineType (name, attr, parent, null, packsize, TypeBuilder.UnspecifiedTypeSize);
259 public TypeBuilder DefineType (string name, TypeAttributes attr, Type parent, PackingSize packsize, int typesize) {
260 return DefineType (name, attr, parent, null, packsize, typesize);
263 public MethodInfo GetArrayMethod( Type arrayClass, string methodName, CallingConventions callingConvention, Type returnType, Type[] parameterTypes) {
264 return new MonoArrayMethod (arrayClass, methodName, callingConvention, returnType, parameterTypes);
267 public EnumBuilder DefineEnum( string name, TypeAttributes visibility, Type underlyingType) {
268 if (name_cache.Contains (name))
269 throw new ArgumentException ("Duplicate type name within an assembly.");
271 EnumBuilder eb = new EnumBuilder (this, name, visibility, underlyingType);
272 TypeBuilder res = eb.GetTypeBuilder ();
274 name_cache.Add (name, res);
278 public override Type GetType( string className) {
279 return GetType (className, false, false);
282 public override Type GetType( string className, bool ignoreCase) {
283 return GetType (className, false, ignoreCase);
286 private TypeBuilder search_in_array (TypeBuilder[] arr, int validElementsInArray, string className) {
288 for (i = 0; i < validElementsInArray; ++i) {
289 if (String.Compare (className, arr [i].FullName, true, CultureInfo.InvariantCulture) == 0) {
296 private TypeBuilder search_nested_in_array (TypeBuilder[] arr, int validElementsInArray, string className) {
298 for (i = 0; i < validElementsInArray; ++i) {
299 if (String.Compare (className, arr [i].Name, true, CultureInfo.InvariantCulture) == 0)
305 [MethodImplAttribute(MethodImplOptions.InternalCall)]
306 private static extern Type create_modified_type (TypeBuilder tb, string modifiers);
308 static readonly char [] type_modifiers = {'&', '[', '*'};
310 private TypeBuilder GetMaybeNested (TypeBuilder t, string className) {
314 subt = className.IndexOf ('+');
316 if (t.subtypes != null)
317 return search_nested_in_array (t.subtypes, t.subtypes.Length, className);
320 if (t.subtypes != null) {
321 pname = className.Substring (0, subt);
322 rname = className.Substring (subt + 1);
323 TypeBuilder result = search_nested_in_array (t.subtypes, t.subtypes.Length, pname);
325 return GetMaybeNested (result, rname);
330 public override Type GetType (string className, bool throwOnError, bool ignoreCase) {
332 string orig = className;
334 TypeBuilder result = null;
336 if (types == null && throwOnError)
337 throw new TypeLoadException (className);
339 subt = className.IndexOfAny (type_modifiers);
341 modifiers = className.Substring (subt);
342 className = className.Substring (0, subt);
347 result = name_cache [className] as TypeBuilder;
349 subt = className.IndexOf ('+');
352 result = search_in_array (types, num_types, className);
355 pname = className.Substring (0, subt);
356 rname = className.Substring (subt + 1);
357 result = search_in_array (types, num_types, pname);
359 result = GetMaybeNested (result, rname);
362 if ((result == null) && throwOnError)
363 throw new TypeLoadException (orig);
364 if (result != null && (modifiers != null))
365 return create_modified_type (result, modifiers);
369 internal int get_next_table_index (object obj, int table, bool inc) {
370 if (table_indexes == null) {
371 table_indexes = new int [64];
372 for (int i=0; i < 64; ++i)
373 table_indexes [i] = 1;
374 /* allow room for .<Module> in TypeDef table */
375 table_indexes [0x02] = 2;
377 // Console.WriteLine ("getindex for table "+table.ToString()+" got "+table_indexes [table].ToString());
379 return table_indexes [table]++;
380 return table_indexes [table];
383 public void SetCustomAttribute( CustomAttributeBuilder customBuilder) {
384 if (cattrs != null) {
385 CustomAttributeBuilder[] new_array = new CustomAttributeBuilder [cattrs.Length + 1];
386 cattrs.CopyTo (new_array, 0);
387 new_array [cattrs.Length] = customBuilder;
390 cattrs = new CustomAttributeBuilder [1];
391 cattrs [0] = customBuilder;
394 public void SetCustomAttribute( ConstructorInfo con, byte[] binaryAttribute) {
395 SetCustomAttribute (new CustomAttributeBuilder (con, binaryAttribute));
398 public ISymbolWriter GetSymWriter () {
402 public ISymbolDocumentWriter DefineDocument (string url, Guid language, Guid languageVendor, Guid documentType) {
406 public override Type [] GetTypes ()
409 return new TypeBuilder [0];
412 TypeBuilder [] copy = new TypeBuilder [n];
413 Array.Copy (types, copy, n);
418 public IResourceWriter DefineResource (string name, string description, ResourceAttributes attribute)
421 throw new ArgumentNullException ("name");
422 if (name == String.Empty)
423 throw new ArgumentException ("name cannot be empty");
425 throw new InvalidOperationException ("The module is transient");
426 if (!assemblyb.IsSave)
427 throw new InvalidOperationException ("The assembly is transient");
428 ResourceWriter writer = new ResourceWriter (new MemoryStream ());
429 if (resource_writers == null)
430 resource_writers = new ArrayList ();
431 resource_writers.Add (writer);
433 // The data is filled out later
434 if (resources != null) {
435 MonoResource[] new_r = new MonoResource [resources.Length + 1];
436 System.Array.Copy(resources, new_r, resources.Length);
439 resources = new MonoResource [1];
441 int p = resources.Length - 1;
442 resources [p].name = name;
443 resources [p].attrs = attribute;
448 public IResourceWriter DefineResource (string name, string description)
450 return DefineResource (name, description, ResourceAttributes.Public);
454 public void DefineUnmanagedResource (byte[] resource)
456 if (resource == null)
457 throw new ArgumentNullException ("resource");
459 throw new NotImplementedException ();
463 public void DefineUnmanagedResource (string resourceFileName)
465 if (resourceFileName == null)
466 throw new ArgumentNullException ("resourceFileName");
467 if (resourceFileName == String.Empty)
468 throw new ArgumentException ("resourceFileName");
469 if (!File.Exists (resourceFileName) || Directory.Exists (resourceFileName))
470 throw new FileNotFoundException ("File '" + resourceFileName + "' does not exists or is a directory.");
472 throw new NotImplementedException ();
476 public void SetSymCustomAttribute (string name, byte[] data)
478 throw new NotImplementedException ();
482 public void SetUserEntryPoint (MethodInfo entryPoint)
484 if (entryPoint == null)
485 throw new ArgumentNullException ("entryPoint");
486 if (entryPoint.DeclaringType.Module != this)
487 throw new InvalidOperationException ("entryPoint is not contained in this module");
488 throw new NotImplementedException ();
491 public MethodToken GetMethodToken (MethodInfo method)
494 throw new ArgumentNullException ("method");
495 if (method.DeclaringType.Module != this)
496 throw new InvalidOperationException ("The method is not in this module");
497 return new MethodToken (GetToken (method));
500 public MethodToken GetArrayMethodToken (Type arrayClass, string methodName, CallingConventions callingConvention, Type returnType, Type[] parameterTypes)
502 return GetMethodToken (GetArrayMethod (arrayClass, methodName, callingConvention, returnType, parameterTypes));
506 public MethodToken GetConstructorToken (ConstructorInfo con)
509 throw new ArgumentNullException ("con");
510 return new MethodToken (GetToken (con));
513 public FieldToken GetFieldToken (FieldInfo field)
516 throw new ArgumentNullException ("field");
517 if (field.DeclaringType.Module != this)
518 throw new InvalidOperationException ("The method is not in this module");
519 return new FieldToken (GetToken (field));
523 public SignatureToken GetSignatureToken (byte[] sigBytes, int sigLength)
525 throw new NotImplementedException ();
528 public SignatureToken GetSignatureToken (SignatureHelper sigHelper)
530 if (sigHelper == null)
531 throw new ArgumentNullException ("sigHelper");
532 return new SignatureToken (GetToken (sigHelper));
535 public StringToken GetStringConstant (string str)
538 throw new ArgumentNullException ("str");
539 return new StringToken (GetToken (str));
542 public TypeToken GetTypeToken (Type type)
545 throw new ArgumentNullException ("type");
547 throw new ArgumentException ("type can't be a byref type", "type");
548 if (!IsTransient () && (type.Module is ModuleBuilder) && ((ModuleBuilder)type.Module).IsTransient ())
549 throw new InvalidOperationException ("a non-transient module can't reference a transient module");
550 return new TypeToken (GetToken (type));
553 public TypeToken GetTypeToken (string type)
555 return GetTypeToken (GetType (name));
558 [MethodImplAttribute(MethodImplOptions.InternalCall)]
559 private static extern int getUSIndex (ModuleBuilder mb, string str);
561 [MethodImplAttribute(MethodImplOptions.InternalCall)]
562 private static extern int getToken (ModuleBuilder mb, object obj);
564 [MethodImplAttribute(MethodImplOptions.InternalCall)]
565 private static extern int getMethodToken (ModuleBuilder mb, MethodInfo method,
566 Type[] opt_param_types);
568 internal int GetToken (string str) {
569 if (us_string_cache.Contains (str))
570 return (int)us_string_cache [str];
571 int result = getUSIndex (this, str);
572 us_string_cache [str] = result;
576 internal int GetToken (MemberInfo member) {
577 return getToken (this, member);
580 internal int GetToken (MethodInfo method, Type[] opt_param_types) {
581 return getMethodToken (this, method, opt_param_types);
584 internal int GetToken (SignatureHelper helper) {
585 return getToken (this, helper);
588 internal TokenGenerator GetTokenGenerator () {
589 if (token_gen == null)
590 token_gen = new ModuleBuilderTokenGenerator (this);
594 [MethodImplAttribute(MethodImplOptions.InternalCall)]
595 private static extern void build_metadata (ModuleBuilder mb);
597 [MethodImplAttribute(MethodImplOptions.InternalCall)]
598 private extern void WriteToFile (IntPtr handle);
600 internal void Save ()
602 if (transient && !is_main)
606 for (int i = 0; i < num_types; ++i)
607 if (!types [i].is_created)
608 throw new NotSupportedException ("Type '" + types [i].FullName + "' was not completed.");
611 if ((global_type != null) && (global_type_created == null))
612 global_type_created = global_type.CreateType ();
614 if (resource_writers != null) {
615 for (int i = 0; i < resource_writers.Count; ++i) {
616 ResourceWriter writer = (ResourceWriter)resource_writers [i];
618 MemoryStream stream = (MemoryStream)writer.Stream;
619 resources [i].data = new byte [stream.Length];
620 stream.Seek (0, SeekOrigin.Begin);
621 stream.Read (resources [i].data, 0, (int)stream.Length);
625 build_metadata (this);
627 string fileName = fqname;
628 if (assemblyb.AssemblyDir != null)
629 fileName = Path.Combine (assemblyb.AssemblyDir, fileName);
631 using (FileStream file = new FileStream (fileName, FileMode.Create, FileAccess.Write))
632 WriteToFile (file.Handle);
635 // The constant 0x80000000 is internal to Mono, it means `make executable'
637 File.SetAttributes (fileName, (FileAttributes) (unchecked ((int) 0x80000000)));
640 internal string FileName {
646 internal bool IsMain {
652 internal void CreateGlobalType () {
653 if (global_type == null)
654 global_type = new TypeBuilder (this, 0);
657 internal static Guid Mono_GetGuid (ModuleBuilder mb)
659 return new Guid (mb.guid);
663 internal class ModuleBuilderTokenGenerator : TokenGenerator {
665 private ModuleBuilder mb;
667 public ModuleBuilderTokenGenerator (ModuleBuilder mb) {
671 public int GetToken (string str) {
672 return mb.GetToken (str);
675 public int GetToken (MemberInfo member) {
676 return mb.GetToken (member);
679 public int GetToken (MethodInfo method, Type[] opt_param_types) {
680 return mb.GetToken (method, opt_param_types);
683 public int GetToken (SignatureHelper helper) {
684 return mb.GetToken (helper);