2 // System.Reflection.Emit/TypeBuilder.cs
5 // Paolo Molaro (lupus@ximian.com)
7 // (C) 2001 Ximian, Inc. http://www.ximian.com
11 using System.Reflection;
12 using System.Reflection.Emit;
13 using System.Runtime.CompilerServices;
14 using System.Runtime.InteropServices;
15 using System.Globalization;
16 using System.Collections;
17 using System.Security;
18 using System.Security.Permissions;
20 namespace System.Reflection.Emit {
21 public sealed class TypeBuilder : Type {
23 private string nspace;
25 private Type nesting_type;
26 private Type[] interfaces;
27 private MethodBuilder[] methods;
28 private ConstructorBuilder[] ctors;
29 private PropertyBuilder[] properties;
30 private FieldBuilder[] fields;
31 private EventBuilder[] events;
32 private CustomAttributeBuilder[] cattrs;
33 internal TypeBuilder[] subtypes;
34 private TypeAttributes attrs;
35 private int table_idx;
36 private ModuleBuilder pmodule;
37 private int class_size;
38 private PackingSize packing_size;
42 public const int UnspecifiedTypeSize = 0;
44 protected override TypeAttributes GetAttributeFlagsImpl () {
48 [MethodImplAttribute(MethodImplOptions.InternalCall)]
49 private extern void setup_internal_class (TypeBuilder tb);
51 [MethodImplAttribute(MethodImplOptions.InternalCall)]
52 private extern void create_internal_class (TypeBuilder tb);
54 internal TypeBuilder (ModuleBuilder mb, TypeAttributes attr) {
58 fullname = this.tname = "<Module>";
61 setup_internal_class (this);
64 internal TypeBuilder (ModuleBuilder mb, string name, TypeAttributes attr, Type parent, Type[] interfaces, PackingSize packing_size, int type_size) {
68 this.class_size = type_size;
69 this.packing_size = packing_size;
70 sep_index = name.LastIndexOf('.');
71 if (sep_index != -1) {
72 this.tname = name.Substring (sep_index + 1);
73 this.nspace = name.Substring (0, sep_index);
78 if (interfaces != null) {
79 this.interfaces = new Type[interfaces.Length];
80 System.Array.Copy (interfaces, this.interfaces, interfaces.Length);
84 table_idx = mb.get_next_table_index (this, 0x02, true);
85 setup_internal_class (this);
86 fullname = GetFullName ();
89 public override Assembly Assembly {
90 get {return pmodule.Assembly;}
92 public override string AssemblyQualifiedName {
94 return fullname + ", " + Assembly.GetName().FullName;
97 public override Type BaseType {
102 public override Type DeclaringType {get {return nesting_type;}}
105 public override Type UnderlyingSystemType {
107 // This should return the type itself for non-enum types but
109 if (fields != null) {
110 foreach (FieldBuilder f in fields) {
111 if ((f.Attributes & FieldAttributes.Static) == 0)
115 throw new InvalidOperationException ("Underlying type information on enumeration is not specified.");
119 string GetFullName () {
120 if (nesting_type != null)
121 return String.Concat (nesting_type.FullName, "+", tname);
122 if ((nspace != null) && (nspace.Length > 0))
123 return String.Concat (nspace, ".", tname);
127 public override string FullName {
133 public override Guid GUID {
135 throw not_supported ();
139 public override Module Module {
140 get {return pmodule;}
142 public override string Name {
145 public override string Namespace {
148 public PackingSize PackingSize {
149 get {return packing_size;}
152 get { return class_size; }
154 public override Type ReflectedType {get {return nesting_type;}}
155 public override MemberTypes MemberType {
156 get {return MemberTypes.TypeInfo;}
160 public void AddDeclarativeSecurity( SecurityAction action, PermissionSet pset) {
161 throw new NotImplementedException ();
164 public void AddInterfaceImplementation( Type interfaceType) {
165 if (interfaceType == null)
166 throw new ArgumentNullException ("interfaceType");
168 throw not_after_created ();
170 if (interfaces != null) {
171 // Check for duplicates
172 foreach (Type t in interfaces)
173 if (t == interfaceType)
176 Type[] ifnew = new Type [interfaces.Length + 1];
177 interfaces.CopyTo (ifnew, 0);
178 ifnew [interfaces.Length] = interfaceType;
181 interfaces = new Type [1];
182 interfaces [0] = interfaceType;
187 protected override ConstructorInfo GetConstructorImpl (BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) {
188 throw new NotImplementedException ();
191 public override bool IsDefined( Type attributeType, bool inherit) {
192 throw not_supported ();
194 public override object[] GetCustomAttributes(bool inherit) {
195 throw not_supported ();
197 public override object[] GetCustomAttributes(Type attributeType, bool inherit) {
198 throw not_supported ();
201 public TypeBuilder DefineNestedType (string name) {
202 return DefineNestedType (name, TypeAttributes.NestedPrivate, pmodule.assemblyb.corlib_object_type, null);
205 public TypeBuilder DefineNestedType (string name, TypeAttributes attr) {
206 return DefineNestedType (name, attr, pmodule.assemblyb.corlib_object_type, null);
209 public TypeBuilder DefineNestedType (string name, TypeAttributes attr, Type parent) {
210 return DefineNestedType (name, attr, parent, null);
213 private TypeBuilder DefineNestedType (string name, TypeAttributes attr, Type parent, Type[] interfaces, PackingSize packsize, int typesize) {
214 check_name ("name", name);
215 // Visibility must be NestedXXX
217 if (((attrs & TypeAttributes.VisibilityMask) == TypeAttributes.Public) ||
218 ((attrs & TypeAttributes.VisibilityMask) == TypeAttributes.NotPublic))
219 throw new ArgumentException ("attr", "Bad type flags for nested type.");
221 if (interfaces != null)
222 foreach (Type iface in interfaces)
224 throw new ArgumentNullException ("interfaces");
226 TypeBuilder res = new TypeBuilder (pmodule, name, attr, parent, interfaces, packsize, typesize);
227 res.nesting_type = this;
228 res.fullname = res.GetFullName ();
229 pmodule.RegisterTypeName (res, res.fullname);
230 if (subtypes != null) {
231 TypeBuilder[] new_types = new TypeBuilder [subtypes.Length + 1];
232 System.Array.Copy (subtypes, new_types, subtypes.Length);
233 new_types [subtypes.Length] = res;
234 subtypes = new_types;
236 subtypes = new TypeBuilder [1];
242 public TypeBuilder DefineNestedType (string name, TypeAttributes attr, Type parent, Type[] interfaces) {
243 return DefineNestedType (name, attr, parent, interfaces, PackingSize.Unspecified, UnspecifiedTypeSize);
246 public TypeBuilder DefineNestedType (string name, TypeAttributes attr, Type parent, int typesize) {
247 return DefineNestedType (name, attr, parent, null, PackingSize.Unspecified, typesize);
250 public TypeBuilder DefineNestedType (string name, TypeAttributes attr, Type parent, PackingSize packsize) {
251 return DefineNestedType (name, attr, parent, null, packsize, UnspecifiedTypeSize);
254 public ConstructorBuilder DefineConstructor( MethodAttributes attributes, CallingConventions callingConvention, Type[] parameterTypes) {
256 throw not_after_created ();
257 ConstructorBuilder cb = new ConstructorBuilder (this, attributes, callingConvention, parameterTypes);
259 ConstructorBuilder[] new_ctors = new ConstructorBuilder [ctors.Length+1];
260 System.Array.Copy (ctors, new_ctors, ctors.Length);
261 new_ctors [ctors.Length] = cb;
264 ctors = new ConstructorBuilder [1];
270 public ConstructorBuilder DefineDefaultConstructor( MethodAttributes attributes) {
271 return DefineConstructor (attributes, CallingConventions.Standard, null);
274 public MethodBuilder DefineMethod( string name, MethodAttributes attributes, Type returnType, Type[] parameterTypes) {
275 return DefineMethod (name, attributes, CallingConventions.Standard, returnType, parameterTypes);
278 private void append_method (MethodBuilder mb) {
279 if (methods != null) {
280 MethodBuilder[] new_methods = new MethodBuilder [methods.Length+1];
281 System.Array.Copy (methods, new_methods, methods.Length);
282 new_methods [methods.Length] = mb;
283 methods = new_methods;
285 methods = new MethodBuilder [1];
290 public MethodBuilder DefineMethod( string name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes) {
291 check_name ("name", name);
293 throw not_after_created ();
295 !((attributes & MethodAttributes.Abstract) != 0) ||
296 !((attributes & MethodAttributes.Virtual) != 0)))
297 throw new ArgumentException ("attributes", "Interface method must be abstract and virtual.");
299 MethodBuilder res = new MethodBuilder (this, name, attributes, callingConvention, returnType, parameterTypes);
304 public MethodBuilder DefinePInvokeMethod (string name, string dllName, string entryName, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes, CallingConvention nativeCallConv, CharSet nativeCharSet) {
305 check_name ("name", name);
306 check_name ("dllName", dllName);
307 check_name ("entryName", entryName);
308 if ((attributes & MethodAttributes.Abstract) != 0)
309 throw new ArgumentException ("attributes", "PInvoke methods must be static and native and cannot be abstract.");
311 throw new ArgumentException ("PInvoke methods cannot exist on interfaces.");
313 throw not_after_created ();
315 MethodBuilder res = new MethodBuilder (this, name, attributes, callingConvention, returnType, parameterTypes,
316 dllName, entryName, nativeCallConv, nativeCharSet);
321 public MethodBuilder DefinePInvokeMethod (string name, string dllName, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes, CallingConvention nativeCallConv, CharSet nativeCharSet) {
322 return DefinePInvokeMethod (name, dllName, name, attributes, callingConvention, returnType, parameterTypes,
323 nativeCallConv, nativeCharSet);
326 public void DefineMethodOverride( MethodInfo methodInfoBody, MethodInfo methodInfoDeclaration) {
327 if (methodInfoBody == null)
328 throw new ArgumentNullException ("methodInfoBody");
329 if (methodInfoDeclaration == null)
330 throw new ArgumentNullException ("methodInfoDeclaration");
332 throw not_after_created ();
334 if (methodInfoBody is MethodBuilder) {
335 MethodBuilder mb = (MethodBuilder)methodInfoBody;
336 mb.set_override (methodInfoDeclaration);
340 public FieldBuilder DefineField( string fieldName, Type type, FieldAttributes attributes) {
341 check_name ("fieldName", fieldName);
342 if (type == typeof (void))
343 throw new ArgumentException ("type", "Bad field type in defining field.");
345 throw not_after_created ();
347 FieldBuilder res = new FieldBuilder (this, fieldName, type, attributes);
348 if (fields != null) {
349 FieldBuilder[] new_fields = new FieldBuilder [fields.Length+1];
350 System.Array.Copy (fields, new_fields, fields.Length);
351 new_fields [fields.Length] = res;
354 fields = new FieldBuilder [1];
356 create_internal_class (this);
361 public PropertyBuilder DefineProperty( string name, PropertyAttributes attributes, Type returnType, Type[] parameterTypes) {
362 check_name ("name", name);
363 if (parameterTypes != null)
364 foreach (Type param in parameterTypes)
366 throw new ArgumentNullException ("parameterTypes");
368 throw not_after_created ();
370 PropertyBuilder res = new PropertyBuilder (this, name, attributes, returnType, parameterTypes);
372 if (properties != null) {
373 PropertyBuilder[] new_properties = new PropertyBuilder [properties.Length+1];
374 System.Array.Copy (properties, new_properties, properties.Length);
375 new_properties [properties.Length] = res;
376 properties = new_properties;
378 properties = new PropertyBuilder [1];
379 properties [0] = res;
385 public ConstructorBuilder DefineTypeInitializer() {
387 throw not_after_created ();
389 throw new NotImplementedException ();
392 [MethodImplAttribute(MethodImplOptions.InternalCall)]
393 private extern Type create_runtime_class (TypeBuilder tb);
395 public Type CreateType() {
396 /* handle nesting_type */
398 throw not_after_created ();
399 if (methods != null) {
400 foreach (MethodBuilder method in methods) {
405 foreach (ConstructorBuilder ctor in ctors) {
409 created = create_runtime_class (this);
415 public override ConstructorInfo[] GetConstructors (BindingFlags bindingAttr) {
417 return new ConstructorInfo [0];
418 ArrayList l = new ArrayList ();
420 MethodAttributes mattrs;
422 foreach (ConstructorBuilder c in ctors) {
424 mattrs = c.Attributes;
425 if ((mattrs & MethodAttributes.MemberAccessMask) == MethodAttributes.Public) {
426 if ((bindingAttr & BindingFlags.Public) != 0)
429 if ((bindingAttr & BindingFlags.NonPublic) != 0)
435 if ((mattrs & MethodAttributes.Static) != 0) {
436 if ((bindingAttr & BindingFlags.Static) != 0)
439 if ((bindingAttr & BindingFlags.Instance) != 0)
446 ConstructorInfo[] result = new ConstructorInfo [l.Count];
451 public override Type GetElementType () {
452 throw not_supported ();
456 public override EventInfo GetEvent (string name, BindingFlags bindingAttr) {
458 throw new ArgumentNullException ("name");
460 throw new NotImplementedException ();
463 public override EventInfo[] GetEvents (BindingFlags bindingAttr) {
464 return new EventInfo [0];
468 public override FieldInfo GetField( string name, BindingFlags bindingAttr) {
470 throw new ArgumentNullException ("name");
472 throw new NotImplementedException ();
475 public override FieldInfo[] GetFields (BindingFlags bindingAttr) {
477 return new FieldInfo [0];
478 ArrayList l = new ArrayList ();
480 FieldAttributes mattrs;
482 foreach (FieldInfo c in fields) {
484 mattrs = c.Attributes;
485 if ((mattrs & FieldAttributes.FieldAccessMask) == FieldAttributes.Public) {
486 if ((bindingAttr & BindingFlags.Public) != 0)
489 if ((bindingAttr & BindingFlags.NonPublic) != 0)
495 if ((mattrs & FieldAttributes.Static) != 0) {
496 if ((bindingAttr & BindingFlags.Static) != 0)
499 if ((bindingAttr & BindingFlags.Instance) != 0)
506 FieldInfo[] result = new FieldInfo [l.Count];
512 public override Type GetInterface (string name, bool ignoreCase) {
514 throw new ArgumentNullException ("name");
516 throw new NotImplementedException ();
519 public override Type[] GetInterfaces () {
520 if (interfaces != null) {
521 Type[] ret = new Type [interfaces.Length];
522 interfaces.CopyTo (ret, 0);
525 return Type.EmptyTypes;
530 public override MemberInfo[] GetMembers( BindingFlags bindingAttr) {
532 throw new NotImplementedException ();
535 public override MethodInfo[] GetMethods (BindingFlags bindingAttr) {
537 return new MethodInfo [0];
538 ArrayList l = new ArrayList ();
540 MethodAttributes mattrs;
542 foreach (MethodInfo c in methods) {
544 mattrs = c.Attributes;
545 if ((mattrs & MethodAttributes.MemberAccessMask) == MethodAttributes.Public) {
546 if ((bindingAttr & BindingFlags.Public) != 0)
549 if ((bindingAttr & BindingFlags.NonPublic) != 0)
555 if ((mattrs & MethodAttributes.Static) != 0) {
556 if ((bindingAttr & BindingFlags.Static) != 0)
559 if ((bindingAttr & BindingFlags.Instance) != 0)
566 MethodInfo[] result = new MethodInfo [l.Count];
572 protected override MethodInfo GetMethodImpl( string name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) {
574 throw new NotImplementedException ();
578 public override Type GetNestedType( string name, BindingFlags bindingAttr) {
580 throw new ArgumentNullException ("name");
582 throw new NotImplementedException ();
585 public override Type[] GetNestedTypes (BindingFlags bindingAttr) {
587 ArrayList result = new ArrayList ();
589 if (subtypes == null)
590 return Type.EmptyTypes;
591 foreach (TypeBuilder t in subtypes) {
593 if ((t.attrs & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPublic) {
594 if ((bindingAttr & BindingFlags.Public) != 0)
597 if ((bindingAttr & BindingFlags.NonPublic) != 0)
604 Type[] r = new Type [result.Count];
609 public override PropertyInfo[] GetProperties( BindingFlags bindingAttr) {
610 if (properties == null)
611 return new PropertyInfo [0];
612 ArrayList l = new ArrayList ();
614 MethodAttributes mattrs;
617 foreach (PropertyInfo c in properties) {
619 accessor = c.GetGetMethod (true);
620 if (accessor == null)
621 accessor = c.GetSetMethod (true);
622 if (accessor == null)
624 mattrs = accessor.Attributes;
625 if ((mattrs & MethodAttributes.MemberAccessMask) == MethodAttributes.Public) {
626 if ((bindingAttr & BindingFlags.Public) != 0)
629 if ((bindingAttr & BindingFlags.NonPublic) != 0)
635 if ((mattrs & MethodAttributes.Static) != 0) {
636 if ((bindingAttr & BindingFlags.Static) != 0)
639 if ((bindingAttr & BindingFlags.Instance) != 0)
646 PropertyInfo[] result = new PropertyInfo [l.Count];
652 protected override PropertyInfo GetPropertyImpl( string name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers) {
654 throw new NotImplementedException ();
657 protected override bool HasElementTypeImpl () {
658 // According to the MSDN docs, this is supported for TypeBuilders,
659 // but in reality, it is not
660 throw not_supported ();
661 // return IsArrayImpl() || IsByRefImpl() || IsPointerImpl ();
664 public override object InvokeMember( string name, BindingFlags invokeAttr, Binder binder, object target, object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] namedParameters) {
665 throw not_supported ();
668 protected override bool IsArrayImpl () {
669 return type_is_subtype_of (this, typeof (System.Array), false);
671 protected override bool IsByRefImpl () {
675 protected override bool IsCOMObjectImpl () {
678 protected override bool IsPointerImpl () {
682 protected override bool IsPrimitiveImpl () {
686 protected override bool IsValueTypeImpl () {
687 return ((type_is_subtype_of (this, pmodule.assemblyb.corlib_value_type, false) || type_is_subtype_of (this, typeof(System.ValueType), false)) &&
688 this != pmodule.assemblyb.corlib_value_type &&
689 this != pmodule.assemblyb.corlib_enum_type);
692 public override RuntimeTypeHandle TypeHandle {
694 throw not_supported ();
698 public void SetCustomAttribute( CustomAttributeBuilder customBuilder) {
699 if (customBuilder == null)
700 throw new ArgumentNullException ("customBuilder");
702 string attrname = customBuilder.Ctor.ReflectedType.FullName;
703 if (attrname == "System.Runtime.InteropServices.StructLayoutAttribute") {
704 byte[] data = customBuilder.Data;
705 int layout_kind; /* the (stupid) ctor takes a short or an int ... */
706 layout_kind = (int)data [2];
707 layout_kind |= ((int)data [3]) << 8;
708 attrs &= ~TypeAttributes.LayoutMask;
709 switch ((LayoutKind)layout_kind) {
710 case LayoutKind.Auto:
711 attrs |= TypeAttributes.AutoLayout;
713 case LayoutKind.Explicit:
714 attrs |= TypeAttributes.ExplicitLayout;
716 case LayoutKind.Sequential:
717 attrs |= TypeAttributes.SequentialLayout;
720 // we should ignore it since it can be any value anyway...
721 throw new Exception ("Error in customattr");
723 string first_type_name = customBuilder.Ctor.GetParameters()[0].ParameterType.FullName;
725 if (first_type_name == "System.Int16")
727 int nnamed = (int)data [pos++];
728 nnamed |= ((int)data [pos++]) << 8;
729 for (int i = 0; i < nnamed; ++i) {
730 byte named_type = data [pos++];
731 byte type = data [pos++];
732 int len = CustomAttributeBuilder.decode_len (data, pos, out pos);
733 string named_name = CustomAttributeBuilder.string_from_bytes (data, pos, len);
735 /* all the fields are integers in StructLayout */
736 int value = (int)data [pos++];
737 value |= ((int)data [pos++]) << 8;
738 value |= ((int)data [pos++]) << 16;
739 value |= ((int)data [pos++]) << 24;
740 switch (named_name) {
742 switch ((CharSet)value) {
746 case CharSet.Unicode:
747 attrs |= TypeAttributes.UnicodeClass;
750 attrs |= TypeAttributes.AutoClass;
753 break; // error out...
757 packing_size = (PackingSize)value;
763 break; // error out...
767 } else if (attrname == "System.SerializableAttribute") {
768 attrs |= TypeAttributes.Serializable;
771 if (cattrs != null) {
772 CustomAttributeBuilder[] new_array = new CustomAttributeBuilder [cattrs.Length + 1];
773 cattrs.CopyTo (new_array, 0);
774 new_array [cattrs.Length] = customBuilder;
777 cattrs = new CustomAttributeBuilder [1];
778 cattrs [0] = customBuilder;
781 public void SetCustomAttribute( ConstructorInfo con, byte[] binaryAttribute) {
782 SetCustomAttribute (new CustomAttributeBuilder (con, binaryAttribute));
785 public EventBuilder DefineEvent( string name, EventAttributes attributes, Type eventtype) {
786 check_name ("name", name);
787 if (eventtype == null)
788 throw new ArgumentNullException ("eventtype");
790 throw not_after_created ();
792 EventBuilder res = new EventBuilder (this, name, attributes, eventtype);
793 if (events != null) {
794 EventBuilder[] new_events = new EventBuilder [events.Length+1];
795 System.Array.Copy (events, new_events, events.Length);
796 new_events [events.Length] = res;
799 events = new EventBuilder [1];
805 static int InitializedDataCount = 0;
807 public FieldBuilder DefineInitializedData( string name, byte[] data, FieldAttributes attributes) {
808 check_name ("name", name);
810 throw new ArgumentNullException ("data");
811 if ((data.Length == 0) || (data.Length > 0x3f0000))
812 throw new ArgumentException ("data", "Data size must be > 0 and < 0x3f0000");
814 throw not_after_created ();
816 TypeBuilder datablobtype = DefineNestedType ("$ArrayType$"+InitializedDataCount.ToString(),
817 TypeAttributes.NestedPrivate|TypeAttributes.ExplicitLayout|TypeAttributes.Sealed,
818 pmodule.assemblyb.corlib_value_type, null, PackingSize.Size1, data.Length);
819 datablobtype.packing_size = PackingSize.Size1;
820 datablobtype.class_size = data.Length;
821 datablobtype.CreateType ();
822 FieldBuilder res = DefineField (name, datablobtype, attributes|FieldAttributes.Assembly|FieldAttributes.Static|FieldAttributes.HasFieldRVA);
823 res.SetRVAData (data);
824 InitializedDataCount++;
829 public FieldBuilder DefineUninitializedData( string name, int size, FieldAttributes attributes) {
830 check_name ("name", name);
831 if ((size <= 0) || (size > 0x3f0000))
832 throw new ArgumentException ("data", "Data size must be > 0 and < 0x3f0000");
834 throw not_after_created ();
836 throw new NotImplementedException ();
839 public TypeToken TypeToken {
841 return new TypeToken (0x02000000 | table_idx);
844 public void SetParent (Type parentType) {
845 if (parentType == null)
846 throw new ArgumentNullException ("parentType");
848 throw not_after_created ();
852 internal int get_next_table_index (object obj, int table, bool inc) {
853 return pmodule.get_next_table_index (obj, table, inc);
856 public override InterfaceMapping GetInterfaceMap (Type interfaceType)
859 throw new NotSupportedException ("This method is not implemented for incomplete types.");
861 return created.GetInterfaceMap (interfaceType);
864 internal bool is_created {
866 return created != null;
870 private Exception not_supported () {
871 return new NotSupportedException ("The invoked member is not supported in a dynamic module.");
874 private Exception not_after_created () {
875 return new InvalidOperationException ("Unable to change after type has been created.");
878 private void check_name (string argName, string name) {
880 throw new ArgumentNullException (argName);
882 throw new ArgumentException (argName, "Empty name is not legal.");
883 if (name.IndexOf ((char)0) != -1)
884 throw new ArgumentException (argName, "Illegal name.");