2003-05-19 Zoltan Varga <vargaz@freemail.hu>
[mono.git] / mcs / class / corlib / System.Reflection.Emit / TypeBuilder.cs
index a85dd2cdaa6b7ddc96551050c0d0291912a45111..80ee0024804f32b9e84bc9bcada2429f0bd77449 100644 (file)
@@ -18,10 +18,12 @@ using System.Security;
 using System.Security.Permissions;
 
 namespace System.Reflection.Emit {
+
        public sealed class TypeBuilder : Type {
        private string tname;
        private string nspace;
        private Type parent;
+       private Type nesting_type;
        private Type[] interfaces;
        private MethodBuilder[] methods;
        private ConstructorBuilder[] ctors;
@@ -35,8 +37,10 @@ namespace System.Reflection.Emit {
        private ModuleBuilder pmodule;
        private int class_size;
        private PackingSize packing_size;
+       private Type created;
+       string fullname;
 
-       public const int UnspecifiedTypeSize = -1;
+       public const int UnspecifiedTypeSize = 0;
 
                protected override TypeAttributes GetAttributeFlagsImpl () {
                        return attrs;
@@ -48,11 +52,23 @@ namespace System.Reflection.Emit {
                [MethodImplAttribute(MethodImplOptions.InternalCall)]
                private extern void create_internal_class (TypeBuilder tb);
                
-               internal TypeBuilder (ModuleBuilder mb, string name, TypeAttributes attr, Type parent, Type[] interfaces) {
+               internal TypeBuilder (ModuleBuilder mb, TypeAttributes attr) {
+                       this.parent = null;
+                       this.attrs = attr;
+                       this.class_size = -1;
+                       fullname = this.tname = "<Module>";
+                       this.nspace = "";
+                       pmodule = mb;
+                       setup_internal_class (this);
+               }
+
+               internal TypeBuilder (ModuleBuilder mb, string name, TypeAttributes attr, Type parent, Type[] interfaces, PackingSize packing_size, int type_size, Type nesting_type) {
                        int sep_index;
                        this.parent = parent;
                        this.attrs = attr;
-                       packing_size = PackingSize.Unspecified;
+                       this.class_size = type_size;
+                       this.packing_size = packing_size;
+                       this.nesting_type = nesting_type;
                        sep_index = name.LastIndexOf('.');
                        if (sep_index != -1) {
                                this.tname = name.Substring (sep_index + 1);
@@ -69,40 +85,58 @@ namespace System.Reflection.Emit {
                        // skip .<Module> ?
                        table_idx = mb.get_next_table_index (this, 0x02, true);
                        setup_internal_class (this);
+                       fullname = GetFullName ();
                }
 
                public override Assembly Assembly {
                        get {return pmodule.Assembly;}
                }
-               public override string AssemblyQualifiedName {get {return null;}}
+
+               public override string AssemblyQualifiedName {
+                       get {
+                               return fullname + ", " + Assembly.GetName().FullName;
+                       }
+               }
                public override Type BaseType {
                        get {
                                return parent;
                        }
                }
-               public override Type DeclaringType {get {return null;}}
+               public override Type DeclaringType {get {return nesting_type;}}
+
+               [MonoTODO]
                public override Type UnderlyingSystemType {
                        get {
+                               // This should return the type itself for non-enum types but 
+                               // that breaks mcs.
                                if (fields != null) {
                                        foreach (FieldBuilder f in fields) {
                                                if ((f.Attributes & FieldAttributes.Static) == 0)
                                                        return f.FieldType;
                                        }
                                }
-                               throw new InvalidOperationException ();
+                               throw new InvalidOperationException ("Underlying type information on enumeration is not specified.");
                        }
                }
 
+               string GetFullName () {
+                       if (nesting_type != null)
+                               return String.Concat (nesting_type.FullName, "+", tname);
+                       if ((nspace != null) && (nspace.Length > 0))
+                               return String.Concat (nspace, ".", tname);
+                       return tname;
+               }
+       
                public override string FullName {
                        get {
-                               if ((nspace != null) && (nspace.Length > 0))
-                                       return String.Concat (nspace, ".", tname);
-                               return tname;
+                               return fullname;
                        }
                }
        
                public override Guid GUID {
-                       get {return Guid.Empty;}
+                       get {
+                           throw not_supported ();
+                       }
                }
 
                public override Module Module {
@@ -117,7 +151,10 @@ namespace System.Reflection.Emit {
                public PackingSize PackingSize {
                        get {return packing_size;}
                }
-               public override Type ReflectedType {get {return parent;}}
+               public int Size {
+                       get { return class_size; }
+               }
+               public override Type ReflectedType {get {return nesting_type;}}
                public override MemberTypes MemberType { 
                        get {return MemberTypes.TypeInfo;}
                }
@@ -127,42 +164,114 @@ namespace System.Reflection.Emit {
                        throw new NotImplementedException ();
                }
 
-               [MonoTODO]
                public void AddInterfaceImplementation( Type interfaceType) {
-                       throw new NotImplementedException ();
+                       if (interfaceType == null)
+                               throw new ArgumentNullException ("interfaceType");
+                       if (is_created)
+                               throw not_after_created ();
+
+                       if (interfaces != null) {
+                               // Check for duplicates
+                               foreach (Type t in interfaces)
+                                       if (t == interfaceType)
+                                               return;
+
+                               Type[] ifnew = new Type [interfaces.Length + 1];
+                               interfaces.CopyTo (ifnew, 0);
+                               ifnew [interfaces.Length] = interfaceType;
+                               interfaces = ifnew;
+                       } else {
+                               interfaces = new Type [1];
+                               interfaces [0] = interfaceType;
+                       }
                }
 
                [MonoTODO]
-               protected override ConstructorInfo GetConstructorImpl (BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) {
-                       throw new NotImplementedException ();
+               protected override ConstructorInfo GetConstructorImpl (BindingFlags bindingAttr, Binder binder,
+                                                                      CallingConventions callConvention, Type[] types,
+                                                                      ParameterModifier[] modifiers)
+               {
+                       if (ctors == null)
+                               return null;
+
+                       ConstructorBuilder found = null;
+                       int count = 0;
+                       
+                       foreach (ConstructorBuilder cb in ctors){
+                               if (callConvention != CallingConventions.Any && cb.CallingConvention != callConvention)
+                                       continue;
+                               found = cb;
+                               count++;
+                       }
+
+                       if (count == 0)
+                               return null;
+                       if (types == null){
+                               if (count > 1)
+                                       throw new AmbiguousMatchException ();
+                               return found;
+                       }
+                       MethodBase[] match = new MethodBase [count];
+                       if (count == 1)
+                               match [0] = found;
+                       else {
+                               count = 0;
+                               foreach (ConstructorInfo m in ctors) {
+                                       if (callConvention != CallingConventions.Any && m.CallingConvention != callConvention)
+                                               continue;
+                                       match [count++] = m;
+                               }
+                       }
+                       if (binder == null)
+                               binder = Binder.DefaultBinder;
+                       return (ConstructorInfo)binder.SelectMethod (bindingAttr, match, types, modifiers);
                }
 
-               public override bool IsDefined( Type attributeType, bool inherit) {
-                       return false;
+               public override bool IsDefined( Type attributeType, bool inherit)
+               {
+                       throw not_supported ();
                }
-               public override object[] GetCustomAttributes(bool inherit) {
-                       return null;
+               
+               public override object[] GetCustomAttributes(bool inherit)
+               {
+                       throw not_supported ();
                }
-               public override object[] GetCustomAttributes(Type attributeType, bool inherit) {
-                       return null;
+               
+               public override object[] GetCustomAttributes(Type attributeType, bool inherit)
+               {
+                       throw not_supported ();
                }
 
-               [MonoTODO]
                public TypeBuilder DefineNestedType (string name) {
-                       // FIXME: LAMESPEC: what other attributes should we use here as default?
-                       return DefineNestedType (name, TypeAttributes.Public, typeof(object), null);
+                       return DefineNestedType (name, TypeAttributes.NestedPrivate, pmodule.assemblyb.corlib_object_type, null);
                }
 
                public TypeBuilder DefineNestedType (string name, TypeAttributes attr) {
-                       return DefineNestedType (name, attr, typeof(object), null);
+                       return DefineNestedType (name, attr, pmodule.assemblyb.corlib_object_type, null);
                }
 
                public TypeBuilder DefineNestedType (string name, TypeAttributes attr, Type parent) {
                        return DefineNestedType (name, attr, parent, null);
                }
 
-               public TypeBuilder DefineNestedType (string name, TypeAttributes attr, Type parent, Type[] interfaces) {
-                       TypeBuilder res = new TypeBuilder (pmodule, name, attr, parent, interfaces);
+               private TypeBuilder DefineNestedType (string name, TypeAttributes attr, Type parent, Type[] interfaces,
+                                                     PackingSize packsize, int typesize)
+               {
+                       check_name ("name", name);
+                       // Visibility must be NestedXXX
+                       /* This breaks mcs
+                       if (((attrs & TypeAttributes.VisibilityMask) == TypeAttributes.Public) ||
+                               ((attrs & TypeAttributes.VisibilityMask) == TypeAttributes.NotPublic))
+                               throw new ArgumentException ("attr", "Bad type flags for nested type.");
+                       */
+                       if (interfaces != null)
+                               foreach (Type iface in interfaces)
+                                       if (iface == null)
+                                               throw new ArgumentNullException ("interfaces");
+
+                       TypeBuilder res = new TypeBuilder (pmodule, name, attr, parent, interfaces, packsize, typesize, this);
+                       res.fullname = res.GetFullName ();
+                       pmodule.RegisterTypeName (res, res.fullname);
                        if (subtypes != null) {
                                TypeBuilder[] new_types = new TypeBuilder [subtypes.Length + 1];
                                System.Array.Copy (subtypes, new_types, subtypes.Length);
@@ -175,19 +284,22 @@ namespace System.Reflection.Emit {
                        return res;
                }
 
-               public TypeBuilder DefineNestedType (string name, TypeAttributes attr, Type parent, int typesize) {
-                       return DefineNestedType (name, attr, parent, null);
+               public TypeBuilder DefineNestedType (string name, TypeAttributes attr, Type parent, Type[] interfaces) {
+                       return DefineNestedType (name, attr, parent, interfaces, PackingSize.Unspecified, UnspecifiedTypeSize);
                }
 
-               public TypeBuilder DefineNestedType (string name, TypeAttributes attr, Type parent, PackingSize packsize) {
-                       return DefineNestedType (name, attr, parent, null);
+               public TypeBuilder DefineNestedType (string name, TypeAttributes attr, Type parent, int typesize) {
+                       return DefineNestedType (name, attr, parent, null, PackingSize.Unspecified, typesize);
                }
 
-               public TypeBuilder DefineNestedType (string name, TypeAttributes attr, Type parent, PackingSize packsize, int typesize) {
-                       return DefineNestedType (name, attr, parent, null);
+               public TypeBuilder DefineNestedType (string name, TypeAttributes attr, Type parent, PackingSize packsize) {
+                       return DefineNestedType (name, attr, parent, null, packsize, UnspecifiedTypeSize);
                }
 
-               public ConstructorBuilder DefineConstructor( MethodAttributes attributes, CallingConventions callingConvention, Type[] parameterTypes) {
+               public ConstructorBuilder DefineConstructor (MethodAttributes attributes, CallingConventions callingConvention, Type[] parameterTypes)
+               {
+                       if (is_created)
+                               throw not_after_created ();
                        ConstructorBuilder cb = new ConstructorBuilder (this, attributes, callingConvention, parameterTypes);
                        if (ctors != null) {
                                ConstructorBuilder[] new_ctors = new ConstructorBuilder [ctors.Length+1];
@@ -201,8 +313,21 @@ namespace System.Reflection.Emit {
                        return cb;
                }
 
-               public ConstructorBuilder DefineDefaultConstructor( MethodAttributes attributes) {
-                       return DefineConstructor (attributes, CallingConventions.Standard, null);
+               public ConstructorBuilder DefineDefaultConstructor (MethodAttributes attributes)
+               {
+                       ConstructorBuilder cb = DefineConstructor (attributes, CallingConventions.Standard, null);
+
+                       ConstructorInfo parent_constructor = parent.GetConstructor (
+                               BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance,
+                               null, Type.EmptyTypes, null);
+
+                       ILGenerator ig = cb.GetILGenerator ();
+                       if (parent_constructor != null){
+                               ig.Emit (OpCodes.Ldarg_0);
+                               ig.Emit (OpCodes.Call, parent_constructor);
+                       }
+                       ig.Emit (OpCodes.Ret);
+                       return cb;
                }
 
                public MethodBuilder DefineMethod( string name, MethodAttributes attributes, Type returnType, Type[] parameterTypes) {
@@ -222,12 +347,32 @@ namespace System.Reflection.Emit {
                }
 
                public MethodBuilder DefineMethod( string name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes) {
+                       check_name ("name", name);
+                       if (is_created)
+                               throw not_after_created ();
+                       if (IsInterface && (
+                               !((attributes & MethodAttributes.Abstract) != 0) || 
+                               !((attributes & MethodAttributes.Virtual) != 0)))
+                               throw new ArgumentException ("attributes", "Interface method must be abstract and virtual.");
+
+                       if (returnType == null)
+                               returnType = pmodule.assemblyb.corlib_void_type;
                        MethodBuilder res = new MethodBuilder (this, name, attributes, callingConvention, returnType, parameterTypes);
                        append_method (res);
                        return res;
                }
 
                public MethodBuilder DefinePInvokeMethod (string name, string dllName, string entryName, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes, CallingConvention nativeCallConv, CharSet nativeCharSet) {
+                       check_name ("name", name);
+                       check_name ("dllName", dllName);
+                       check_name ("entryName", entryName);
+                       if ((attributes & MethodAttributes.Abstract) != 0)
+                               throw new ArgumentException ("attributes", "PInvoke methods must be static and native and cannot be abstract.");
+                       if (IsInterface)
+                               throw new ArgumentException ("PInvoke methods cannot exist on interfaces.");            
+                       if (is_created)
+                               throw not_after_created ();
+
                        MethodBuilder res = new MethodBuilder (this, name, attributes, callingConvention, returnType, parameterTypes,
                                dllName, entryName, nativeCallConv, nativeCharSet);
                        append_method (res);
@@ -240,6 +385,13 @@ namespace System.Reflection.Emit {
                }
 
                public void DefineMethodOverride( MethodInfo methodInfoBody, MethodInfo methodInfoDeclaration) {
+                       if (methodInfoBody == null)
+                               throw new ArgumentNullException ("methodInfoBody");
+                       if (methodInfoDeclaration == null)
+                               throw new ArgumentNullException ("methodInfoDeclaration");
+                       if (is_created)
+                               throw not_after_created ();
+
                        if (methodInfoBody is MethodBuilder) {
                                MethodBuilder mb = (MethodBuilder)methodInfoBody;
                                mb.set_override (methodInfoDeclaration);
@@ -247,6 +399,12 @@ namespace System.Reflection.Emit {
                }
 
                public FieldBuilder DefineField( string fieldName, Type type, FieldAttributes attributes) {
+                       check_name ("fieldName", fieldName);
+                       if (type == typeof (void))
+                               throw new ArgumentException ("type",  "Bad field type in defining field.");
+                       if (is_created)
+                               throw not_after_created ();
+
                        FieldBuilder res = new FieldBuilder (this, fieldName, type, attributes);
                        if (fields != null) {
                                FieldBuilder[] new_fields = new FieldBuilder [fields.Length+1];
@@ -262,6 +420,14 @@ namespace System.Reflection.Emit {
                }
 
                public PropertyBuilder DefineProperty( string name, PropertyAttributes attributes, Type returnType, Type[] parameterTypes) {
+                       check_name ("name", name);
+                       if (parameterTypes != null)
+                               foreach (Type param in parameterTypes)
+                                       if (param == null)
+                                               throw new ArgumentNullException ("parameterTypes");
+                       if (is_created)
+                               throw not_after_created ();
+
                        PropertyBuilder res = new PropertyBuilder (this, name, attributes, returnType, parameterTypes);
 
                        if (properties != null) {
@@ -278,24 +444,44 @@ namespace System.Reflection.Emit {
 
                [MonoTODO]
                public ConstructorBuilder DefineTypeInitializer() {
+                       if (is_created)
+                               throw not_after_created ();
+
                        throw new NotImplementedException ();
                }
 
+               [MethodImplAttribute(MethodImplOptions.InternalCall)]
+               private extern Type create_runtime_class (TypeBuilder tb);
+               
                public Type CreateType() {
+                       /* handle nesting_type */
+                       if (is_created)
+                               throw not_after_created ();
                        if (methods != null) {
                                foreach (MethodBuilder method in methods) {
                                        method.fixup ();
                                }
                        }
-                       if (ctors != null) {
-                               foreach (ConstructorBuilder ctor in ctors) {
+
+                       //
+                       // On classes, define a default constructor if not provided
+                       //
+                       if (!(IsInterface || IsValueType) && (ctors == null) && (tname != "<Module>"))
+                               DefineDefaultConstructor (MethodAttributes.Public);
+
+                       if (ctors != null){
+                               foreach (ConstructorBuilder ctor in ctors) 
                                        ctor.fixup ();
-                               }
                        }
+                       
+                       created = create_runtime_class (this);
+                       if (created != null)
+                               return created;
                        return this;
                }
 
-               public override ConstructorInfo[] GetConstructors (BindingFlags bindingAttr) {
+               public override ConstructorInfo[] GetConstructors (BindingFlags bindingAttr)
+               {
                        if (ctors == null)
                                return new ConstructorInfo [0];
                        ArrayList l = new ArrayList ();
@@ -331,21 +517,22 @@ namespace System.Reflection.Emit {
                        return result;
                }
 
-               public override Type GetElementType () { return null; }
+               public override Type GetElementType () { 
+                       throw not_supported ();
+               }
 
-               [MonoTODO]
                public override EventInfo GetEvent (string name, BindingFlags bindingAttr) {
-                       throw new NotImplementedException ();
+                       throw not_supported ();
                }
 
                public override EventInfo[] GetEvents (BindingFlags bindingAttr) {
+                       // FIXME: Under MS.NET, this throws a NotImplementedException
+                       // But mcs calls this method. How can that be?
                        return new EventInfo [0];
                }
 
-               [MonoTODO]
                public override FieldInfo GetField( string name, BindingFlags bindingAttr) {
-                       //FIXME
-                       throw new NotImplementedException ();
+                       throw not_supported ();
                }
 
                public override FieldInfo[] GetFields (BindingFlags bindingAttr) {
@@ -384,9 +571,8 @@ namespace System.Reflection.Emit {
                        return result;
                }
 
-               [MonoTODO]
                public override Type GetInterface (string name, bool ignoreCase) {
-                       throw new NotImplementedException ();
+                       throw not_supported ();
                }
                
                public override Type[] GetInterfaces () {
@@ -399,10 +585,13 @@ namespace System.Reflection.Emit {
                        }
                }
 
-               [MonoTODO]
-               public override MemberInfo[] GetMembers( BindingFlags bindingAttr) {
-                       // FIXME
-                       throw new NotImplementedException ();
+               public override MemberInfo[] GetMember (string name, MemberTypes type,
+                                                                                               BindingFlags bindingAttr) {
+                       throw not_supported ();
+               }
+
+               public override MemberInfo[] GetMembers (BindingFlags bindingAttr) {
+                       throw not_supported ();
                }
 
                public override MethodInfo[] GetMethods (BindingFlags bindingAttr) {
@@ -441,22 +630,36 @@ namespace System.Reflection.Emit {
                        return result;
                }
 
-               [MonoTODO]
                protected override MethodInfo GetMethodImpl( string name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) {
-                       // FIXME
-                       throw new NotImplementedException ();
+                       throw not_supported ();
                }
                
-               [MonoTODO]
                public override Type GetNestedType( string name, BindingFlags bindingAttr) {
-                       // FIXME
-                       throw new NotImplementedException ();
+                       throw not_supported ();
                }
 
-               [MonoTODO]
                public override Type[] GetNestedTypes (BindingFlags bindingAttr) {
-                       // FIXME
-                       throw new NotImplementedException ();
+                       bool match;
+                       ArrayList result = new ArrayList ();
+               
+                       if (subtypes == null)
+                               return Type.EmptyTypes;
+                       foreach (TypeBuilder t in subtypes) {
+                               match = false;
+                               if ((t.attrs & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPublic) {
+                                       if ((bindingAttr & BindingFlags.Public) != 0)
+                                               match = true;
+                               } else {
+                                       if ((bindingAttr & BindingFlags.NonPublic) != 0)
+                                               match = true;
+                               }
+                               if (!match)
+                                       continue;
+                               result.Add (t);
+                       }
+                       Type[] r = new Type [result.Count];
+                       result.CopyTo (r);
+                       return r;
                }
 
                public override PropertyInfo[] GetProperties( BindingFlags bindingAttr) {
@@ -501,25 +704,23 @@ namespace System.Reflection.Emit {
                        return result;
                }
                
-               [MonoTODO]
                protected override PropertyInfo GetPropertyImpl( string name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers) {
-                       // FIXME
-                       throw new NotImplementedException ();
+                       throw not_supported ();
                }
 
                protected override bool HasElementTypeImpl () {
-                       return IsArrayImpl() || IsByRefImpl() || IsPointerImpl ();
+                       // According to the MSDN docs, this is supported for TypeBuilders,
+                       // but in reality, it is not
+                       throw not_supported ();
+                       //                      return IsArrayImpl() || IsByRefImpl() || IsPointerImpl ();
                }
 
-               [MonoTODO]
                public override object InvokeMember( string name, BindingFlags invokeAttr, Binder binder, object target, object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] namedParameters) {
-                       // FIXME
-                       throw new NotImplementedException ();
+                       throw not_supported ();
                }
 
                protected override bool IsArrayImpl () {
-                       // FIXME
-                       return false;
+                       return type_is_subtype_of (this, typeof (System.Array), false);
                }
                protected override bool IsByRefImpl () {
                        // FIXME
@@ -537,36 +738,21 @@ namespace System.Reflection.Emit {
                        return false;
                }
                protected override bool IsValueTypeImpl () {
-                       // test this one
-                       return type_is_subtype_of (this, typeof (System.ValueType), false);
+                       return ((type_is_subtype_of (this, pmodule.assemblyb.corlib_value_type, false) || type_is_subtype_of (this, typeof(System.ValueType), false)) &&
+                               this != pmodule.assemblyb.corlib_value_type &&
+                               this != pmodule.assemblyb.corlib_enum_type);
                }
                
-               public override RuntimeTypeHandle TypeHandle { get { return _impl; } }
-
-               private static int decode_len (byte[] data, int pos, out int rpos) {
-                       int len = 0;
-                       if ((data [pos] & 0x80) == 0) {
-                               len = (int)(data [pos++] & 0x7f);
-                       } else if ((data [pos] & 0x40) == 0) {
-                               len = ((data [pos] & 0x3f) << 8) + data [pos + 1];
-                               pos += 2;
-                       } else {
-                               len = ((data [pos] & 0x1f) << 24) + (data [pos + 1] << 16) + (data [pos + 2] << 8) + data [pos + 3];
-                               pos += 4;
-                       }
-                       rpos = pos;
-                       return len;
-               }
-
-               private static string string_from_bytes (byte[] data, int pos, int len) {
-                       char[] chars = new char [len];
-                       // FIXME: use a utf8 decoder here
-                       for (int i = 0; i < len; ++i)
-                               chars [i] = (char)data [pos + i];
-                       return new String (chars);
+               public override RuntimeTypeHandle TypeHandle { 
+                       get { 
+                               throw not_supported (); 
+                       } 
                }
 
                public void SetCustomAttribute( CustomAttributeBuilder customBuilder) {
+                       if (customBuilder == null)
+                               throw new ArgumentNullException ("customBuilder");
+
                        string attrname = customBuilder.Ctor.ReflectedType.FullName;
                        if (attrname == "System.Runtime.InteropServices.StructLayoutAttribute") {
                                byte[] data = customBuilder.Data;
@@ -595,9 +781,10 @@ namespace System.Reflection.Emit {
                                int nnamed = (int)data [pos++];
                                nnamed |= ((int)data [pos++]) << 8;
                                for (int i = 0; i < nnamed; ++i) {
+                                       byte named_type = data [pos++];
                                        byte type = data [pos++];
-                                       int len = decode_len (data, pos, out pos);
-                                       string named_name = string_from_bytes (data, pos, len);
+                                       int len = CustomAttributeBuilder.decode_len (data, pos, out pos);
+                                       string named_name = CustomAttributeBuilder.string_from_bytes (data, pos, len);
                                        pos += len;
                                        /* all the fields are integers in StructLayout */
                                        int value = (int)data [pos++];
@@ -631,6 +818,9 @@ namespace System.Reflection.Emit {
                                        }
                                }
                                return;
+                       } else if (attrname == "System.SerializableAttribute") {
+                               attrs |= TypeAttributes.Serializable;
+                               return;
                        }
                        if (cattrs != null) {
                                CustomAttributeBuilder[] new_array = new CustomAttributeBuilder [cattrs.Length + 1];
@@ -647,6 +837,12 @@ namespace System.Reflection.Emit {
                }
 
                public EventBuilder DefineEvent( string name, EventAttributes attributes, Type eventtype) {
+                       check_name ("name", name);
+                       if (eventtype == null)
+                               throw new ArgumentNullException ("eventtype");
+                       if (is_created)
+                               throw not_after_created ();
+
                        EventBuilder res = new EventBuilder (this, name, attributes, eventtype);
                        if (events != null) {
                                EventBuilder[] new_events = new EventBuilder [events.Length+1];
@@ -663,11 +859,17 @@ namespace System.Reflection.Emit {
                static int InitializedDataCount = 0;
                
                public FieldBuilder DefineInitializedData( string name, byte[] data, FieldAttributes attributes) {
-                       TypeBuilder datablobtype = pmodule.DefineType ("$ArrayType$"+InitializedDataCount.ToString(),
-                               TypeAttributes.Public|TypeAttributes.ExplicitLayout|TypeAttributes.Sealed,
-                               typeof (System.ValueType), PackingSize.Size1, data.Length);
-                       datablobtype.packing_size = PackingSize.Size1;
-                       datablobtype.class_size = data.Length;
+                       check_name ("name", name);
+                       if (data == null)
+                               throw new ArgumentNullException ("data");
+                       if ((data.Length == 0) || (data.Length > 0x3f0000))
+                               throw new ArgumentException ("data", "Data size must be > 0 and < 0x3f0000");
+                       if (is_created)
+                               throw not_after_created ();
+
+                       TypeBuilder datablobtype = DefineNestedType ("$ArrayType$"+InitializedDataCount.ToString(),
+                               TypeAttributes.NestedPrivate|TypeAttributes.ExplicitLayout|TypeAttributes.Sealed,
+                               pmodule.assemblyb.corlib_value_type, null, PackingSize.Size1, data.Length);
                        datablobtype.CreateType ();
                        FieldBuilder res = DefineField (name, datablobtype, attributes|FieldAttributes.Assembly|FieldAttributes.Static|FieldAttributes.HasFieldRVA);
                        res.SetRVAData (data);
@@ -677,15 +879,64 @@ namespace System.Reflection.Emit {
 
                [MonoTODO]
                public FieldBuilder DefineUninitializedData( string name, int size, FieldAttributes attributes) {
+                       check_name ("name", name);
+                       if ((size <= 0) || (size > 0x3f0000))
+                               throw new ArgumentException ("data", "Data size must be > 0 and < 0x3f0000");
+                       if (is_created)
+                               throw not_after_created ();
+
                        throw new NotImplementedException ();
                }
 
+               public TypeToken TypeToken {
+                       get {
+                               return new TypeToken (0x02000000 | table_idx);
+                       }
+               }
                public void SetParent (Type parentType) {
+                       if (parentType == null)
+                               throw new ArgumentNullException ("parentType");
+                       if (is_created)
+                               throw not_after_created ();
+
                        parent = parentType;
                }
                internal int get_next_table_index (object obj, int table, bool inc) {
                        return pmodule.get_next_table_index (obj, table, inc);
                }
 
+               public override InterfaceMapping GetInterfaceMap (Type interfaceType)
+               {
+                       if (created == null)
+                               throw new NotSupportedException ("This method is not implemented for incomplete types.");
+
+                       return created.GetInterfaceMap (interfaceType);
+               }
+
+               internal bool is_created {
+                       get {
+                               return created != null;
+                       }
+               }
+
+               private Exception not_supported ()
+               {
+                       return new NotSupportedException ("The invoked member is not supported in a dynamic module.");
+               }
+
+               private Exception not_after_created ()
+               {
+                       return new InvalidOperationException ("Unable to change after type has been created.");
+               }
+
+               private void check_name (string argName, string name)
+               {
+                       if (name == null)
+                               throw new ArgumentNullException (argName);
+                       if (name == "")
+                               throw new ArgumentException (argName, "Empty name is not legal.");
+                       if (name.IndexOf ((char)0) != -1)
+                               throw new ArgumentException (argName, "Illegal name.");
+               }
        }
 }