2009-12-09 Rodrigo Kumpera <rkumpera@novell.com>
[mono.git] / mono / metadata / reflection.c
index 5a272aa5feb87cf658313a2b819ebd1d82ad1a6f..0bb970b541e81e4bdc2af18a38235fa7ee73e93b 100644 (file)
@@ -38,6 +38,9 @@
 #include <mono/metadata/mempool-internals.h>
 #include <mono/metadata/security-core-clr.h>
 #include <mono/metadata/debug-helpers.h>
+#include <mono/utils/mono-string.h>
+#include <mono/utils/mono-error-internals.h>
+
 
 #if HAVE_SGEN_GC
 static void* reflection_info_desc = NULL;
@@ -52,6 +55,9 @@ static void* reflection_info_desc = NULL;
 #define MOVING_GC_REGISTER(addr)
 #endif
 
+static gboolean is_usertype (MonoReflectionType *ref);
+static MonoReflectionType *mono_reflection_type_resolve_user_types (MonoReflectionType *type);
+
 typedef struct {
        char *p;
        char *buf;
@@ -174,8 +180,13 @@ static void get_default_param_value_blobs (MonoMethod *method, char **blobs, gui
 static MonoObject *mono_get_object_from_blob (MonoDomain *domain, MonoType *type, const char *blob);
 static MonoReflectionType *mono_reflection_type_get_underlying_system_type (MonoReflectionType* t);
 static MonoType* mono_reflection_get_type_with_rootimage (MonoImage *rootimage, MonoImage* image, MonoTypeNameParse *info, gboolean ignorecase, gboolean *type_resolve);
-static MonoType* mono_reflection_type_get_handle (MonoReflectionType *ref);
 static MonoReflectionType* mono_reflection_type_resolve_user_types (MonoReflectionType *type);
+static gboolean is_sre_array (MonoClass *class);
+static gboolean is_sre_byref (MonoClass *class);
+static gboolean is_sre_pointer (MonoClass *class);
+static guint32 mono_image_get_methodspec_token (MonoDynamicImage *assembly, MonoMethod *method);
+static guint32 mono_image_get_inflated_method_token (MonoDynamicImage *assembly, MonoMethod *m);
+static MonoMethod * inflate_method (MonoReflectionType *type, MonoObject *obj);
 
 #define RESOLVE_TYPE(type) do { type = (void*)mono_reflection_type_resolve_user_types ((MonoReflectionType*)type); } while (0)
 #define RESOLVE_ARRAY_TYPE_ELEMENT(array, index) do {  \
@@ -912,7 +923,7 @@ method_encode_clauses (MonoImage *image, MonoDynamicImage *assembly, MonoReflect
                        clause->handler_offset = ex_block->start;
                        clause->handler_len = ex_block->len;
                        if (ex_block->extype) {
-                               clause->data.catch_class = mono_class_from_mono_type (mono_reflection_type_get_handle (ex_block->extype));
+                               clause->data.catch_class = mono_class_from_mono_type (mono_reflection_type_get_handle ((MonoReflectionType*)ex_block->extype));
                        } else {
                                if (ex_block->type == MONO_EXCEPTION_CLAUSE_FILTER)
                                        clause->data.filter_offset = ex_block->filter_offset;
@@ -1064,7 +1075,7 @@ fat_header:
                                        mono_image_add_stream_data (&assembly->code, (char*)&val, sizeof (guint32));
                                        finally_start = ex_block->start + ex_block->len;
                                        if (ex_block->extype) {
-                                               val = mono_metadata_token_from_dor (mono_image_typedef_or_ref (assembly, mono_reflection_type_get_handle (ex_block->extype)));
+                                               val = mono_metadata_token_from_dor (mono_image_typedef_or_ref (assembly, mono_reflection_type_get_handle ((MonoReflectionType*)ex_block->extype)));
                                        } else {
                                                if (ex_block->type == MONO_EXCEPTION_CLAUSE_FILTER)
                                                        val = ex_block->filter_offset;
@@ -1117,7 +1128,7 @@ lookup_custom_attr (MonoImage *image, gpointer member)
        if (!res)
                return NULL;
 
-       return g_memdup (res, sizeof (MonoCustomAttrInfo) + sizeof (MonoCustomAttrEntry) * (res->num_attrs - MONO_ZERO_LEN_ARRAY));
+       return g_memdup (res, MONO_SIZEOF_CUSTOM_ATTR_INFO + sizeof (MonoCustomAttrEntry) * res->num_attrs);
 }
 
 static gboolean
@@ -1157,7 +1168,7 @@ mono_custom_attrs_from_builders (MonoImage *alloc_img, MonoImage *image, MonoArr
        }
        count -= not_visible;
 
-       ainfo = image_g_malloc0 (alloc_img, sizeof (MonoCustomAttrInfo) + sizeof (MonoCustomAttrEntry) * (count - MONO_ZERO_LEN_ARRAY));
+       ainfo = image_g_malloc0 (alloc_img, MONO_SIZEOF_CUSTOM_ATTR_INFO + sizeof (MonoCustomAttrEntry) * count);
 
        ainfo->image = image;
        ainfo->num_attrs = count;
@@ -1389,7 +1400,7 @@ reflection_methodbuilder_from_method_builder (ReflectionMethodBuilder *rmb, Mono
        memset (rmb, 0, sizeof (ReflectionMethodBuilder));
 
        rmb->ilgen = mb->ilgen;
-       rmb->rtype = mono_reflection_type_resolve_user_types (mb->rtype);
+       rmb->rtype = mono_reflection_type_resolve_user_types ((MonoReflectionType*)mb->rtype);
        rmb->parameters = mb->parameters;
        rmb->generic_params = mb->generic_params;
        rmb->generic_container = mb->generic_container;
@@ -1611,11 +1622,12 @@ type_get_qualified_name (MonoType *type, MonoAssembly *ass) {
 }
 
 #ifndef DISABLE_REFLECTION_EMIT
+/*field_image is the image to which the eventual custom mods have been encoded against*/
 static guint32
-fieldref_encode_signature (MonoDynamicImage *assembly, MonoType *type)
+fieldref_encode_signature (MonoDynamicImage *assembly, MonoImage *field_image, MonoType *type)
 {
        SigBuffer buf;
-       guint32 idx, i;
+       guint32 idx, i, token;
 
        if (!assembly->save)
                return 0;
@@ -1624,14 +1636,22 @@ fieldref_encode_signature (MonoDynamicImage *assembly, MonoType *type)
        
        sigbuffer_add_value (&buf, 0x06);
        /* encode custom attributes before the type */
-       /* FIXME: This should probably go in encode_type () */
        if (type->num_mods) {
                for (i = 0; i < type->num_mods; ++i) {
+                       if (field_image) {
+                               MonoClass *class = mono_class_get (field_image, type->modifiers [i].token);
+                               g_assert (class);
+                               token = mono_image_typedef_or_ref (assembly, &class->byval_arg);
+                       } else {
+                               token = type->modifiers [i].token;
+                       }
+
                        if (type->modifiers [i].required)
                                sigbuffer_add_byte (&buf, MONO_TYPE_CMOD_REQD);
                        else
                                sigbuffer_add_byte (&buf, MONO_TYPE_CMOD_OPT);
-                       sigbuffer_add_value (&buf, type->modifiers [i].token);
+
+                       sigbuffer_add_value (&buf, token);
                }
        }
        encode_type (assembly, type, &buf);
@@ -1809,7 +1829,7 @@ encode_marshal_blob (MonoDynamicImage *assembly, MonoReflectionMarshal *minfo) {
                /* custom marshaler type name */
                if (minfo->marshaltype || minfo->marshaltyperef) {
                        if (minfo->marshaltyperef)
-                               str = type_get_fully_qualified_name (mono_reflection_type_get_handle (minfo->marshaltyperef));
+                               str = type_get_fully_qualified_name (mono_reflection_type_get_handle ((MonoReflectionType*)minfo->marshaltyperef));
                        else
                                str = mono_string_to_utf8 (minfo->marshaltype);
                        len = strlen (str);
@@ -2006,7 +2026,7 @@ mono_image_get_event_info (MonoReflectionEventBuilder *eb, MonoDynamicImage *ass
        values = table->values + eb->table_idx * MONO_EVENT_SIZE;
        values [MONO_EVENT_NAME] = string_heap_insert_mstring (&assembly->sheap, eb->name);
        values [MONO_EVENT_FLAGS] = eb->attrs;
-       values [MONO_EVENT_TYPE] = mono_image_typedef_or_ref (assembly, eb->type->type);
+       values [MONO_EVENT_TYPE] = mono_image_typedef_or_ref (assembly, mono_reflection_type_get_handle (eb->type));
 
        /*
         * FIXME: we still don't handle 'other' methods 
@@ -2064,7 +2084,7 @@ encode_constraints (MonoReflectionGenericParam *gparam, guint32 owner, MonoDynam
 
                values [MONO_GENPARCONSTRAINT_GENERICPAR] = owner;
                values [MONO_GENPARCONSTRAINT_CONSTRAINT] = mono_image_typedef_or_ref (
-                       assembly, gparam->base_type->type);
+                       assembly, mono_reflection_type_get_handle (gparam->base_type));
        }
 
        for (i = 0; i < num_constraints; i++) {
@@ -2076,7 +2096,7 @@ encode_constraints (MonoReflectionGenericParam *gparam, guint32 owner, MonoDynam
 
                values [MONO_GENPARCONSTRAINT_GENERICPAR] = owner;
                values [MONO_GENPARCONSTRAINT_CONSTRAINT] = mono_image_typedef_or_ref (
-                       assembly, constraint->type);
+                       assembly, mono_reflection_type_get_handle (constraint));
        }
 }
 
@@ -2113,7 +2133,7 @@ write_generic_param_entry (MonoDynamicImage *assembly, GenericParamTableEntry *e
        table_idx = table->next_idx ++;
        values = table->values + table_idx * MONO_GENERICPARAM_SIZE;
 
-       param = entry->gparam->type.type->data.generic_param;
+       param = mono_reflection_type_get_handle ((MonoReflectionType*)entry->gparam)->data.generic_param;
 
        values [MONO_GENERICPARAM_OWNER] = entry->owner;
        values [MONO_GENERICPARAM_FLAGS] = entry->gparam->attrs;
@@ -2432,7 +2452,7 @@ mono_image_get_methodref_token_for_methodbuilder (MonoDynamicImage *assembly, Mo
        */
        if ((rmb.call_conv & ~0x60) != MONO_CALL_DEFAULT && (rmb.call_conv & ~0x60) != MONO_CALL_VARARG)
                rmb.call_conv = (rmb.call_conv & 0x60) | MONO_CALL_DEFAULT;
-       token = mono_image_get_memberref_token (assembly, ((MonoReflectionTypeBuilder*)rmb.type)->type.type,
+       token = mono_image_get_memberref_token (assembly, mono_reflection_type_get_handle ((MonoReflectionType*)rmb.type),
                                        name, method_builder_encode_signature (assembly, &rmb));
 
        g_free (name);
@@ -2560,7 +2580,7 @@ mono_image_get_ctorbuilder_token (MonoDynamicImage *assembly, MonoReflectionCtor
        reflection_methodbuilder_from_ctor_builder (&rmb, mb);
 
        name = mono_string_to_utf8 (rmb.name);
-       token = mono_image_get_memberref_token (assembly, ((MonoReflectionTypeBuilder*)rmb.type)->type.type,
+       token = mono_image_get_memberref_token (assembly, mono_reflection_type_get_handle ((MonoReflectionType*)rmb.type),
                name, method_builder_encode_signature (assembly, &rmb));
 
        g_free (name);
@@ -2581,16 +2601,29 @@ is_field_on_inst (MonoClassField *field)
 static MonoType*
 get_field_on_inst_generic_type (MonoClassField *field)
 {
+       MonoClass *class, *gtd;
        MonoDynamicGenericClass *dgclass;
        int field_index;
 
        g_assert (is_field_on_inst (field));
 
        dgclass = (MonoDynamicGenericClass*)field->parent->generic_class;
-       field_index = field - dgclass->fields;
 
-       g_assert (field_index >= 0 && field_index < dgclass->count_fields);
-       return dgclass->field_generic_types [field_index];
+       if (field >= dgclass->fields && field - dgclass->fields < dgclass->count_fields) {
+               field_index = field - dgclass->fields;
+               return dgclass->field_generic_types [field_index];              
+       }
+
+       class = field->parent;
+       gtd = class->generic_class->container_class;
+
+       if (field >= class->fields && field - class->fields < class->field.count) {
+               field_index = field - class->fields;
+               return gtd->fields [field_index].type;
+       }
+
+       g_assert_not_reached ();
+       return 0;
 }
 
 #ifndef DISABLE_REFLECTION_EMIT
@@ -2618,7 +2651,7 @@ mono_image_get_fieldref_token (MonoDynamicImage *assembly, MonoReflectionField *
        }
        token = mono_image_get_memberref_token (assembly, &f->field->parent->byval_arg, 
                                                                                        mono_field_get_name (f->field),  
-                                                                                       fieldref_encode_signature (assembly, type));
+                                                                                       fieldref_encode_signature (assembly, field->parent->image, type));
        g_hash_table_insert (assembly->handleref, f, GUINT_TO_POINTER(token));
        return token;
 }
@@ -2631,13 +2664,15 @@ mono_image_get_field_on_inst_token (MonoDynamicImage *assembly, MonoReflectionFi
        MonoGenericClass *gclass;
        MonoDynamicGenericClass *dgclass;
        MonoReflectionFieldBuilder *fb = f->fb;
+       MonoType *type;
        char *name;
 
        token = GPOINTER_TO_UINT (g_hash_table_lookup (assembly->handleref, f));
        if (token)
                return token;
-       klass = mono_class_from_mono_type (f->inst->type.type);
-       gclass = f->inst->type.type->data.generic_class;
+       type = mono_reflection_type_get_handle ((MonoReflectionType*)f->inst);
+       klass = mono_class_from_mono_type (type);
+       gclass = type->data.generic_class;
        g_assert (gclass->is_dynamic);
        dgclass = (MonoDynamicGenericClass *) gclass;
 
@@ -2658,6 +2693,7 @@ mono_image_get_ctor_on_inst_token (MonoDynamicImage *assembly, MonoReflectionCto
        MonoDynamicGenericClass *dgclass;
        MonoReflectionCtorBuilder *cb = c->cb;
        ReflectionMethodBuilder rmb;
+       MonoType *type;
        char *name;
 
        /* A ctor cannot be a generic method, so we can ignore create_methodspec */
@@ -2665,8 +2701,9 @@ mono_image_get_ctor_on_inst_token (MonoDynamicImage *assembly, MonoReflectionCto
        token = GPOINTER_TO_UINT (g_hash_table_lookup (assembly->handleref, c));
        if (token)
                return token;
-       klass = mono_class_from_mono_type (c->inst->type.type);
-       gclass = c->inst->type.type->data.generic_class;
+       type = mono_reflection_type_get_handle ((MonoReflectionType*)c->inst);
+       klass = mono_class_from_mono_type (type);
+       gclass = type->data.generic_class;
        g_assert (gclass->is_dynamic);
        dgclass = (MonoDynamicGenericClass *) gclass;
 
@@ -2683,6 +2720,40 @@ mono_image_get_ctor_on_inst_token (MonoDynamicImage *assembly, MonoReflectionCto
        return token;
 }
 
+static MonoMethod*
+mono_reflection_method_on_tb_inst_get_handle (MonoReflectionMethodOnTypeBuilderInst *m)
+{
+       MonoClass *klass;
+       MonoGenericContext tmp_context;
+       MonoType **type_argv;
+       MonoGenericInst *ginst;
+       MonoMethod *method, *inflated;
+       int count, i;
+
+       method = inflate_method (m->inst, (MonoObject*)m->mb);
+
+       klass = method->klass;
+
+       if (method->is_inflated)
+               method = ((MonoMethodInflated *) method)->declaring;
+
+       count = mono_array_length (m->method_args);
+
+       type_argv = g_new0 (MonoType *, count);
+       for (i = 0; i < count; i++) {
+               MonoReflectionType *garg = mono_array_get (m->method_args, gpointer, i);
+               type_argv [i] = mono_reflection_type_get_handle (garg);
+       }
+       ginst = mono_metadata_get_generic_inst (count, type_argv);
+       g_free (type_argv);
+
+       tmp_context.class_inst = klass->generic_class ? klass->generic_class->context.class_inst : NULL;
+       tmp_context.method_inst = ginst;
+
+       inflated = mono_class_inflate_generic_method (method, &tmp_context);
+       return inflated;
+}
+
 static guint32
 mono_image_get_method_on_inst_token (MonoDynamicImage *assembly, MonoReflectionMethodOnTypeBuilderInst *m, gboolean create_methodspec)
 {
@@ -2691,17 +2762,26 @@ mono_image_get_method_on_inst_token (MonoDynamicImage *assembly, MonoReflectionM
        MonoGenericClass *gclass;
        MonoReflectionMethodBuilder *mb = m->mb;
        ReflectionMethodBuilder rmb;
+       MonoType *type;
        char *name;
 
-       if (create_methodspec && mb->generic_params)
-               // FIXME:
-               g_assert_not_reached ();
+       if (m->method_args) {
+               MonoMethod *inflated;
+
+               inflated = mono_reflection_method_on_tb_inst_get_handle (m);
+               if (create_methodspec)
+                       token = mono_image_get_methodspec_token (assembly, inflated);
+               else
+                       token = mono_image_get_inflated_method_token (assembly, inflated);
+               return token;
+       }
 
        token = GPOINTER_TO_UINT (g_hash_table_lookup (assembly->handleref, m));
        if (token)
                return token;
-       klass = mono_class_from_mono_type (m->inst->type.type);
-       gclass = m->inst->type.type->data.generic_class;
+       type = mono_reflection_type_get_handle ((MonoReflectionType*)m->inst);
+       klass = mono_class_from_mono_type (type);
+       gclass = type->data.generic_class;
        g_assert (gclass->is_dynamic);
 
        reflection_methodbuilder_from_method_builder (&rmb, mb);
@@ -2834,6 +2914,7 @@ create_generic_typespec (MonoDynamicImage *assembly, MonoReflectionTypeBuilder *
 {
        MonoDynamicTable *table;
        MonoClass *klass;
+       MonoType *type;
        guint32 *values;
        guint32 token;
        SigBuffer buf;
@@ -2844,15 +2925,15 @@ create_generic_typespec (MonoDynamicImage *assembly, MonoReflectionTypeBuilder *
         * ie. what we'd normally use as the generic type in a TypeSpec signature.
         * Because of this, we must not insert it into the `typeref' hash table.
         */
-
-       token = GPOINTER_TO_UINT (g_hash_table_lookup (assembly->typespec, tb->type.type));
+       type = mono_reflection_type_get_handle ((MonoReflectionType*)tb);
+       token = GPOINTER_TO_UINT (g_hash_table_lookup (assembly->typespec, type));
        if (token)
                return token;
 
        sigbuffer_init (&buf, 32);
 
        g_assert (tb->generic_params);
-       klass = mono_class_from_mono_type (tb->type.type);
+       klass = mono_class_from_mono_type (type);
 
        if (tb->generic_container)
                mono_reflection_create_generic_class (tb);
@@ -2869,7 +2950,7 @@ create_generic_typespec (MonoDynamicImage *assembly, MonoReflectionTypeBuilder *
 
                gparam = mono_array_get (tb->generic_params, MonoReflectionGenericParam *, i);
 
-               encode_type (assembly, gparam->type.type, &buf);
+               encode_type (assembly, mono_reflection_type_get_handle ((MonoReflectionType*)gparam), &buf);
        }
 
        table = &assembly->tables [MONO_TABLE_TYPESPEC];
@@ -2883,7 +2964,7 @@ create_generic_typespec (MonoDynamicImage *assembly, MonoReflectionTypeBuilder *
        sigbuffer_free (&buf);
 
        token = MONO_TYPEDEFORREF_TYPESPEC | (table->next_idx << MONO_TYPEDEFORREF_BITS);
-       g_hash_table_insert (assembly->typespec, tb->type.type, GUINT_TO_POINTER(token));
+       g_hash_table_insert (assembly->typespec, type, GUINT_TO_POINTER(token));
        table->next_idx ++;
        return token;
 }
@@ -2906,9 +2987,9 @@ add_custom_modifiers (MonoDynamicImage *assembly, MonoType *type, MonoArray *mod
        if (count == 0)
                return mono_metadata_type_dup (NULL, type);
 
-       len = sizeof (MonoType) + ((gint32)count - MONO_ZERO_LEN_ARRAY) * sizeof (MonoCustomMod);
+       len = MONO_SIZEOF_TYPE + ((gint32)count) * sizeof (MonoCustomMod);
        t = g_malloc (len);
-       memcpy (t, type, sizeof (MonoType));
+       memcpy (t, type, MONO_SIZEOF_TYPE);
 
        t->num_mods = count;
        pos = 0;
@@ -2946,17 +3027,17 @@ mono_image_get_generic_field_token (MonoDynamicImage *assembly, MonoReflectionFi
        if (token)
                return token;
 
-       klass = mono_class_from_mono_type (fb->typeb->type);
+       klass = mono_class_from_mono_type (mono_reflection_type_get_handle (fb->typeb));
        name = mono_string_to_utf8 (fb->name);
 
        /* fb->type does not include the custom modifiers */
        /* FIXME: We should do this in one place when a fieldbuilder is created */
        if (fb->modreq || fb->modopt) {
-               custom = add_custom_modifiers (assembly, mono_reflection_type_get_handle (fb->type), fb->modreq, fb->modopt);
-               sig = fieldref_encode_signature (assembly, custom);
+               custom = add_custom_modifiers (assembly, mono_reflection_type_get_handle ((MonoReflectionType*)fb->type), fb->modreq, fb->modopt);
+               sig = fieldref_encode_signature (assembly, NULL, custom);
                g_free (custom);
        } else {
-               sig = fieldref_encode_signature (assembly, mono_reflection_type_get_handle (fb->type));
+               sig = fieldref_encode_signature (assembly, NULL, mono_reflection_type_get_handle ((MonoReflectionType*)fb->type));
        }
 
        parent = create_generic_typespec (assembly, (MonoReflectionTypeBuilder *) fb->typeb);
@@ -3093,22 +3174,24 @@ mono_image_get_array_token (MonoDynamicImage *assembly, MonoReflectionArrayMetho
        char *name;
        MonoMethodSignature *sig;
        ArrayMethod *am;
-       
+       MonoType *mtype;
+
        name = mono_string_to_utf8 (m->name);
        nparams = mono_array_length (m->parameters);
-       sig = g_malloc0 (sizeof (MonoMethodSignature) + sizeof (MonoType*) * nparams);
+       sig = g_malloc0 (MONO_SIZEOF_METHOD_SIGNATURE + sizeof (MonoType*) * nparams);
        sig->hasthis = 1;
        sig->sentinelpos = -1;
        sig->call_convention = reflection_cc_to_file (m->call_conv);
        sig->param_count = nparams;
-       sig->ret = m->ret? m->ret->type: &mono_defaults.void_class->byval_arg;
+       sig->ret = m->ret ? mono_reflection_type_get_handle (m->ret): &mono_defaults.void_class->byval_arg;
+       mtype = mono_reflection_type_get_handle (m->parent);
        for (i = 0; i < nparams; ++i)
                sig->params [i] = mono_type_array_get_and_resolve (m->parameters, i);
 
        for (tmp = assembly->array_methods; tmp; tmp = tmp->next) {
                am = tmp->data;
                if (strcmp (name, am->name) == 0 && 
-                               mono_metadata_type_equal (am->parent, m->parent->type) &&
+                               mono_metadata_type_equal (am->parent, mtype) &&
                                mono_metadata_signature_equal (am->sig, sig)) {
                        g_free (name);
                        g_free (sig);
@@ -3119,7 +3202,7 @@ mono_image_get_array_token (MonoDynamicImage *assembly, MonoReflectionArrayMetho
        am = g_new0 (ArrayMethod, 1);
        am->name = name;
        am->sig = sig;
-       am->parent = m->parent->type;
+       am->parent = mtype;
        am->token = mono_image_get_memberref_token (assembly, am->parent, name,
                method_encode_signature (assembly, sig));
        assembly->array_methods = g_list_prepend (assembly->array_methods, am);
@@ -3155,7 +3238,7 @@ mono_image_get_type_info (MonoDomain *domain, MonoReflectionTypeBuilder *tb, Mon
        g_free (n);
        if (tb->parent && !(is_system && is_object) && 
                        !(tb->attrs & TYPE_ATTRIBUTE_INTERFACE)) { /* interfaces don't have a parent */
-               values [MONO_TYPEDEF_EXTENDS] = mono_image_typedef_or_ref (assembly, mono_reflection_type_get_handle (tb->parent));
+               values [MONO_TYPEDEF_EXTENDS] = mono_image_typedef_or_ref (assembly, mono_reflection_type_get_handle ((MonoReflectionType*)tb->parent));
        } else {
                values [MONO_TYPEDEF_EXTENDS] = 0;
        }
@@ -3187,7 +3270,7 @@ mono_image_get_type_info (MonoDomain *domain, MonoReflectionTypeBuilder *tb, Mon
                for (i = 0; i < mono_array_length (tb->interfaces); ++i) {
                        MonoReflectionType* iface = (MonoReflectionType*) mono_array_get (tb->interfaces, gpointer, i);
                        values [MONO_INTERFACEIMPL_CLASS] = tb->table_idx;
-                       values [MONO_INTERFACEIMPL_INTERFACE] = mono_image_typedef_or_ref (assembly, iface->type);
+                       values [MONO_INTERFACEIMPL_INTERFACE] = mono_image_typedef_or_ref (assembly, mono_reflection_type_get_handle (iface));
                        values += MONO_INTERFACEIMPL_SIZE;
                }
        }
@@ -3511,7 +3594,7 @@ mono_image_fill_export_table (MonoDomain *domain, MonoReflectionTypeBuilder *tb,
        MonoClass *klass;
        guint32 idx, i;
 
-       klass = mono_class_from_mono_type (tb->type.type);
+       klass = mono_class_from_mono_type (mono_reflection_type_get_handle ((MonoReflectionType*)tb));
 
        klass->type_token = mono_metadata_make_token (MONO_TABLE_TYPEDEF, tb->table_idx);
 
@@ -3668,8 +3751,8 @@ compare_genericparam (const void *a, const void *b)
 
        if ((*b_entry)->owner == (*a_entry)->owner)
                return 
-                       mono_type_get_generic_param_num ((*a_entry)->gparam->type.type) -
-                       mono_type_get_generic_param_num ((*b_entry)->gparam->type.type);
+                       mono_type_get_generic_param_num (mono_reflection_type_get_handle ((MonoReflectionType*)(*a_entry)->gparam)) -
+                       mono_type_get_generic_param_num (mono_reflection_type_get_handle ((MonoReflectionType*)(*b_entry)->gparam));
        else
                return (*a_entry)->owner - (*b_entry)->owner;
 }
@@ -4039,6 +4122,8 @@ fixup_method (MonoReflectionILGen *ilgen, gpointer value, MonoDynamicImage *asse
                                continue;
                        } else if (!strcmp (iltoken->member->vtable->klass->name, "MethodBuilder")) {
                                continue;
+                       } else if (!strcmp (iltoken->member->vtable->klass->name, "MethodOnTypeBuilderInst")) {
+                               continue;
                        } else {
                                g_assert_not_reached ();
                        }
@@ -4566,7 +4651,7 @@ mono_image_create_method_token (MonoDynamicImage *assembly, MonoObject *obj, Mon
 
                for (i = 0; i < nargs; i++) {
                        MonoReflectionType *rt = mono_array_get (opt_param_types, MonoReflectionType *, i);
-                       sig->params [old->param_count + i] = rt->type;
+                       sig->params [old->param_count + i] = mono_reflection_type_get_handle (rt);
                }
 
                parent = mono_image_typedef_or_ref (assembly, &method->klass->byval_arg);
@@ -4661,18 +4746,18 @@ mono_image_create_token (MonoDynamicImage *assembly, MonoObject *obj,
                MonoReflectionTypeBuilder *tb = (MonoReflectionTypeBuilder *)obj;
                token = tb->table_idx | MONO_TOKEN_TYPE_DEF;
        } else if (strcmp (klass->name, "MonoType") == 0) {
-               MonoReflectionType *tb = (MonoReflectionType *)obj;
-               MonoClass *mc = mono_class_from_mono_type (tb->type);
+               MonoType *type = mono_reflection_type_get_handle ((MonoReflectionType *)obj);
+               MonoClass *mc = mono_class_from_mono_type (type);
                token = mono_metadata_token_from_dor (
-                       mono_image_typedef_or_ref_full (assembly, tb->type, mc->generic_container == NULL));
+                       mono_image_typedef_or_ref_full (assembly, type, mc->generic_container == NULL));
        } else if (strcmp (klass->name, "GenericTypeParameterBuilder") == 0) {
-               MonoReflectionType *tb = (MonoReflectionType *)obj;
+               MonoType *type = mono_reflection_type_get_handle ((MonoReflectionType *)obj);
                token = mono_metadata_token_from_dor (
-                       mono_image_typedef_or_ref (assembly, tb->type));
+                       mono_image_typedef_or_ref (assembly, type));
        } else if (strcmp (klass->name, "MonoGenericClass") == 0) {
-               MonoReflectionType *tb = (MonoReflectionType *)obj;
+               MonoType *type = mono_reflection_type_get_handle ((MonoReflectionType *)obj);
                token = mono_metadata_token_from_dor (
-                       mono_image_typedef_or_ref (assembly, tb->type));
+                       mono_image_typedef_or_ref (assembly, type));
        } else if (strcmp (klass->name, "MonoCMethod") == 0 ||
                   strcmp (klass->name, "MonoMethod") == 0 ||
                   strcmp (klass->name, "MonoGenericMethod") == 0 ||
@@ -4722,9 +4807,9 @@ mono_image_create_token (MonoDynamicImage *assembly, MonoObject *obj,
                MonoReflectionSigHelper *s = (MonoReflectionSigHelper*)obj;
                token = MONO_TOKEN_SIGNATURE | mono_image_get_sighelper_token (assembly, s);
        } else if (strcmp (klass->name, "EnumBuilder") == 0) {
-               MonoReflectionType *tb = (MonoReflectionType *)obj;
+               MonoType *type = mono_reflection_type_get_handle ((MonoReflectionType *)obj);
                token = mono_metadata_token_from_dor (
-                       mono_image_typedef_or_ref (assembly, tb->type));
+                       mono_image_typedef_or_ref (assembly, type));
        } else if (strcmp (klass->name, "FieldOnTypeBuilderInst") == 0) {
                MonoReflectionFieldOnTypeBuilderInst *f = (MonoReflectionFieldOnTypeBuilderInst*)obj;
                token = mono_image_get_field_on_inst_token (assembly, f);
@@ -4734,7 +4819,7 @@ mono_image_create_token (MonoDynamicImage *assembly, MonoObject *obj,
        } else if (strcmp (klass->name, "MethodOnTypeBuilderInst") == 0) {
                MonoReflectionMethodOnTypeBuilderInst *m = (MonoReflectionMethodOnTypeBuilderInst*)obj;
                token = mono_image_get_method_on_inst_token (assembly, m, create_methodspec);
-       } else if (strcmp (klass->name, "ArrayType") == 0) {
+       } else if (is_sre_array (klass) || is_sre_byref (klass) || is_sre_pointer (klass)) {
                MonoReflectionType *type = (MonoReflectionType *)obj;
                token = mono_metadata_token_from_dor (
                                mono_image_typedef_or_ref (assembly, mono_reflection_type_get_handle (type)));
@@ -4895,6 +4980,7 @@ mono_dynamic_image_free (MonoDynamicImage *image)
                                g_free ((char*)mono_generic_param_info (param)->name);
                                g_free (param);
                        }
+                       mono_gc_deregister_root ((char*) &entry->gparam);
                        g_free (entry);
                }
                g_ptr_array_free (di->gen_params, TRUE);
@@ -4989,6 +5075,13 @@ mono_image_basic_init (MonoReflectionAssemblyBuilder *assemblyb)
        image->initial_image = TRUE;
        assembly->assembly.aname.name = image->image.name;
        assembly->assembly.image = &image->image;
+       if (assemblyb->pktoken && assemblyb->pktoken->max_length) {
+               /* -1 to correct for the trailing NULL byte */
+               if (assemblyb->pktoken->max_length != MONO_PUBLIC_KEY_TOKEN_LENGTH - 1) {
+                       g_error ("Public key token length invalid for assembly %s: %i", assembly->assembly.aname.name, assemblyb->pktoken->max_length);
+               }
+               memcpy (&assembly->assembly.aname.public_key_token, mono_array_addr (assemblyb->pktoken, guint8, 0), assemblyb->pktoken->max_length);           
+       }
 
        mono_domain_assemblies_lock (domain);
        domain->domain_assemblies = g_slist_prepend (domain->domain_assemblies, assembly);
@@ -5842,16 +5935,24 @@ mono_image_module_basic_init (MonoReflectionModuleBuilder *moduleb)
        MonoDynamicImage *image = moduleb->dynamic_image;
        MonoReflectionAssemblyBuilder *ab = moduleb->assemblyb;
        if (!image) {
+               MonoError error;
                int module_count;
                MonoImage **new_modules;
                MonoImage *ass;
+               char *name, *fqname;
                /*
                 * FIXME: we already created an image in mono_image_basic_init (), but
                 * we don't know which module it belongs to, since that is only 
                 * determined at assembly save time.
                 */
                /*image = (MonoDynamicImage*)ab->dynamic_assembly->assembly.image; */
-               image = create_dynamic_mono_image (ab->dynamic_assembly, mono_string_to_utf8 (ab->name), mono_string_to_utf8 (moduleb->module.fqname));
+               name = mono_string_to_utf8 (ab->name);
+               fqname = mono_string_to_utf8_checked (moduleb->module.fqname, &error);
+               if (!mono_error_ok (&error)) {
+                       g_free (name);
+                       mono_error_raise_exception (&error);
+               }
+               image = create_dynamic_mono_image (ab->dynamic_assembly, name, fqname);
 
                moduleb->module.image = &image->image;
                moduleb->dynamic_image = image;
@@ -5877,6 +5978,8 @@ void
 mono_image_set_wrappers_type (MonoReflectionModuleBuilder *moduleb, MonoReflectionType *type)
 {
        MonoDynamicImage *image = moduleb->dynamic_image;
+
+       g_assert (type->type);
        image->wrappers_type = mono_class_from_mono_type (type->type);
 }
 
@@ -6090,6 +6193,9 @@ mono_generic_class_get_object (MonoDomain *domain, MonoType *geninst)
        static MonoClass *System_Reflection_MonoGenericClass;
        MonoReflectionGenericClass *res;
        MonoClass *klass, *gklass;
+       MonoGenericInst *ginst;
+       MonoArray *type_args;
+       int i;
 
        if (!System_Reflection_MonoGenericClass) {
                System_Reflection_MonoGenericClass = mono_class_from_name (
@@ -6113,6 +6219,12 @@ mono_generic_class_get_object (MonoDomain *domain, MonoType *geninst)
        g_assert (!strcmp (((MonoObject*)gklass->reflection_info)->vtable->klass->name, "TypeBuilder"));
        MONO_OBJECT_SETREF (res, generic_type, gklass->reflection_info);
 
+       ginst = klass->generic_class->context.class_inst;
+       type_args = mono_array_new (domain, mono_defaults.systemtype_class, ginst->type_argc);
+       for (i = 0; i < ginst->type_argc; ++i)
+               mono_array_setref (type_args, i, mono_type_get_object (domain, ginst->type_argv [i]));
+       MONO_OBJECT_SETREF (res, type_arguments, type_args);
+
        return res;
 }
 
@@ -6174,7 +6286,7 @@ mono_type_get_object (MonoDomain *domain, MonoType *type)
         * the MonoType from there and avoid all locking and hash table lookups.
         * 
         * We cannot do this for TypeBuilders as mono_reflection_create_runtime_class expects
-        * that the resulting object is diferent.   
+        * that the resulting object is different.   
         */
        if (type == &klass->byval_arg && !klass->image->dynamic) {
                MonoVTable *vtable = mono_class_try_get_vtable (domain, klass);
@@ -6227,7 +6339,7 @@ mono_type_get_object (MonoDomain *domain, MonoType *type)
        mono_g_hash_table_insert (domain->type_hash, type, res);
 
        if (type->type == MONO_TYPE_VOID)
-               MONO_OBJECT_SETREF (domain, typeof_void, res);
+               domain->typeof_void = (MonoObject*)res;
 
        mono_domain_unlock (domain);
        mono_loader_unlock ();
@@ -6619,7 +6731,6 @@ mono_method_body_get_object (MonoDomain *domain, MonoMethod *method)
        format = flags & METHOD_HEADER_FORMAT_MASK;
        switch (format){
        case METHOD_HEADER_TINY_FORMAT:
-       case METHOD_HEADER_TINY_FORMAT1:
                local_var_sig_token = 0;
                break;
        case METHOD_HEADER_FAT_FORMAT:
@@ -6750,7 +6861,7 @@ get_default_param_value_blobs (MonoMethod *method, char **blobs, guint32 *types)
                mono_metadata_decode_row (paramt, i - 1, param_cols, MONO_PARAM_SIZE);
                paramseq = param_cols [MONO_PARAM_SEQUENCE];
 
-               if (!param_cols [MONO_PARAM_FLAGS] & PARAM_ATTRIBUTE_HAS_DEFAULT) 
+               if (!(param_cols [MONO_PARAM_FLAGS] & PARAM_ATTRIBUTE_HAS_DEFAULT))
                        continue;
 
                crow = mono_metadata_get_constant_index (image, MONO_TOKEN_PARAM_DEF | i, crow + 1);
@@ -7161,7 +7272,7 @@ mono_reflection_get_type_internal (MonoImage *rootimage, MonoImage* image, MonoT
 
                while ((klass = mono_class_get_nested_types (parent, &iter))) {
                        if (ignorecase) {
-                               if (g_strcasecmp (klass->name, mod->data) == 0)
+                               if (mono_utf8_strcasecmp (klass->name, mod->data) == 0)
                                        break;
                        } else {
                                if (strcmp (klass->name, mod->data) == 0)
@@ -7298,7 +7409,7 @@ mono_reflection_get_type_with_rootimage (MonoImage *rootimage, MonoImage* image,
        if (info->name_space && (info->name_space [0] != '\0'))
                g_string_printf (fullName, "%s.%s", info->name_space, info->name);
        else
-               g_string_printf (fullName, info->name);
+               g_string_printf (fullName, "%s", info->name);
        for (mod = info->nested; mod; mod = mod->next)
                g_string_append_printf (fullName, "+%s", (char*)mod->data);
 
@@ -7396,8 +7507,8 @@ mono_reflection_get_token (MonoObject *obj)
                MonoReflectionTypeBuilder *tb = (MonoReflectionTypeBuilder *)obj;
                token = tb->table_idx | MONO_TOKEN_TYPE_DEF;
        } else if (strcmp (klass->name, "MonoType") == 0) {
-               MonoReflectionType *tb = (MonoReflectionType *)obj;
-               token = mono_class_from_mono_type (tb->type)->type_token;
+               MonoType *type = mono_reflection_type_get_handle ((MonoReflectionType *)obj);
+               token = mono_class_from_mono_type (type)->type_token;
        } else if (strcmp (klass->name, "MonoCMethod") == 0 ||
                   strcmp (klass->name, "MonoMethod") == 0 ||
                   strcmp (klass->name, "MonoGenericMethod") == 0 ||
@@ -7584,6 +7695,7 @@ handle_type:
                }
                val = load_cattr_value (image, &subc->byval_arg, p, end);
                obj = mono_object_new (mono_domain_get (), subc);
+               g_assert (!subc->has_references);
                memcpy ((char*)obj + sizeof (MonoObject), val, mono_class_value_size (subc, NULL));
                g_free (val);
                return obj;
@@ -7879,51 +7991,48 @@ create_custom_attr (MonoImage *image, MonoMethod *method, const guchar *data, gu
 
        return attr;
 }
-
-static MonoObject*
-create_custom_attr_data (MonoImage *image, MonoMethod *method, const guchar *data, guint32 len)
+       
+/*
+ * mono_reflection_create_custom_attr_data_args:
+ *
+ *   Create an array of typed and named arguments from the cattr blob given by DATA.
+ * TYPED_ARGS and NAMED_ARGS will contain the objects representing the arguments,
+ * NAMED_ARG_INFO will contain information about the named arguments.
+ */
+void
+mono_reflection_create_custom_attr_data_args (MonoImage *image, MonoMethod *method, const guchar *data, guint32 len, MonoArray **typed_args, MonoArray **named_args, CattrNamedArg **named_arg_info)
 {
        MonoArray *typedargs, *namedargs;
        MonoClass *attrklass;
-       static MonoMethod *ctor;
        MonoDomain *domain;
-       MonoObject *attr;
        const char *p = (const char*)data;
        const char *named;
        guint32 i, j, num_named;
-       void *params [3];
+       CattrNamedArg *arginfo = NULL;
 
        mono_class_init (method->klass);
 
-       if (!ctor)
-               ctor = mono_class_get_method_from_name (mono_defaults.customattribute_data_class, ".ctor", 3);
-
+       *typed_args = NULL;
+       *named_args = NULL;
+       *named_arg_info = NULL;
+       
        domain = mono_domain_get ();
-       if (len == 0) {
-               /* This is for Attributes with no parameters */
-               attr = mono_object_new (domain, mono_defaults.customattribute_data_class);
-               params [0] = mono_method_get_object (domain, method, NULL);
-               params [1] = params [2] = NULL;
-               mono_runtime_invoke (method, attr, params, NULL);
-               return attr;
-       }
 
        if (len < 2 || read16 (p) != 0x0001) /* Prolog */
-               return NULL;
+               return;
 
        typedargs = mono_array_new (domain, mono_get_object_class (), mono_method_signature (method)->param_count);
        
        /* skip prolog */
        p += 2;
        for (i = 0; i < mono_method_signature (method)->param_count; ++i) {
-               MonoObject *obj, *typedarg;
+               MonoObject *obj;
                void *val;
 
                val = load_cattr_value (image, mono_method_signature (method)->params [i], p, &p);
                obj = type_is_reference (mono_method_signature (method)->params [i]) ? 
                        val : mono_value_box (domain, mono_class_from_mono_type (mono_method_signature (method)->params [i]), val);
-               typedarg = create_cattr_typed_arg (mono_method_signature (method)->params [i], obj);
-               mono_array_setref (typedargs, i, typedarg);
+               mono_array_setref (typedargs, i, obj);
 
                if (!type_is_reference (mono_method_signature (method)->params [i]))
                        g_free (val);
@@ -7934,6 +8043,10 @@ create_custom_attr_data (MonoImage *image, MonoMethod *method, const guchar *dat
        namedargs = mono_array_new (domain, mono_get_object_class (), num_named);
        named += 2;
        attrklass = method->klass;
+
+       arginfo = g_new0 (CattrNamedArg, num_named);
+       *named_arg_info = arginfo;
+
        for (j = 0; j < num_named; j++) {
                gint name_len;
                char *name, named_type, data_type;
@@ -7958,36 +8071,96 @@ create_custom_attr_data (MonoImage *image, MonoMethod *method, const guchar *dat
                name [name_len] = 0;
                named += name_len;
                if (named_type == 0x53) {
-                       MonoObject *obj, *typedarg, *namedarg;
+                       MonoObject *obj;
                        MonoClassField *field = mono_class_get_field_from_name (attrklass, name);
-                       void *minfo, *val = load_cattr_value (image, field->type, named, &named);
-                       
-                       minfo = mono_field_get_object (domain, NULL, field);
+                       void *val;
+
+                       arginfo [j].type = field->type;
+                       arginfo [j].field = field;
+
+                       val = load_cattr_value (image, field->type, named, &named);
                        obj = type_is_reference (field->type) ? val : mono_value_box (domain, mono_class_from_mono_type (field->type), val);
-                       typedarg = create_cattr_typed_arg (field->type, obj);
-                       namedarg = create_cattr_named_arg (minfo, typedarg);
-                       mono_array_setref (namedargs, j, namedarg);
+                       mono_array_setref (namedargs, j, obj);
                        if (!type_is_reference (field->type))
                                g_free (val);
                } else if (named_type == 0x54) {
-                       MonoObject *obj, *typedarg, *namedarg;
+                       MonoObject *obj;
                        MonoType *prop_type;
-                       void *val, *minfo;
                        MonoProperty *prop = mono_class_get_property_from_name (attrklass, name);
+                       void *val;
 
                        prop_type = prop->get? mono_method_signature (prop->get)->ret :
                             mono_method_signature (prop->set)->params [mono_method_signature (prop->set)->param_count - 1];
-                       minfo =  mono_property_get_object (domain, NULL, prop);
+
+                       arginfo [j].type = prop_type;
+                       arginfo [j].prop = prop;
+
                        val = load_cattr_value (image, prop_type, named, &named);
                        obj = type_is_reference (prop_type) ? val : mono_value_box (domain, mono_class_from_mono_type (prop_type), val);
-                       typedarg = create_cattr_typed_arg (prop_type, obj);
-                       namedarg = create_cattr_named_arg (minfo, typedarg);
-                       mono_array_setref (namedargs, j, namedarg);
+                       mono_array_setref (namedargs, j, obj);
                        if (!type_is_reference (prop_type))
                                g_free (val);
                }
                g_free (name);
        }
+
+       *typed_args = typedargs;
+       *named_args = namedargs;
+}
+
+static MonoObject*
+create_custom_attr_data (MonoImage *image, MonoMethod *method, const guchar *data, guint32 len)
+{
+       MonoArray *typedargs, *namedargs;
+       static MonoMethod *ctor;
+       MonoDomain *domain;
+       MonoObject *attr;
+       void *params [3];
+       CattrNamedArg *arginfo;
+       int i;
+
+       mono_class_init (method->klass);
+
+       if (!ctor)
+               ctor = mono_class_get_method_from_name (mono_defaults.customattribute_data_class, ".ctor", 3);
+
+       domain = mono_domain_get ();
+       if (len == 0) {
+               /* This is for Attributes with no parameters */
+               attr = mono_object_new (domain, mono_defaults.customattribute_data_class);
+               params [0] = mono_method_get_object (domain, method, NULL);
+               params [1] = params [2] = NULL;
+               mono_runtime_invoke (method, attr, params, NULL);
+               return attr;
+       }
+
+       mono_reflection_create_custom_attr_data_args (image, method, data, len, &typedargs, &namedargs, &arginfo);
+       if (!typedargs || !namedargs)
+               return NULL;
+
+       for (i = 0; i < mono_method_signature (method)->param_count; ++i) {
+               MonoObject *obj = mono_array_get (typedargs, MonoObject*, i);
+               MonoObject *typedarg;
+
+               typedarg = create_cattr_typed_arg (mono_method_signature (method)->params [i], obj);
+               mono_array_setref (typedargs, i, typedarg);
+       }
+
+       for (i = 0; i < mono_array_length (namedargs); ++i) {
+               MonoObject *obj = mono_array_get (namedargs, MonoObject*, i);
+               MonoObject *typedarg, *namedarg, *minfo;
+
+               if (arginfo [i].prop)
+                       minfo = (MonoObject*)mono_property_get_object (domain, NULL, arginfo [i].prop);
+               else
+                       minfo = (MonoObject*)mono_field_get_object (domain, NULL, arginfo [i].field);
+
+               typedarg = create_cattr_typed_arg (arginfo [i].type, obj);
+               namedarg = create_cattr_named_arg (minfo, typedarg);
+
+               mono_array_setref (namedargs, i, namedarg);
+       }
+
        attr = mono_object_new (domain, mono_defaults.customattribute_data_class);
        params [0] = mono_method_get_object (domain, method, NULL);
        params [1] = typedargs;
@@ -8085,7 +8258,7 @@ mono_custom_attrs_from_index (MonoImage *image, guint32 idx)
        len = g_list_length (list);
        if (!len)
                return NULL;
-       ainfo = g_malloc0 (sizeof (MonoCustomAttrInfo) + sizeof (MonoCustomAttrEntry) * (len - MONO_ZERO_LEN_ARRAY));
+       ainfo = g_malloc0 (MONO_SIZEOF_CUSTOM_ATTR_INFO + sizeof (MonoCustomAttrEntry) * len);
        ainfo->num_attrs = len;
        ainfo->image = image;
        for (i = 0, tmp = list; i < len; ++i, tmp = tmp->next) {
@@ -8266,7 +8439,7 @@ mono_custom_attrs_from_param (MonoMethod *method, guint32 param)
 
                /* Need to copy since it will be freed later */
                ainfo = aux->param_cattr [param];
-               size = sizeof (MonoCustomAttrInfo) + sizeof (MonoCustomAttrEntry) * (ainfo->num_attrs - MONO_ZERO_LEN_ARRAY);
+               size = MONO_SIZEOF_CUSTOM_ATTR_INFO + sizeof (MonoCustomAttrEntry) * ainfo->num_attrs;
                res = g_malloc0 (size);
                memcpy (res, ainfo, size);
                return res;
@@ -8355,8 +8528,8 @@ mono_reflection_get_custom_attrs_info (MonoObject *obj)
        
        klass = obj->vtable->klass;
        if (klass == mono_defaults.monotype_class) {
-               MonoReflectionType *rtype = (MonoReflectionType*)obj;
-               klass = mono_class_from_mono_type (rtype->type);
+               MonoType *type = mono_reflection_type_get_handle ((MonoReflectionType *)obj);
+               klass = mono_class_from_mono_type (type);
                cinfo = mono_custom_attrs_from_class (klass);
        } else if (strcmp ("Assembly", klass->name) == 0) {
                MonoReflectionAssembly *rassembly = (MonoReflectionAssembly*)obj;
@@ -8485,77 +8658,133 @@ mono_reflection_get_custom_attrs_data (MonoObject *obj)
 static MonoReflectionType*
 mono_reflection_type_get_underlying_system_type (MonoReflectionType* t)
 {
-        MonoMethod *method_get_underlying_system_type;
+       static MonoMethod *method_get_underlying_system_type = NULL;
+       MonoMethod *usertype_method;
 
-        method_get_underlying_system_type = mono_object_get_virtual_method ((MonoObject *) t,
-                                                                            mono_class_get_method_from_name (mono_object_class (t),
-                                                                                                             "get_UnderlyingSystemType",
-                                                                                                             0));
-        return (MonoReflectionType *) mono_runtime_invoke (method_get_underlying_system_type, t, NULL, NULL);
+       if (!method_get_underlying_system_type)
+               method_get_underlying_system_type = mono_class_get_method_from_name (mono_defaults.systemtype_class, "get_UnderlyingSystemType", 0);
+       usertype_method = mono_object_get_virtual_method ((MonoObject *) t, method_get_underlying_system_type);
+        return (MonoReflectionType *) mono_runtime_invoke (usertype_method, t, NULL, NULL);
 }
 
 #ifndef DISABLE_REFLECTION_EMIT
 
 static gboolean
-is_corlib_type (MonoReflectionType *ref)
+is_corlib_type (MonoClass *class)
 {
-       return ref && mono_object_class (ref)->image == mono_defaults.corlib;
+       return class->image == mono_defaults.corlib;
 }
 
+#define check_corlib_type_cached(_class, _namespace, _name) do { \
+       static MonoClass *cached_class; \
+       if (cached_class) \
+               return cached_class == _class; \
+       if (is_corlib_type (_class) && !strcmp (_name, _class->name) && !strcmp (_namespace, _class->name_space)) { \
+               cached_class = _class; \
+               return TRUE; \
+       } \
+       return FALSE; \
+} while (0) \
+
 static gboolean
-is_sre_usertype (MonoReflectionType *ref)
+is_sre_array (MonoClass *class)
 {
-       MonoClass *class = mono_object_class (ref);
-       return ref && class->image == mono_defaults.corlib && strcmp ("TypeDelegator", class->name);
+       check_corlib_type_cached (class, "System.Reflection.Emit", "ArrayType");
 }
 
 static gboolean
-is_sre_array (MonoReflectionType *ref)
+is_sre_byref (MonoClass *class)
 {
-       return ref && is_corlib_type (ref) &&
-                       !strcmp ("ArrayType", mono_object_class (ref)->name) &&
-                       !strcmp ("System.Reflection.Emit", mono_object_class (ref)->name_space);
+       check_corlib_type_cached (class, "System.Reflection.Emit", "ByRefType");
 }
 
-static MonoType*
+static gboolean
+is_sre_pointer (MonoClass *class)
+{
+       check_corlib_type_cached (class, "System.Reflection.Emit", "PointerType");
+}
+
+static gboolean
+is_sre_generic_instance (MonoClass *class)
+{
+       check_corlib_type_cached (class, "System.Reflection", "MonoGenericClass");
+}
+
+static gboolean
+is_sre_type_builder (MonoClass *class)
+{
+       check_corlib_type_cached (class, "System.Reflection.Emit", "TypeBuilder");
+}
+
+MonoType*
 mono_reflection_type_get_handle (MonoReflectionType* ref)
 {
+       MonoClass *class;
        if (!ref)
                return NULL;
        if (ref->type)
                return ref->type;
 
-       if (!is_sre_usertype (ref))
+       if (is_usertype (ref)) {
                ref = mono_reflection_type_get_underlying_system_type (ref);
+               g_assert (!is_usertype (ref)); /*FIXME fail better*/
+               if (ref->type)
+                       return ref->type;
+       }
 
-       if (is_sre_array (ref)) {
+       class = mono_object_class (ref);
+
+       if (is_sre_array (class)) {
                MonoType *res;
                MonoReflectionArrayType *sre_array = (MonoReflectionArrayType*)ref;
                MonoType *base = mono_reflection_type_get_handle (sre_array->element_type);
                g_assert (base);
-               res = &mono_array_class_get (mono_class_from_mono_type (base), sre_array->rank)->byval_arg;
+               if (sre_array->rank == 0) //single dimentional array
+                       res = &mono_array_class_get (mono_class_from_mono_type (base), 1)->byval_arg;
+               else
+                       res = &mono_bounded_array_class_get (mono_class_from_mono_type (base), sre_array->rank, TRUE)->byval_arg;
                sre_array->type.type = res;
                return res;
+       } else if (is_sre_byref (class)) {
+               MonoType *res;
+               MonoReflectionDerivedType *sre_byref = (MonoReflectionDerivedType*)ref;
+               MonoType *base = mono_reflection_type_get_handle (sre_byref->element_type);
+               g_assert (base);
+               res = &mono_class_from_mono_type (base)->this_arg;
+               sre_byref->type.type = res;
+               return res;
+       } else if (is_sre_pointer (class)) {
+               MonoType *res;
+               MonoReflectionDerivedType *sre_pointer = (MonoReflectionDerivedType*)ref;
+               MonoType *base = mono_reflection_type_get_handle (sre_pointer->element_type);
+               g_assert (base);
+               res = &mono_ptr_class_get (base)->byval_arg;
+               sre_pointer->type.type = res;
+               return res;
+       } else if (is_sre_generic_instance (class)) {
+               MonoType *res, **types;
+               MonoReflectionGenericClass *gclass = (MonoReflectionGenericClass*)ref;
+               int i, count;
+
+               count = mono_array_length (gclass->type_arguments);
+               types = g_new0 (MonoType*, count);
+               for (i = 0; i < count; ++i) {
+                       MonoReflectionType *t = mono_array_get (gclass->type_arguments, gpointer, i);
+                       types [i] = mono_reflection_type_get_handle (t);
+               }
+
+               res = mono_reflection_bind_generic_parameters ((MonoReflectionType*)gclass->generic_type, count, types);
+               g_free (types);
+               g_assert (res);
+               gclass->type.type = res;
+               return res;
        }
 
        g_error ("Cannot handle corlib user type %s", mono_type_full_name (&mono_object_class(ref)->byval_arg));
        return NULL;
 }
 
-static MonoReflectionType*
-mono_reflection_type_resolve_user_types (MonoReflectionType *type)
-{
-       if (!type || type->type)
-               return type;
-
-       if (!is_sre_usertype (type)) {
-               type = mono_reflection_type_get_underlying_system_type (type);
-               if (!is_sre_usertype (type))
-                       mono_raise_exception (mono_get_exception_not_supported ("User defined subclasses of System.Type are not yet supported22"));
-       }
 
-       return type;
-}
 
 void
 mono_reflection_create_unmanaged_type (MonoReflectionType *type)
@@ -8573,7 +8802,7 @@ parameters_to_signature (MonoImage *image, MonoArray *parameters) {
 
        count = parameters? mono_array_length (parameters): 0;
 
-       sig = image_g_malloc0 (image, sizeof (MonoMethodSignature) + sizeof (MonoType*) * count);
+       sig = image_g_malloc0 (image, MONO_SIZEOF_METHOD_SIGNATURE + sizeof (MonoType*) * count);
        sig->param_count = count;
        sig->sentinelpos = -1; /* FIXME */
        for (i = 0; i < count; ++i)
@@ -8603,7 +8832,7 @@ method_builder_to_signature (MonoImage *image, MonoReflectionMethodBuilder *meth
 
        sig = parameters_to_signature (image, method->parameters);
        sig->hasthis = method->attrs & METHOD_ATTRIBUTE_STATIC? 0: 1;
-       sig->ret = method->rtype? mono_reflection_type_get_handle (method->rtype): &mono_defaults.void_class->byval_arg;
+       sig->ret = method->rtype? mono_reflection_type_get_handle ((MonoReflectionType*)method->rtype): &mono_defaults.void_class->byval_arg;
        sig->generic_param_count = method->generic_params ? mono_array_length (method->generic_params) : 0;
        return sig;
 }
@@ -8614,7 +8843,7 @@ dynamic_method_to_signature (MonoReflectionDynamicMethod *method) {
 
        sig = parameters_to_signature (NULL, method->parameters);
        sig->hasthis = method->attrs & METHOD_ATTRIBUTE_STATIC? 0: 1;
-       sig->ret = method->rtype? method->rtype->type: &mono_defaults.void_class->byval_arg;
+       sig->ret = method->rtype? mono_reflection_type_get_handle (method->rtype): &mono_defaults.void_class->byval_arg;
        sig->generic_param_count = 0;
        return sig;
 }
@@ -8626,7 +8855,7 @@ get_prop_name_and_type (MonoObject *prop, char **name, MonoType **type)
        if (strcmp (klass->name, "PropertyBuilder") == 0) {
                MonoReflectionPropertyBuilder *pb = (MonoReflectionPropertyBuilder *)prop;
                *name = mono_string_to_utf8 (pb->name);
-               *type = mono_reflection_type_get_handle (pb->type);
+               *type = mono_reflection_type_get_handle ((MonoReflectionType*)pb->type);
        } else {
                MonoReflectionProperty *p = (MonoReflectionProperty *)prop;
                *name = g_strdup (p->property->name);
@@ -8644,7 +8873,7 @@ get_field_name_and_type (MonoObject *field, char **name, MonoType **type)
        if (strcmp (klass->name, "FieldBuilder") == 0) {
                MonoReflectionFieldBuilder *fb = (MonoReflectionFieldBuilder *)field;
                *name = mono_string_to_utf8 (fb->name);
-               *type = mono_reflection_type_get_handle (fb->type);
+               *type = mono_reflection_type_get_handle ((MonoReflectionType*)fb->type);
        } else {
                MonoReflectionField *f = (MonoReflectionField *)field;
                *name = g_strdup (mono_field_get_name (f->field));
@@ -8653,6 +8882,27 @@ get_field_name_and_type (MonoObject *field, char **name, MonoType **type)
 }
 #endif /* !DISABLE_REFLECTION_EMIT */
 
+static gboolean
+is_usertype (MonoReflectionType *ref)
+{
+       MonoClass *class = mono_object_class (ref);
+       return class->image != mono_defaults.corlib || strcmp ("TypeDelegator", class->name) == 0;
+}
+
+static MonoReflectionType*
+mono_reflection_type_resolve_user_types (MonoReflectionType *type)
+{
+       if (!type || type->type)
+               return type;
+
+       if (is_usertype (type)) {
+               type = mono_reflection_type_get_underlying_system_type (type);
+               if (is_usertype (type))
+                       mono_raise_exception (mono_get_exception_not_supported ("User defined subclasses of System.Type are not yet supported22"));
+       }
+
+       return type;
+}
 /*
  * Encode a value in a custom attribute stream of bytes.
  * The value to encode is either supplied as an object in argument val
@@ -8753,27 +9003,12 @@ handle_enum:
        case MONO_TYPE_CLASS: {
                char *str;
                guint32 slen;
-               MonoClass *k;
                if (!arg) {
                        *p++ = 0xFF;
                        break;
                }
-               k = mono_object_class (arg);
-               if (!mono_object_isinst (arg, mono_defaults.monotype_class) &&
-                        (strcmp (k->name, "TypeBuilder") || strcmp (k->name_space, "System.Reflection.Emit"))) {
-                        MonoReflectionType* rt = mono_reflection_type_get_underlying_system_type ((MonoReflectionType*) arg);
-                        MonoClass *rtc;
-                        
-                        if (rt && (rtc = mono_object_class (rt)) &&
-                                   (mono_object_isinst ((MonoObject *) rt, mono_defaults.monotype_class) ||
-                                    !strcmp (rtc->name, "TypeBuilder") || !strcmp (rtc->name_space, "System.Reflection.Emit"))) {
-                                arg = (MonoObject *) rt;
-                                k = rtc;
-                        } else
-                                g_error ("Only System.Type allowed, not %s.%s", k->name_space, k->name);
-                }
 handle_type:
-               str = type_get_qualified_name (((MonoReflectionType*)arg)->type, NULL);
+               str = type_get_qualified_name (mono_reflection_type_get_handle ((MonoReflectionType*)arg), NULL);
                slen = strlen (str);
                if ((p-buffer) + 10 + slen >= *buflen) {
                        char *newbuf;
@@ -9067,6 +9302,7 @@ mono_reflection_get_custom_attrs_blob (MonoReflectionAssembly *assembly, MonoObj
 void
 mono_reflection_setup_internal_class (MonoReflectionTypeBuilder *tb)
 {
+       MonoError error;
        MonoClass *klass, *parent;
 
        MONO_ARCH_SAVE_REGS;
@@ -9079,9 +9315,9 @@ mono_reflection_setup_internal_class (MonoReflectionTypeBuilder *tb)
                /* check so we can compile corlib correctly */
                if (strcmp (mono_object_class (tb->parent)->name, "TypeBuilder") == 0) {
                        /* mono_class_setup_mono_type () guaranteess type->data.klass is valid */
-                       parent = mono_reflection_type_get_handle (tb->parent)->data.klass;
+                       parent = mono_reflection_type_get_handle ((MonoReflectionType*)tb->parent)->data.klass;
                } else {
-                       parent = mono_class_from_mono_type (mono_reflection_type_get_handle (tb->parent));
+                       parent = mono_class_from_mono_type (mono_reflection_type_get_handle ((MonoReflectionType*)tb->parent));
                }
        } else {
                parent = NULL;
@@ -9104,8 +9340,12 @@ mono_reflection_setup_internal_class (MonoReflectionTypeBuilder *tb)
        klass->image = &tb->module->dynamic_image->image;
 
        klass->inited = 1; /* we lie to the runtime */
-       klass->name = mono_string_to_utf8_image (klass->image, tb->name);
-       klass->name_space = mono_string_to_utf8_image (klass->image, tb->nspace);
+       klass->name = mono_string_to_utf8_image (klass->image, tb->name, &error);
+       if (!mono_error_ok (&error))
+               goto failure;
+       klass->name_space = mono_string_to_utf8_image (klass->image, tb->nspace, &error);
+       if (!mono_error_ok (&error))
+               goto failure;
        klass->type_token = MONO_TOKEN_TYPE_DEF | tb->table_idx;
        klass->flags = tb->attrs;
        
@@ -9113,11 +9353,22 @@ mono_reflection_setup_internal_class (MonoReflectionTypeBuilder *tb)
 
        klass->element_class = klass;
 
-       MOVING_GC_REGISTER (&klass->reflection_info);
-       klass->reflection_info = tb;
+       if (klass->reflection_info == NULL) {
 
-       /* Put into cache so mono_class_get () will find it */
-       mono_image_add_to_name_cache (klass->image, klass->name_space, klass->name, tb->table_idx);
+               MOVING_GC_REGISTER (&klass->reflection_info);
+               klass->reflection_info = tb;
+
+               /* Put into cache so mono_class_get () will find it.
+               Skip nested types as those should not be available on the global scope. */
+               if (!tb->nesting_type) {
+                       mono_image_add_to_name_cache (klass->image, klass->name_space, klass->name, tb->table_idx);
+               } else {
+                       klass->image->reflection_info_unregister_classes =
+                               g_slist_prepend (klass->image->reflection_info_unregister_classes, klass);
+               }
+       } else {
+               g_assert (klass->reflection_info == tb);
+       }
 
        mono_g_hash_table_insert (tb->module->dynamic_image->tokens,
                GUINT_TO_POINTER (MONO_TOKEN_TYPE_DEF | tb->table_idx), tb);
@@ -9152,7 +9403,7 @@ mono_reflection_setup_internal_class (MonoReflectionTypeBuilder *tb)
 
        if (tb->nesting_type) {
                g_assert (tb->nesting_type->type);
-               klass->nested_in = mono_class_from_mono_type (tb->nesting_type->type);
+               klass->nested_in = mono_class_from_mono_type (mono_reflection_type_get_handle (tb->nesting_type));
        }
 
        /*g_print ("setup %s as %s (%p)\n", klass->name, ((MonoObject*)tb)->vtable->klass->name, tb);*/
@@ -9160,6 +9411,11 @@ mono_reflection_setup_internal_class (MonoReflectionTypeBuilder *tb)
        mono_profiler_class_loaded (klass, MONO_PROFILE_OK);
        
        mono_loader_unlock ();
+       return;
+
+failure:
+       mono_loader_unlock ();
+       mono_error_raise_exception (&error);
 }
 
 /*
@@ -9206,7 +9462,7 @@ mono_reflection_create_generic_class (MonoReflectionTypeBuilder *tb)
 
        for (i = 0; i < count; i++) {
                MonoReflectionGenericParam *gparam = mono_array_get (tb->generic_params, gpointer, i);
-               MonoGenericParamFull *param = (MonoGenericParamFull *) gparam->type.type->data.generic_param;
+               MonoGenericParamFull *param = (MonoGenericParamFull *) mono_reflection_type_get_handle ((MonoReflectionType*)gparam)->data.generic_param;
                klass->generic_container->type_params [i] = *param;
                /*Make sure we are a diferent type instance */
                klass->generic_container->type_params [i].param.owner = klass->generic_container;
@@ -9244,12 +9500,12 @@ mono_reflection_create_internal_class (MonoReflectionTypeBuilder *tb)
 
                fb = mono_array_get (tb->fields, MonoReflectionFieldBuilder*, 0);
 
-               if (!mono_type_is_valid_enum_basetype (mono_reflection_type_get_handle (fb->type))) {
+               if (!mono_type_is_valid_enum_basetype (mono_reflection_type_get_handle ((MonoReflectionType*)fb->type))) {
                        mono_loader_unlock ();
                        return;
                }
 
-               enum_basetype = mono_reflection_type_get_handle (fb->type);
+               enum_basetype = mono_reflection_type_get_handle ((MonoReflectionType*)fb->type);
                klass->element_class = mono_class_from_mono_type (enum_basetype);
                if (!klass->element_class)
                        klass->element_class = mono_class_from_mono_type (enum_basetype);
@@ -9302,7 +9558,7 @@ mono_marshal_spec_from_builder (MonoImage *image, MonoAssembly *assembly,
        case MONO_NATIVE_CUSTOM:
                if (minfo->marshaltyperef)
                        res->data.custom_data.custom_name =
-                               type_get_fully_qualified_name (mono_reflection_type_get_handle (minfo->marshaltyperef));
+                               type_get_fully_qualified_name (mono_reflection_type_get_handle ((MonoReflectionType*)minfo->marshaltyperef));
                if (minfo->mcookie)
                        res->data.custom_data.cookie = mono_string_to_utf8 (minfo->mcookie);
                break;
@@ -9369,6 +9625,7 @@ reflection_methodbuilder_to_mono_method (MonoClass *klass,
                                         ReflectionMethodBuilder *rmb,
                                         MonoMethodSignature *sig)
 {
+       MonoError error;
        MonoMethod *m;
        MonoMethodNormal *pm;
        MonoMarshalSpec **specs;
@@ -9377,6 +9634,7 @@ reflection_methodbuilder_to_mono_method (MonoClass *klass,
        gboolean dynamic;
        int i;
 
+       mono_error_init (&error);
        /*
         * Methods created using a MethodBuilder should have their memory allocated
         * inside the image mempool, while dynamic methods should have their memory
@@ -9404,7 +9662,8 @@ reflection_methodbuilder_to_mono_method (MonoClass *klass,
        m->slot = -1;
        m->flags = rmb->attrs;
        m->iflags = rmb->iattrs;
-       m->name = mono_string_to_utf8_image (image, rmb->name);
+       m->name = mono_string_to_utf8_image (image, rmb->name, &error);
+       g_assert (mono_error_ok (&error));
        m->klass = klass;
        m->signature = sig;
        m->skip_visibility = rmb->skip_visibility;
@@ -9421,8 +9680,10 @@ reflection_methodbuilder_to_mono_method (MonoClass *klass,
 
                method_aux = image_g_new0 (image, MonoReflectionMethodAux, 1);
 
-               method_aux->dllentry = rmb->dllentry ? mono_string_to_utf8_image (image, rmb->dllentry) : image_strdup (image, m->name);
-               method_aux->dll = mono_string_to_utf8_image (image, rmb->dll);
+               method_aux->dllentry = rmb->dllentry ? mono_string_to_utf8_image (image, rmb->dllentry, &error) : image_strdup (image, m->name);
+               g_assert (mono_error_ok (&error));
+               method_aux->dll = mono_string_to_utf8_image (image, rmb->dll, &error);
+               g_assert (mono_error_ok (&error));
                
                ((MonoMethodPInvoke*)m)->piflags = (rmb->native_cc << 8) | (rmb->charset ? (rmb->charset - 1) * 2 : 0) | rmb->extra_flags;
 
@@ -9462,8 +9723,7 @@ reflection_methodbuilder_to_mono_method (MonoClass *klass,
                        }
                }
 
-               header = image_g_malloc0 (image, sizeof (MonoMethodHeader) + 
-                       (num_locals - MONO_ZERO_LEN_ARRAY) * sizeof (MonoType*));
+               header = image_g_malloc0 (image, MONO_SIZEOF_METHOD_HEADER + num_locals * sizeof (MonoType*));
                header->code_size = code_size;
                header->code = image_g_malloc (image, code_size);
                memcpy ((char*)header->code, code, code_size);
@@ -9476,7 +9736,7 @@ reflection_methodbuilder_to_mono_method (MonoClass *klass,
                                mono_array_get (rmb->ilgen->locals, MonoReflectionLocalBuilder*, i);
 
                        header->locals [i] = image_g_new0 (image, MonoType, 1);
-                       memcpy (header->locals [i], mono_reflection_type_get_handle (lb->type), sizeof (MonoType));
+                       memcpy (header->locals [i], mono_reflection_type_get_handle ((MonoReflectionType*)lb->type), MONO_SIZEOF_TYPE);
                }
 
                header->num_clauses = num_clauses;
@@ -9504,7 +9764,7 @@ reflection_methodbuilder_to_mono_method (MonoClass *klass,
                for (i = 0; i < count; i++) {
                        MonoReflectionGenericParam *gp =
                                mono_array_get (rmb->generic_params, MonoReflectionGenericParam*, i);
-                       MonoGenericParamFull *param = (MonoGenericParamFull *) gp->type.type->data.generic_param;
+                       MonoGenericParamFull *param = (MonoGenericParamFull *) mono_reflection_type_get_handle ((MonoReflectionType*)gp)->data.generic_param;
                        container->type_params [i] = *param;
                }
 
@@ -9565,8 +9825,10 @@ reflection_methodbuilder_to_mono_method (MonoClass *klass,
                                        memcpy ((gpointer)method_aux->param_defaults [i], p, len);
                                }
 
-                               if (pb->name)
-                                       method_aux->param_names [i] = mono_string_to_utf8_image (image, pb->name);
+                               if (pb->name) {
+                                       method_aux->param_names [i] = mono_string_to_utf8_image (image, pb->name, &error);
+                                       g_assert (mono_error_ok (&error));
+                               }
                                if (pb->cattrs) {
                                        if (!method_aux->param_cattr)
                                                method_aux->param_cattr = image_g_new0 (image, MonoCustomAttrInfo*, m->signature->param_count + 1);
@@ -9661,7 +9923,7 @@ fieldbuilder_to_mono_class_field (MonoClass *klass, MonoReflectionFieldBuilder*
 
        field->name = mono_string_to_utf8 (fb->name);
        if (fb->attrs || fb->modreq || fb->modopt) {
-               field->type = mono_metadata_type_dup (NULL, mono_reflection_type_get_handle (fb->type));
+               field->type = mono_metadata_type_dup (NULL, mono_reflection_type_get_handle ((MonoReflectionType*)fb->type));
                field->type->attrs = fb->attrs;
 
                g_assert (klass->image->dynamic);
@@ -9669,7 +9931,7 @@ fieldbuilder_to_mono_class_field (MonoClass *klass, MonoReflectionFieldBuilder*
                g_free (field->type);
                field->type = custom;
        } else {
-               field->type = mono_reflection_type_get_handle (fb->type);
+               field->type = mono_reflection_type_get_handle ((MonoReflectionType*)fb->type);
        }
        if (fb->offset != -1)
                field->offset = fb->offset;
@@ -9710,7 +9972,7 @@ mono_reflection_bind_generic_parameters (MonoReflectionType *type, int type_argc
        if (tb && tb->generic_container)
                mono_reflection_create_generic_class (tb);
 
-       klass = mono_class_from_mono_type (type->type);
+       klass = mono_class_from_mono_type (mono_reflection_type_get_handle (type));
        if (!klass->generic_container) {
                mono_loader_unlock ();
                return NULL;
@@ -9764,7 +10026,7 @@ mono_reflection_bind_generic_method_parameters (MonoReflectionMethod *rmethod, M
 
                mb = (MonoReflectionMethodBuilder *) rmethod;
                tb = (MonoReflectionTypeBuilder *) mb->type;
-               klass = mono_class_from_mono_type (tb->type.type);
+               klass = mono_class_from_mono_type (mono_reflection_type_get_handle ((MonoReflectionType*)tb));
 
                method = methodbuilder_to_mono_method (klass, mb);
 #else
@@ -9787,7 +10049,7 @@ mono_reflection_bind_generic_method_parameters (MonoReflectionMethod *rmethod, M
        type_argv = g_new0 (MonoType *, count);
        for (i = 0; i < count; i++) {
                MonoReflectionType *garg = mono_array_get (types, gpointer, i);
-               type_argv [i] = garg->type;
+               type_argv [i] = mono_reflection_type_get_handle (garg);
        }
        ginst = mono_metadata_get_generic_inst (count, type_argv);
        g_free (type_argv);
@@ -9855,12 +10117,24 @@ inflate_mono_method (MonoClass *klass, MonoMethod *method, MonoObject *obj)
 }
 
 static MonoMethod *
-inflate_method (MonoReflectionGenericClass *type, MonoObject *obj)
+inflate_method (MonoReflectionType *type, MonoObject *obj)
 {
        MonoMethod *method;
        MonoClass *gklass;
 
-       gklass = mono_class_from_mono_type (type->generic_type->type.type);
+       MonoClass *type_class = mono_object_class (type);
+
+       if (is_sre_generic_instance (type_class)) {
+               MonoReflectionGenericClass *mgc = (MonoReflectionGenericClass*)type;
+               gklass = mono_class_from_mono_type (mono_reflection_type_get_handle ((MonoReflectionType*)mgc->generic_type));
+       } else if (is_sre_type_builder (type_class)) {
+               gklass = mono_class_from_mono_type (mono_reflection_type_get_handle (type));
+       } else if (type->type) {
+               gklass = mono_class_from_mono_type (type->type);
+               gklass = mono_class_get_generic_type_definition (gklass);
+       } else {
+               g_error ("Can't handle type %s", mono_type_get_full_name (mono_object_class (type)));
+       }
 
        if (!strcmp (obj->vtable->klass->name, "MethodBuilder"))
                if (((MonoReflectionMethodBuilder*)obj)->mhandle)
@@ -9873,10 +10147,10 @@ inflate_method (MonoReflectionGenericClass *type, MonoObject *obj)
                method = ((MonoReflectionMethod *) obj)->method;
        else {
                method = NULL; /* prevent compiler warning */
-               g_assert_not_reached ();
+               g_error ("can't handle type %s", obj->vtable->klass->name);
        }
 
-       return inflate_mono_method (mono_class_from_mono_type (type->type.type), method, obj);
+       return inflate_mono_method (mono_class_from_mono_type (mono_reflection_type_get_handle ((MonoReflectionType*)type)), method, obj);
 }
 
 /*TODO avoid saving custom attrs for generic classes as it's enough to have them on the generic type definition.*/
@@ -9888,13 +10162,15 @@ mono_reflection_generic_class_initialize (MonoReflectionGenericClass *type, Mono
        MonoGenericClass *gclass;
        MonoDynamicGenericClass *dgclass;
        MonoClass *klass, *gklass;
+       MonoType *gtype;
        int i;
 
        MONO_ARCH_SAVE_REGS;
 
-       klass = mono_class_from_mono_type (type->type.type);
-       g_assert (type->type.type->type == MONO_TYPE_GENERICINST);
-       gclass = type->type.type->data.generic_class;
+       gtype = mono_reflection_type_get_handle ((MonoReflectionType*)type);
+       klass = mono_class_from_mono_type (gtype);
+       g_assert (gtype->type == MONO_TYPE_GENERICINST);
+       gclass = gtype->data.generic_class;
 
        g_assert (gclass->is_dynamic);
        dgclass = (MonoDynamicGenericClass *) gclass;
@@ -9922,13 +10198,13 @@ mono_reflection_generic_class_initialize (MonoReflectionGenericClass *type, Mono
        for (i = 0; i < dgclass->count_methods; i++) {
                MonoObject *obj = mono_array_get (methods, gpointer, i);
 
-               dgclass->methods [i] = inflate_method (type, obj);
+               dgclass->methods [i] = inflate_method ((MonoReflectionType*)type, obj);
        }
 
        for (i = 0; i < dgclass->count_ctors; i++) {
                MonoObject *obj = mono_array_get (ctors, gpointer, i);
 
-               dgclass->ctors [i] = inflate_method (type, obj);
+               dgclass->ctors [i] = inflate_method ((MonoReflectionType*)type, obj);
        }
 
        for (i = 0; i < dgclass->count_fields; i++) {
@@ -9970,9 +10246,9 @@ mono_reflection_generic_class_initialize (MonoReflectionGenericClass *type, Mono
                        property->attrs = pb->attrs;
                        property->name = mono_string_to_utf8 (pb->name);
                        if (pb->get_method)
-                               property->get = inflate_method (type, (MonoObject *) pb->get_method);
+                               property->get = inflate_method ((MonoReflectionType*)type, (MonoObject *) pb->get_method);
                        if (pb->set_method)
-                               property->set = inflate_method (type, (MonoObject *) pb->set_method);
+                               property->set = inflate_method ((MonoReflectionType*)type, (MonoObject *) pb->set_method);
                } else if (!strcmp (obj->vtable->klass->name, "MonoProperty")) {
                        *property = *((MonoReflectionProperty *) obj)->property;
                        property->name = g_strdup (property->name);
@@ -9996,9 +10272,9 @@ mono_reflection_generic_class_initialize (MonoReflectionGenericClass *type, Mono
                        event->attrs = eb->attrs;
                        event->name = mono_string_to_utf8 (eb->name);
                        if (eb->add_method)
-                               event->add = inflate_method (type, (MonoObject *) eb->add_method);
+                               event->add = inflate_method ((MonoReflectionType*)type, (MonoObject *) eb->add_method);
                        if (eb->remove_method)
-                               event->remove = inflate_method (type, (MonoObject *) eb->remove_method);
+                               event->remove = inflate_method ((MonoReflectionType*)type, (MonoObject *) eb->remove_method);
                } else if (!strcmp (obj->vtable->klass->name, "MonoEvent")) {
                        *event = *((MonoReflectionMonoEvent *) obj)->event;
                        event->name = g_strdup (event->name);
@@ -10015,34 +10291,55 @@ mono_reflection_generic_class_initialize (MonoReflectionGenericClass *type, Mono
 }
 
 static void
-ensure_generic_class_runtime_vtable (MonoClass *klass)
+fix_partial_generic_class (MonoClass *klass)
 {
        MonoClass *gklass = klass->generic_class->container_class;
+       MonoDynamicGenericClass *dgclass;
        int i;
 
        if (klass->wastypebuilder)
                return;
 
-       ensure_runtime_vtable (gklass);
+       dgclass = (MonoDynamicGenericClass *)  klass->generic_class;
 
-       klass->method.count = gklass->method.count;
-       klass->methods = mono_image_alloc (klass->image, sizeof (MonoMethod*) * (klass->method.count + 1));
+       if (!dgclass->initialized)
+               return;
+
+       if (klass->method.count != gklass->method.count) {
+               klass->method.count = gklass->method.count;
+               klass->methods = mono_image_alloc (klass->image, sizeof (MonoMethod*) * (klass->method.count + 1));
 
-       for (i = 0; i < klass->method.count; i++) {
-               klass->methods [i] = mono_class_inflate_generic_method_full (
-                       gklass->methods [i], klass, mono_class_get_context (klass));
+               for (i = 0; i < klass->method.count; i++) {
+                       klass->methods [i] = mono_class_inflate_generic_method_full (
+                               gklass->methods [i], klass, mono_class_get_context (klass));
+               }
        }
 
-       klass->interface_count = gklass->interface_count;
-       klass->interfaces = mono_image_alloc (klass->image, sizeof (MonoClass*) * klass->interface_count);
-       for (i = 0; i < klass->interface_count; ++i) {
-               MonoType *iface_type = mono_class_inflate_generic_type (&gklass->interfaces [i]->byval_arg, mono_class_get_context (klass));
-               klass->interfaces [i] = mono_class_from_mono_type (iface_type);
-               mono_metadata_free_type (iface_type);
+       if (klass->interface_count && klass->interface_count != gklass->interface_count) {
+               klass->interface_count = gklass->interface_count;
+               klass->interfaces = mono_image_alloc (klass->image, sizeof (MonoClass*) * gklass->interface_count);
+               klass->interfaces_packed = NULL; /*make setup_interface_offsets happy*/
 
-               ensure_runtime_vtable (klass->interfaces [i]);
+               for (i = 0; i < gklass->interface_count; ++i) {
+                       MonoType *iface_type = mono_class_inflate_generic_type (&gklass->interfaces [i]->byval_arg, mono_class_get_context (klass));
+                       klass->interfaces [i] = mono_class_from_mono_type (iface_type);
+                       mono_metadata_free_type (iface_type);
+
+                       ensure_runtime_vtable (klass->interfaces [i]);
+               }
+               klass->interfaces_inited = 1;
+       }
+
+       if (klass->field.count != gklass->field.count) {
+               klass->field.count = gklass->field.count;
+               klass->fields = image_g_new0 (klass->image, MonoClassField, klass->field.count);
+
+               for (i = 0; i < klass->field.count; i++) {
+                       klass->fields [i] = gklass->fields [i];
+                       klass->fields [i].parent = klass;
+                       klass->fields [i].type = mono_class_inflate_generic_type (gklass->fields [i].type, mono_class_get_context (klass));
+               }
        }
-       klass->interfaces_inited = 1;
 
        /*We can only finish with this klass once it's parent has as well*/
        if (gklass->wastypebuilder)
@@ -10050,6 +10347,16 @@ ensure_generic_class_runtime_vtable (MonoClass *klass)
        return;
 }
 
+static void
+ensure_generic_class_runtime_vtable (MonoClass *klass)
+{
+       MonoClass *gklass = klass->generic_class->container_class;
+
+       ensure_runtime_vtable (gklass); 
+
+       fix_partial_generic_class (klass);
+}
+
 static void
 ensure_runtime_vtable (MonoClass *klass)
 {
@@ -10092,6 +10399,7 @@ ensure_runtime_vtable (MonoClass *klass)
                for (i = 0; i < klass->method.count; ++i)
                        klass->methods [i]->slot = i;
                
+               klass->interfaces_packed = NULL; /*make setup_interface_offsets happy*/
                mono_class_setup_interface_offsets (klass);
                mono_class_setup_interface_id (klass);
        }
@@ -10162,7 +10470,7 @@ mono_reflection_get_dynamic_overrides (MonoClass *klass, MonoMethod ***overrides
 }
 
 static void
-typebuilder_setup_fields (MonoClass *klass)
+typebuilder_setup_fields (MonoClass *klass, MonoError *error)
 {
        MonoReflectionTypeBuilder *tb = klass->reflection_info;
        MonoReflectionFieldBuilder *fb;
@@ -10175,6 +10483,8 @@ typebuilder_setup_fields (MonoClass *klass)
        klass->field.count = tb->num_fields;
        klass->field.first = 0;
 
+       mono_error_init (error);
+
        if (tb->class_size) {
                g_assert ((tb->packing_size & 0xfffffff0) == 0);
                klass->packing_size = tb->packing_size;
@@ -10193,12 +10503,14 @@ typebuilder_setup_fields (MonoClass *klass)
        for (i = 0; i < klass->field.count; ++i) {
                fb = mono_array_get (tb->fields, gpointer, i);
                field = &klass->fields [i];
-               field->name = mono_string_to_utf8_image (image, fb->name);
+               field->name = mono_string_to_utf8_image (image, fb->name, error);
+               if (!mono_error_ok (error))
+                       return;
                if (fb->attrs) {
-                       field->type = mono_metadata_type_dup (klass->image, mono_reflection_type_get_handle (fb->type));
+                       field->type = mono_metadata_type_dup (klass->image, mono_reflection_type_get_handle ((MonoReflectionType*)fb->type));
                        field->type->attrs = fb->attrs;
                } else {
-                       field->type = mono_reflection_type_get_handle (fb->type);
+                       field->type = mono_reflection_type_get_handle ((MonoReflectionType*)fb->type);
                }
                if ((fb->attrs & FIELD_ATTRIBUTE_HAS_FIELD_RVA) && fb->rva_data)
                        klass->ext->field_def_values [i].data = mono_array_addr (fb->rva_data, char, 0);
@@ -10226,7 +10538,7 @@ typebuilder_setup_fields (MonoClass *klass)
 }
 
 static void
-typebuilder_setup_properties (MonoClass *klass)
+typebuilder_setup_properties (MonoClass *klass, MonoError *error)
 {
        MonoReflectionTypeBuilder *tb = klass->reflection_info;
        MonoReflectionPropertyBuilder *pb;
@@ -10234,6 +10546,8 @@ typebuilder_setup_properties (MonoClass *klass)
        MonoProperty *properties;
        int i;
 
+       mono_error_init (error);
+
        if (!klass->ext)
                klass->ext = image_g_new0 (image, MonoClassExt, 1);
 
@@ -10246,7 +10560,9 @@ typebuilder_setup_properties (MonoClass *klass)
                pb = mono_array_get (tb->properties, MonoReflectionPropertyBuilder*, i);
                properties [i].parent = klass;
                properties [i].attrs = pb->attrs;
-               properties [i].name = mono_string_to_utf8_image (image, pb->name);
+               properties [i].name = mono_string_to_utf8_image (image, pb->name, error);
+               if (!mono_error_ok (error))
+                       return;
                if (pb->get_method)
                        properties [i].get = pb->get_method->mhandle;
                if (pb->set_method)
@@ -10263,7 +10579,7 @@ mono_reflection_event_builder_get_event_info (MonoReflectionTypeBuilder *tb, Mon
        MonoClass *klass;
        int j;
 
-       klass = mono_class_from_mono_type (tb->type.type);
+       klass = mono_class_from_mono_type (mono_reflection_type_get_handle ((MonoReflectionType*)tb));
 
        event->parent = klass;
        event->attrs = eb->attrs;
@@ -10289,7 +10605,7 @@ mono_reflection_event_builder_get_event_info (MonoReflectionTypeBuilder *tb, Mon
 }
 
 static void
-typebuilder_setup_events (MonoClass *klass)
+typebuilder_setup_events (MonoClass *klass, MonoError *error)
 {
        MonoReflectionTypeBuilder *tb = klass->reflection_info;
        MonoReflectionEventBuilder *eb;
@@ -10297,6 +10613,8 @@ typebuilder_setup_events (MonoClass *klass)
        MonoEvent *events;
        int i, j;
 
+       mono_error_init (error);
+
        if (!klass->ext)
                klass->ext = image_g_new0 (image, MonoClassExt, 1);
 
@@ -10309,7 +10627,9 @@ typebuilder_setup_events (MonoClass *klass)
                eb = mono_array_get (tb->events, MonoReflectionEventBuilder*, i);
                events [i].parent = klass;
                events [i].attrs = eb->attrs;
-               events [i].name = mono_string_to_utf8_image (image, eb->name);
+               events [i].name = mono_string_to_utf8_image (image, eb->name, error);
+               if (!mono_error_ok (error))
+                       return;
                if (eb->add_method)
                        events [i].add = eb->add_method->mhandle;
                if (eb->remove_method)
@@ -10331,16 +10651,17 @@ typebuilder_setup_events (MonoClass *klass)
 }
 
 static gboolean
-remove_instantiations_of (gpointer key,
+remove_instantiations_of_and_ensure_contents (gpointer key,
                                                  gpointer value,
                                                  gpointer user_data)
 {
        MonoType *type = (MonoType*)key;
        MonoClass *klass = (MonoClass*)user_data;
 
-       if ((type->type == MONO_TYPE_GENERICINST) && (type->data.generic_class->container_class == klass))
+       if ((type->type == MONO_TYPE_GENERICINST) && (type->data.generic_class->container_class == klass)) {
+               fix_partial_generic_class (mono_class_from_mono_type (type)); //Ensure it's safe to use it.
                return TRUE;
-       else
+       else
                return FALSE;
 }
 
@@ -10359,6 +10680,7 @@ check_array_for_usertypes (MonoArray *arr)
 MonoReflectionType*
 mono_reflection_create_runtime_class (MonoReflectionTypeBuilder *tb)
 {
+       MonoError error;
        MonoClass *klass;
        MonoDomain* domain;
        MonoReflectionType* res;
@@ -10459,7 +10781,7 @@ mono_reflection_create_runtime_class (MonoReflectionTypeBuilder *tb)
                for (i = 0; i < mono_array_length (tb->subtypes); ++i) {
                        MonoReflectionTypeBuilder *subtb = mono_array_get (tb->subtypes, MonoReflectionTypeBuilder*, i);
                        mono_class_alloc_ext (klass);
-                       klass->ext->nested_classes = g_list_prepend_image (klass->image, klass->ext->nested_classes, mono_class_from_mono_type (subtb->type.type));
+                       klass->ext->nested_classes = g_list_prepend_image (klass->image, klass->ext->nested_classes, mono_class_from_mono_type (mono_reflection_type_get_handle ((MonoReflectionType*)subtb)));
                }
        }
 
@@ -10482,21 +10804,28 @@ mono_reflection_create_runtime_class (MonoReflectionTypeBuilder *tb)
        }
 
        /* FIXME: handle packing_size and instance_size */
-       typebuilder_setup_fields (klass);
+       typebuilder_setup_fields (klass, &error);
+       if (!mono_error_ok (&error))
+               goto failure;
+       typebuilder_setup_properties (klass, &error);
+       if (!mono_error_ok (&error))
+               goto failure;
 
-       typebuilder_setup_properties (klass);
+       typebuilder_setup_events (klass, &error);
+       if (!mono_error_ok (&error))
+               goto failure;
 
-       typebuilder_setup_events (klass);
-       
        klass->wastypebuilder = TRUE;
 
        /* 
         * If we are a generic TypeBuilder, there might be instantiations in the type cache
         * which have type System.Reflection.MonoGenericClass, but after the type is created, 
         * we want to return normal System.MonoType objects, so clear these out from the cache.
+        *
+        * Together with this we must ensure the contents of all instances to match the created type.
         */
        if (domain->type_hash && klass->generic_container)
-               mono_g_hash_table_foreach_remove (domain->type_hash, remove_instantiations_of, klass);
+               mono_g_hash_table_foreach_remove (domain->type_hash, remove_instantiations_of_and_ensure_contents, klass);
 
        mono_domain_unlock (domain);
        mono_loader_unlock ();
@@ -10510,6 +10839,14 @@ mono_reflection_create_runtime_class (MonoReflectionTypeBuilder *tb)
        g_assert (res != (MonoReflectionType*)tb);
 
        return res;
+
+failure:
+       mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, NULL);
+       klass->wastypebuilder = TRUE;
+       mono_domain_unlock (domain);
+       mono_loader_unlock ();
+       mono_error_raise_exception (&error);
+       return NULL;
 }
 
 void
@@ -10526,7 +10863,7 @@ mono_reflection_initialize_generic_parameter (MonoReflectionGenericParam *gparam
        if (gparam->mbuilder) {
                if (!gparam->mbuilder->generic_container) {
                        MonoReflectionTypeBuilder *tb = (MonoReflectionTypeBuilder *)gparam->mbuilder->type;
-                       MonoClass *klass = mono_class_from_mono_type (tb->type.type);
+                       MonoClass *klass = mono_class_from_mono_type (mono_reflection_type_get_handle ((MonoReflectionType*)tb));
                        gparam->mbuilder->generic_container = mono_image_alloc0 (klass->image, sizeof (MonoGenericContainer));
                        gparam->mbuilder->generic_container->is_method = TRUE;
                        /* 
@@ -10538,7 +10875,7 @@ mono_reflection_initialize_generic_parameter (MonoReflectionGenericParam *gparam
                param->param.owner = gparam->mbuilder->generic_container;
        } else if (gparam->tbuilder) {
                if (!gparam->tbuilder->generic_container) {
-                       MonoClass *klass = mono_class_from_mono_type (gparam->tbuilder->type.type);
+                       MonoClass *klass = mono_class_from_mono_type (mono_reflection_type_get_handle ((MonoReflectionType*)gparam->tbuilder));
                        gparam->tbuilder->generic_container = mono_image_alloc0 (klass->image, sizeof (MonoGenericContainer));
                        gparam->tbuilder->generic_container->owner.klass = klass;
                }
@@ -10555,12 +10892,16 @@ mono_reflection_initialize_generic_parameter (MonoReflectionGenericParam *gparam
 
        MOVING_GC_REGISTER (&pklass->reflection_info);
        pklass->reflection_info = gparam; /* FIXME: GC pin gparam */
+       mono_image_lock (image);
+       image->reflection_info_unregister_classes = g_slist_prepend (image->reflection_info_unregister_classes, pklass);
+       mono_image_unlock (image);
 }
 
 MonoArray *
 mono_reflection_sighelper_get_signature_local (MonoReflectionSigHelper *sig)
 {
-       MonoDynamicImage *assembly = sig->module->dynamic_image;
+       MonoReflectionModuleBuilder *module = sig->module;
+       MonoDynamicImage *assembly = module != NULL ? module->dynamic_image : NULL;
        guint32 na = sig->arguments ? mono_array_length (sig->arguments) : 0;
        guint32 buflen, i;
        MonoArray *result;
@@ -10572,9 +10913,11 @@ mono_reflection_sighelper_get_signature_local (MonoReflectionSigHelper *sig)
 
        sigbuffer_add_value (&buf, 0x07);
        sigbuffer_add_value (&buf, na);
-       for (i = 0; i < na; ++i) {
-               MonoReflectionType *type = mono_array_get (sig->arguments, MonoReflectionType*, i);
-               encode_reflection_type (assembly, type, &buf);
+       if (assembly != NULL){
+               for (i = 0; i < na; ++i) {
+                       MonoReflectionType *type = mono_array_get (sig->arguments, MonoReflectionType*, i);
+                       encode_reflection_type (assembly, type, &buf);
+               }
        }
 
        buflen = buf.p - buf.buf;
@@ -10676,7 +11019,7 @@ mono_reflection_create_dynamic_method (MonoReflectionDynamicMethod *mb)
                rmb.refs [i + 1] = handle_class;
        }               
 
-       klass = mb->owner ? mono_class_from_mono_type (mb->owner->type) : mono_defaults.object_class;
+       klass = mb->owner ? mono_class_from_mono_type (mono_reflection_type_get_handle ((MonoReflectionType*)mb->owner)) : mono_defaults.object_class;
 
        mb->mhandle = reflection_methodbuilder_to_mono_method (klass, &rmb, sig);
 
@@ -10796,16 +11139,16 @@ resolve_object (MonoImage *image, MonoObject *obj, MonoClass **handle_class, Mon
 
        if (strcmp (obj->vtable->klass->name, "String") == 0) {
                result = mono_string_intern ((MonoString*)obj);
-               *handle_class = NULL;
+               *handle_class = mono_defaults.string_class;
                g_assert (result);
        } else if (strcmp (obj->vtable->klass->name, "MonoType") == 0) {
-               MonoReflectionType *tb = (MonoReflectionType*)obj;
+               MonoType *type = mono_reflection_type_get_handle ((MonoReflectionType*)obj);
                if (context) {
-                       MonoType *inflated = mono_class_inflate_generic_type (tb->type, context);
+                       MonoType *inflated = mono_class_inflate_generic_type (type, context);
                        result = mono_class_from_mono_type (inflated);
                        mono_metadata_free_type (inflated);
                } else {
-                       result = mono_class_from_mono_type (tb->type);
+                       result = mono_class_from_mono_type (type);
                }
                *handle_class = mono_defaults.typehandle_class;
                g_assert (result);
@@ -10897,16 +11240,17 @@ resolve_object (MonoImage *image, MonoObject *obj, MonoClass **handle_class, Mon
                *handle_class = mono_defaults.fieldhandle_class;
        } else if (strcmp (obj->vtable->klass->name, "TypeBuilder") == 0) {
                MonoReflectionTypeBuilder *tb = (MonoReflectionTypeBuilder*)obj;
+               MonoType *type = mono_reflection_type_get_handle ((MonoReflectionType*)tb); 
                MonoClass *klass;
 
-               klass = tb->type.type->data.klass;
+               klass = type->data.klass;
                if (klass->wastypebuilder) {
                        /* Already created */
                        result = klass;
                }
                else {
                        mono_domain_try_type_resolve (mono_domain_get (), NULL, (MonoObject*)tb);
-                       result = tb->type.type->data.klass;
+                       result = type->data.klass;
                        g_assert (result);
                }
                *handle_class = mono_defaults.typehandle_class;
@@ -10947,15 +11291,15 @@ resolve_object (MonoImage *image, MonoObject *obj, MonoClass **handle_class, Mon
                result = method->mhandle;
                *handle_class = mono_defaults.methodhandle_class;
        } else if (strcmp (obj->vtable->klass->name, "GenericTypeParameterBuilder") == 0) {
-               MonoReflectionType *tb = (MonoReflectionType*)obj;
-               MonoType *type = mono_class_inflate_generic_type (tb->type, context);
+               MonoType *type = mono_reflection_type_get_handle ((MonoReflectionType*)obj);
+               type = mono_class_inflate_generic_type (type, context);
                result = mono_class_from_mono_type (type);
                *handle_class = mono_defaults.typehandle_class;
                g_assert (result);
                mono_metadata_free_type (type);
        } else if (strcmp (obj->vtable->klass->name, "MonoGenericClass") == 0) {
-               MonoReflectionGenericClass *ref = (MonoReflectionGenericClass*)obj;
-               MonoType *type = mono_class_inflate_generic_type (ref->type.type, context);
+               MonoType *type = mono_reflection_type_get_handle ((MonoReflectionType*)obj);
+               type = mono_class_inflate_generic_type (type, context);
                result = mono_class_from_mono_type (type);
                *handle_class = mono_defaults.typehandle_class;
                g_assert (result);
@@ -10965,7 +11309,7 @@ resolve_object (MonoImage *image, MonoObject *obj, MonoClass **handle_class, Mon
                MonoClass *inflated;
                MonoType *type;
 
-               type = mono_class_inflate_generic_type (f->inst->type.type, context);
+               type = mono_class_inflate_generic_type (mono_reflection_type_get_handle ((MonoReflectionType*)f->inst), context);
                inflated = mono_class_from_mono_type (type);
 
                g_assert (f->fb->handle);
@@ -10975,7 +11319,7 @@ resolve_object (MonoImage *image, MonoObject *obj, MonoClass **handle_class, Mon
                *handle_class = mono_defaults.fieldhandle_class;
        } else if (strcmp (obj->vtable->klass->name, "ConstructorOnTypeBuilderInst") == 0) {
                MonoReflectionCtorOnTypeBuilderInst *c = (MonoReflectionCtorOnTypeBuilderInst*)obj;
-               MonoType *type = mono_class_inflate_generic_type (c->inst->type.type, context);
+               MonoType *type = mono_class_inflate_generic_type (mono_reflection_type_get_handle ((MonoReflectionType*)c->inst), context);
                MonoClass *inflated_klass = mono_class_from_mono_type (type);
                g_assert (c->cb->mhandle);
                result = inflate_mono_method (inflated_klass, c->cb->mhandle, (MonoObject*)c->cb);
@@ -10983,19 +11327,25 @@ resolve_object (MonoImage *image, MonoObject *obj, MonoClass **handle_class, Mon
                mono_metadata_free_type (type);
        } else if (strcmp (obj->vtable->klass->name, "MethodOnTypeBuilderInst") == 0) {
                MonoReflectionMethodOnTypeBuilderInst *m = (MonoReflectionMethodOnTypeBuilderInst*)obj;
-               MonoType *type = mono_class_inflate_generic_type (m->inst->type.type, context);
-               MonoClass *inflated_klass = mono_class_from_mono_type (type);
-               g_assert (m->mb->mhandle);
-               result = inflate_mono_method (inflated_klass, m->mb->mhandle, (MonoObject*)m->mb);
+               if (m->method_args) {
+                       result = mono_reflection_method_on_tb_inst_get_handle (m);
+               } else {
+                       MonoType *type = mono_class_inflate_generic_type (mono_reflection_type_get_handle ((MonoReflectionType*)m->inst), context);
+                       MonoClass *inflated_klass = mono_class_from_mono_type (type);
+                       g_assert (m->mb->mhandle);
+                       result = inflate_mono_method (inflated_klass, m->mb->mhandle, (MonoObject*)m->mb);
+                       mono_metadata_free_type (type);
+               }
                *handle_class = mono_defaults.methodhandle_class;
-               mono_metadata_free_type (type);
-       } else if (strcmp (mono_object_get_class(obj)->name, "ArrayType") == 0) {
+       } else if (is_sre_array (mono_object_get_class(obj)) ||
+                               is_sre_byref (mono_object_get_class(obj)) ||
+                               is_sre_pointer (mono_object_get_class(obj))) {
                MonoReflectionType *ref_type = (MonoReflectionType *)obj;
                MonoType *type = mono_reflection_type_get_handle (ref_type);
                result = mono_class_from_mono_type (type);
                *handle_class = mono_defaults.typehandle_class;
        } else {
-               g_print (obj->vtable->klass->name);
+               g_print ("%s\n", obj->vtable->klass->name);
                g_assert_not_reached ();
        }
        return result;
@@ -11146,6 +11496,14 @@ mono_reflection_lookup_dynamic_token (MonoImage *image, guint32 token, gboolean
        return NULL;
 }
 
+MonoType*
+mono_reflection_type_get_handle (MonoReflectionType* ref)
+{
+       if (!ref)
+               return NULL;
+       return ref->type;
+}
+
 #endif /* DISABLE_REFLECTION_EMIT */
 
 /* SECURITY_ACTION_* are defined in mono/metadata/tabledefs.h */