merge 99244:99306
[mono.git] / mono / metadata / verify.c
index 9578df033d407197c881cee8a66a98835ee82b31..59c96c7d2b18bd679a4b2e7d30c2ace8ec568afb 100644 (file)
@@ -14,6 +14,7 @@
 #include <signal.h>
 #include <ctype.h>
 
+
 /*
  * Pull the list of opcodes
  */
@@ -26,46 +27,81 @@ enum {
 };
 #undef OPDEF
 
-#if DISABLE_LOGGING
-#define VERIFIER_DEBUG(code)
-#else
+#ifdef MONO_VERIFIER_DEBUG
 #define VERIFIER_DEBUG(code) do { code } while (0)
+#else
+#define VERIFIER_DEBUG(code)
 #endif
 
 //////////////////////////////////////////////////////////////////
-#define ADD_VERIFY_INFO(__ctx, __msg, __status)        \
+#define IS_STRICT_MODE(ctx) (((ctx)->level & MONO_VERIFY_NON_STRICT) == 0)
+#define IS_FAIL_FAST_MODE(ctx) (((ctx)->level & MONO_VERIFY_FAIL_FAST) == MONO_VERIFY_FAIL_FAST)
+#define IS_SKIP_VISIBILITY(ctx) (((ctx)->level & MONO_VERIFY_SKIP_VISIBILITY) == MONO_VERIFY_SKIP_VISIBILITY)
+
+#define ADD_VERIFY_INFO(__ctx, __msg, __status, __exception)   \
        do {    \
-               MonoVerifyInfo *vinfo = g_new (MonoVerifyInfo, 1);      \
-               vinfo->status = __status;       \
-               vinfo->message = ( __msg );     \
+               MonoVerifyInfoExtended *vinfo = g_new (MonoVerifyInfoExtended, 1);      \
+               vinfo->info.status = __status;  \
+               vinfo->info.message = ( __msg );        \
+               vinfo->exception_type = (__exception);  \
                (__ctx)->list = g_slist_prepend ((__ctx)->list, vinfo); \
        } while (0)
 
 #define ADD_VERIFY_ERROR(__ctx, __msg) \
        do {    \
-               ADD_VERIFY_INFO(__ctx, __msg, MONO_VERIFY_ERROR); \
+               ADD_VERIFY_INFO(__ctx, __msg, MONO_VERIFY_ERROR, MONO_EXCEPTION_INVALID_PROGRAM); \
                (__ctx)->valid = 0; \
        } while (0)
 
 #define CODE_NOT_VERIFIABLE(__ctx, __msg) \
        do {    \
                if ((__ctx)->verifiable) { \
-                       ADD_VERIFY_INFO(__ctx, __msg, MONO_VERIFY_NOT_VERIFIABLE); \
+                       ADD_VERIFY_INFO(__ctx, __msg, MONO_VERIFY_NOT_VERIFIABLE, MONO_EXCEPTION_UNVERIFIABLE_IL); \
                        (__ctx)->verifiable = 0; \
+                       if (IS_FAIL_FAST_MODE (__ctx)) \
+                               (__ctx)->valid = 0; \
                } \
        } while (0)
 
-#define UNMASK_TYPE(type) ((type) & TYPE_MASK)
-#define IS_MANAGED_POINTER(type) (((type) & POINTER_MASK) == POINTER_MASK)
+#define ADD_VERIFY_ERROR2(__ctx, __msg, __exception)   \
+       do {    \
+               ADD_VERIFY_INFO(__ctx, __msg, MONO_VERIFY_ERROR, __exception); \
+               (__ctx)->valid = 0; \
+       } while (0)
 
+#define CODE_NOT_VERIFIABLE2(__ctx, __msg, __exception) \
+       do {    \
+               if ((__ctx)->verifiable) { \
+                       ADD_VERIFY_INFO(__ctx, __msg, MONO_VERIFY_NOT_VERIFIABLE, __exception); \
+                       (__ctx)->verifiable = 0; \
+                       if (IS_FAIL_FAST_MODE (__ctx)) \
+                               (__ctx)->valid = 0; \
+               } \
+       } while (0)
+/*Flags to be used with ILCodeDesc::flags */
 enum {
+       /*Instruction has not been processed.*/
        IL_CODE_FLAG_NOT_PROCESSED  = 0,
-       IL_CODE_FLAG_SEEN = 1
+       /*Instruction was decoded by mono_method_verify loop.*/
+       IL_CODE_FLAG_SEEN = 1,
+       /*Instruction was target of a branch or is at a protected block boundary.*/
+       IL_CODE_FLAG_WAS_TARGET = 2,
+       /*Used by stack_init to avoid double initialize each entry.*/
+       IL_CODE_FLAG_STACK_INITED = 4,
+       /*Used by merge_stacks to decide if it should just copy the eval stack.*/
+       IL_CODE_STACK_MERGED = 8,
+       /*This instruction is part of the delegate construction sequence, it cannot be target of a branch.*/
+       IL_CODE_DELEGATE_SEQUENCE = 0x10,
+       /*This is a delegate created from a ldftn to a non final virtual method*/
+       IL_CODE_LDFTN_DELEGATE_NONFINAL_VIRTUAL = 0x20,
+       /*This is a call to a non final virtual method*/
+       IL_CODE_CALL_NONFINAL_VIRTUAL = 0x40,
 };
 
 typedef struct {
        MonoType *type;
        int stype;
+       MonoMethod *method;
 } ILStackDesc;
 
 
@@ -80,6 +116,7 @@ typedef struct {
        int max_stack;
        int verifiable;
        int valid;
+       int level;
 
        int code_size;
        ILCodeDesc *code;
@@ -87,10 +124,13 @@ typedef struct {
 
        MonoType **params;
        GSList *list;
+       /*Allocated fnptr MonoType that should be freed by us.*/
+       GSList *funptrs;
 
        int num_locals;
        MonoType **locals;
 
+       /*TODO get rid of target here, need_merge in mono_method_verify and hoist the merging code in the branching code*/
        int target;
 
        guint32 ip_offset;
@@ -100,8 +140,23 @@ typedef struct {
        MonoGenericContext *generic_context;
        MonoImage *image;
        MonoMethod *method;
+
+       /*This flag helps solving a corner case of delegate verification in that you cannot have a "starg 0" 
+        *on a method that creates a delegate for a non-final virtual method using ldftn*/
+       gboolean has_this_store;
+
+       guint32 prefix_set;
+       MonoType *constrained_type;
 } VerifyContext;
 
+static void
+merge_stacks (VerifyContext *ctx, ILCodeDesc *from, ILCodeDesc *to, int start, gboolean external);
+
+static int
+get_stack_type (MonoType *type);
+
+static gboolean
+mono_delegate_signature_equal (MonoMethodSignature *sig1, MonoMethodSignature *sig2);
 //////////////////////////////////////////////////////////////////
 
 
@@ -117,7 +172,7 @@ enum {
        /* value types and classes */
        TYPE_COMPLEX = 6,
        /* Number of types, used to define the size of the tables*/
-       TYPE_MAX = 8,           /* FIXME: This should probably be 7, but would require all the tables to be updated */
+       TYPE_MAX = 6,
 
        /* Used by tables to signal that a result is not verifiable*/
        NON_VERIFIABLE_RESULT = 0x80,
@@ -127,19 +182,32 @@ enum {
 
        /* The stack type is a managed pointer, unmask the value to res */
        POINTER_MASK = 0x100,
+       
+       /*Stack type with the pointer mask*/
+       RAW_TYPE_MASK = 0x10F,
 
        /* Controlled Mutability Manager Pointer */
        CMMP_MASK = 0x200,
+
+       /* The stack type is a null literal*/
+       NULL_LITERAL_MASK = 0x400,
+       
+       /**Used by ldarg.0 and family to let delegate verification happens.*/
+       THIS_POINTER_MASK = 0x800,
+
+       /**Signals that this is a boxed value type*/
+       BOXED_MASK = 0x1000,
+
 };
 
 static const char* const
-type_names [TYPE_MAX] = {
+type_names [TYPE_MAX + 1] = {
        "Invalid",
        "Int32",
        "Int64",
        "Native Int",
        "Float64",
-       "TYPE_PTR",             /* FIXME: Give an appropriate name */
+       "Native Pointer",
        "Complex"       
 };
 
@@ -147,22 +215,257 @@ enum {
        PREFIX_UNALIGNED = 1,
        PREFIX_VOLATILE  = 2,
        PREFIX_TAIL      = 4,
-       PREFIX_ADDR_MASK = 3,
-       PREFIX_FUNC_MASK = 4
+       PREFIX_CONSTRAINED = 8,
+       PREFIX_READONLY = 16
 };
+//////////////////////////////////////////////////////////////////
+
+
+/*Token validation macros and functions */
+#define IS_MEMBER_REF(token) (mono_metadata_token_table (token) == MONO_TABLE_MEMBERREF)
+#define IS_METHOD_DEF(token) (mono_metadata_token_table (token) == MONO_TABLE_METHOD)
+#define IS_METHOD_SPEC(token) (mono_metadata_token_table (token) == MONO_TABLE_METHODSPEC)
+#define IS_FIELD_DEF(token) (mono_metadata_token_table (token) == MONO_TABLE_FIELD)
+
+#define IS_TYPE_REF(token) (mono_metadata_token_table (token) == MONO_TABLE_TYPEREF)
+#define IS_TYPE_DEF(token) (mono_metadata_token_table (token) == MONO_TABLE_TYPEDEF)
+#define IS_TYPE_SPEC(token) (mono_metadata_token_table (token) == MONO_TABLE_TYPESPEC)
+#define IS_METHOD_DEF_OR_REF_OR_SPEC(token) (IS_METHOD_DEF (token) || IS_MEMBER_REF (token) || IS_METHOD_SPEC (token))
+#define IS_TYPE_DEF_OR_REF_OR_SPEC(token) (IS_TYPE_DEF (token) || IS_TYPE_REF (token) || IS_TYPE_SPEC (token))
+#define IS_FIELD_DEF_OR_REF(token) (IS_FIELD_DEF (token) || IS_MEMBER_REF (token))
+
+/*
+ * Verify if @token refers to a valid row on int's table.
+ */
+static gboolean
+token_bounds_check (MonoImage *image, guint32 token)
+{
+       if (image->dynamic)
+               return mono_reflection_is_valid_dynamic_token ((MonoDynamicImage*)image, token);
+       return image->tables [mono_metadata_token_table (token)].rows >= mono_metadata_token_index (token);
+}
+
+static MonoType *
+mono_type_create_fnptr_from_mono_method (VerifyContext *ctx, MonoMethod *method)
+{
+       MonoType *res = g_new0 (MonoType, 1);
+       //FIXME use mono_method_get_signature_full
+       res->data.method = mono_method_signature (method);
+       res->type = MONO_TYPE_FNPTR;
+       ctx->funptrs = g_slist_prepend (ctx->funptrs, res);
+       return res;
+}
+
+/*
+ * mono_type_is_enum_type:
+ * 
+ * Returns TRUE if @type is an enum type. 
+ */
+static gboolean
+mono_type_is_enum_type (MonoType *type)
+{
+       if (type->type == MONO_TYPE_VALUETYPE && type->data.klass->enumtype)
+               return TRUE;
+       if (type->type == MONO_TYPE_GENERICINST && type->data.generic_class->container_class->enumtype)
+               return TRUE;
+       return FALSE;
+}
+
+/*
+ * mono_type_is_value_type:
+ * 
+ * Returns TRUE if @type is named after @namespace.@name.
+ * 
+ */
+static gboolean
+mono_type_is_value_type (MonoType *type, const char *namespace, const char *name)
+{
+       return type->type == MONO_TYPE_VALUETYPE &&
+               !strcmp (namespace, type->data.klass->name_space) &&
+               !strcmp (name, type->data.klass->name);
+}
+/*
+ * mono_type_get_underlying_type_any:
+ * 
+ * This functions is just like mono_type_get_underlying_type but it doesn't care if the type is byref.
+ * 
+ * Returns the underlying type of @type regardless if it is byref or not.
+ */
+static MonoType*
+mono_type_get_underlying_type_any (MonoType *type)
+{
+       if (type->type == MONO_TYPE_VALUETYPE && type->data.klass->enumtype)
+               return type->data.klass->enum_basetype;
+       if (type->type == MONO_TYPE_GENERICINST && type->data.generic_class->container_class->enumtype)
+               return type->data.generic_class->container_class->enum_basetype;
+       return type;
+}
+
+static const char*
+mono_type_get_stack_name (MonoType *type)
+{
+       return type_names [get_stack_type (type) & TYPE_MASK];
+}
+
+#define CTOR_REQUIRED_FLAGS (METHOD_ATTRIBUTE_SPECIAL_NAME | METHOD_ATTRIBUTE_RT_SPECIAL_NAME)
+#define CTOR_INVALID_FLAGS (METHOD_ATTRIBUTE_STATIC)
+
+static gboolean
+mono_method_is_constructor (MonoMethod *method) 
+{
+       return ((method->flags & CTOR_REQUIRED_FLAGS) == CTOR_REQUIRED_FLAGS &&
+                       !(method->flags & CTOR_INVALID_FLAGS) &&
+                       !strcmp (".ctor", method->name));
+}
+
+
+static MonoClassField*
+verifier_load_field (VerifyContext *ctx, int token, MonoClass **klass, const char *opcode) {
+       MonoClassField *field;
+       
+       if (!IS_FIELD_DEF_OR_REF (token) || !token_bounds_check (ctx->image, token)) {
+               ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid field token 0x%x08x for %s at 0x%04x", token, opcode, ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE);
+               return NULL;
+       }
+
+       field = mono_field_from_token (ctx->image, token, klass, ctx->generic_context);
+       if (!field) {
+               ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Cannot load field from token 0x%08x for %s at 0x%04x", token, opcode, ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE);
+               return NULL;
+       }
+
+       return field;
+}
+
+static MonoMethod*
+verifier_load_method (VerifyContext *ctx, int token, const char *opcode) {
+       MonoMethod* method;
+       
+       if (!IS_METHOD_DEF_OR_REF_OR_SPEC (token) || !token_bounds_check (ctx->image, token)) {
+               ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid method token 0x%08x for %s at 0x%04x", token, opcode, ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE);
+               return NULL;
+       }
+
+       method = mono_get_method_full (ctx->image, token, NULL, ctx->generic_context);
+
+       if (!method) {
+               ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Cannot load method from token 0x%08x for %s at 0x%04x", token, opcode, ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE);
+               return NULL;
+       }
+       
+       return method;
+}
+
+static MonoType*
+verifier_load_type (VerifyContext *ctx, int token, const char *opcode) {
+       MonoType* type;
+       
+       if (!IS_TYPE_DEF_OR_REF_OR_SPEC (token) || !token_bounds_check (ctx->image, token)) {
+               ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid type token 0x%08x at 0x%04x", token, ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE);
+               return NULL;
+       }
+
+       type = mono_type_get_full (ctx->image, token, ctx->generic_context);
+
+       if (!type) {
+               ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Cannot load type from token 0x%08x for %s at 0x%04x", token, opcode, ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE);
+               return NULL;
+       }
+       return type;
+}
+
+
+/* stack_slot_get_type:
+ * 
+ * Returns the stack type of @value. This value includes POINTER_MASK.
+ * 
+ * Use this function to checks that account for a managed pointer.
+ */
+static gint32
+stack_slot_get_type (ILStackDesc *value)
+{
+       return value->stype & RAW_TYPE_MASK;
+}
+
+/* stack_slot_get_underlying_type:
+ * 
+ * Returns the stack type of @value. This value does not include POINTER_MASK.
+ * 
+ * Use this function is cases where the fact that the value could be a managed pointer is
+ * irrelevant. For example, field load doesn't care about this fact of type on stack.
+ */
+static gint32
+stack_slot_get_underlying_type (ILStackDesc *value)
+{
+       return value->stype & TYPE_MASK;
+}
+
+/* stack_slot_is_managed_pointer:
+ * 
+ * Returns TRUE is @value is a managed pointer.
+ */
+static gboolean
+stack_slot_is_managed_pointer (ILStackDesc *value)
+{
+       return (value->stype & POINTER_MASK) == POINTER_MASK;
+}
+
+/* stack_slot_is_managed_mutability_pointer:
+ * 
+ * Returns TRUE is @value is a managed mutability pointer.
+ */
+static G_GNUC_UNUSED gboolean
+stack_slot_is_managed_mutability_pointer (ILStackDesc *value)
+{
+       return (value->stype & CMMP_MASK) == CMMP_MASK;
+}
 
+/* stack_slot_is_null_literal:
+ * 
+ * Returns TRUE is @value is the null literal.
+ */
+static gboolean
+stack_slot_is_null_literal (ILStackDesc *value)
+{
+       return (value->stype & NULL_LITERAL_MASK) == NULL_LITERAL_MASK;
+}
+
+
+/* stack_slot_is_this_pointer:
+ * 
+ * Returns TRUE is @value is the this literal
+ */
+static gboolean
+stack_slot_is_this_pointer (ILStackDesc *value)
+{
+       return (value->stype & THIS_POINTER_MASK) == THIS_POINTER_MASK;
+}
 
+/* stack_slot_is_boxed_value:
+ * 
+ * Returns TRUE is @value is a boxed value
+ */
+static gboolean
+stack_slot_is_boxed_value (ILStackDesc *value)
+{
+       return (value->stype & BOXED_MASK) == BOXED_MASK;
+}
 
+static const char *
+stack_slot_get_name (ILStackDesc *value)
+{
+       return type_names [value->stype & TYPE_MASK];
+}
 //////////////////////////////////////////////////////////////////
 void
 mono_free_verify_list (GSList *list)
 {
-       MonoVerifyInfo *info;
+       MonoVerifyInfoExtended *info;
        GSList *tmp;
 
        for (tmp = list; tmp; tmp = tmp->next) {
                info = tmp->data;
-               g_free (info->message);
+               g_free (info->info.message);
                g_free (info);
        }
        g_slist_free (list);
@@ -170,17 +473,17 @@ mono_free_verify_list (GSList *list)
 
 #define ADD_ERROR(list,msg)    \
        do {    \
-               MonoVerifyInfo *vinfo = g_new (MonoVerifyInfo, 1);      \
-               vinfo->status = MONO_VERIFY_ERROR;      \
-               vinfo->message = (msg); \
+               MonoVerifyInfoExtended *vinfo = g_new (MonoVerifyInfoExtended, 1);      \
+               vinfo->info.status = MONO_VERIFY_ERROR; \
+               vinfo->info.message = (msg);    \
                (list) = g_slist_prepend ((list), vinfo);       \
        } while (0)
 
 #define ADD_WARN(list,code,msg)        \
        do {    \
-               MonoVerifyInfo *vinfo = g_new (MonoVerifyInfo, 1);      \
-               vinfo->status = (code); \
-               vinfo->message = (msg); \
+               MonoVerifyInfoExtended *vinfo = g_new (MonoVerifyInfoExtended, 1);      \
+               vinfo->info.status = (code);    \
+               vinfo->info.message = (msg);    \
                (list) = g_slist_prepend ((list), vinfo);       \
        } while (0)
 
@@ -803,75 +1106,9 @@ mono_image_verify_tables (MonoImage *image, int level)
        return g_slist_reverse (error_list);
 }
 
-
-static const char
-bin_num_table [TYPE_MAX] [TYPE_MAX] = {
-       {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
-       {TYPE_INV, TYPE_I4,  TYPE_INV, TYPE_PTR, TYPE_INV, TYPE_COMPLEX,  TYPE_INV, TYPE_INV},
-       {TYPE_INV, TYPE_INV, TYPE_I8,  TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
-       {TYPE_INV, TYPE_PTR, TYPE_INV, TYPE_PTR, TYPE_INV, TYPE_COMPLEX,  TYPE_INV, TYPE_INV},
-       {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_R8,  TYPE_INV, TYPE_INV, TYPE_INV},
-       {TYPE_INV, TYPE_COMPLEX,  TYPE_INV, TYPE_COMPLEX,  TYPE_INV, TYPE_PTR, TYPE_INV, TYPE_INV},
-       {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
-       {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV}
-};
-
-static const char 
-neg_table [] = {
-       TYPE_INV, TYPE_I4, TYPE_I8, TYPE_PTR, TYPE_R8, TYPE_INV, TYPE_INV, TYPE_INV
-};
-
-/* reduce the size of this table */
-static const char
-bin_int_table [TYPE_MAX] [TYPE_MAX] = {
-       {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
-       {TYPE_INV, TYPE_I4,  TYPE_INV, TYPE_PTR, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
-       {TYPE_INV, TYPE_INV, TYPE_I8,  TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
-       {TYPE_INV, TYPE_PTR, TYPE_INV, TYPE_PTR, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
-       {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
-       {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
-       {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
-       {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV}
-};
-
-static const char
-bin_comp_table [TYPE_MAX] [TYPE_MAX] = {
-       {0},
-       {0, 1, 0, 1, 0, 0, 0, 0},
-       {0, 0, 1, 0, 0, 0, 0, 0},
-       {0, 1, 0, 1, 0, 2, 0, 0},
-       {0, 0, 0, 0, 1, 0, 0, 0},
-       {0, 0, 0, 2, 0, 1, 0, 0},
-       {0, 0, 0, 0, 0, 0, 3, 0},
-       {0, 0, 0, 0, 0, 0, 0, 0},
-};
-
-/* reduce the size of this table */
-static const char
-shift_table [TYPE_MAX] [TYPE_MAX] = {
-       {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
-       {TYPE_INV, TYPE_I4,  TYPE_INV, TYPE_I4,  TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
-       {TYPE_INV, TYPE_I8,  TYPE_INV, TYPE_I8,  TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
-       {TYPE_INV, TYPE_PTR, TYPE_INV, TYPE_PTR, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
-       {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
-       {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
-       {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
-       {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV}
-};
-
-static const char 
-ldind_type [] = {
-       TYPE_I4, TYPE_I4, TYPE_I4, TYPE_I4, TYPE_I4, TYPE_I4, TYPE_I8, TYPE_PTR, TYPE_R8, TYPE_R8, TYPE_COMPLEX
-};
-
-static const char
-ldelem_type [] = {
-       TYPE_I4, TYPE_I4, TYPE_I4, TYPE_I4, TYPE_I4, TYPE_I4, TYPE_I8, TYPE_PTR, TYPE_R8, TYPE_R8, TYPE_COMPLEX
-};
-
 #define ADD_INVALID(list,msg)  \
        do {    \
-               MonoVerifyInfo *vinfo = g_new (MonoVerifyInfo, 1);      \
+               MonoVerifyInfoExtended *vinfo = g_new (MonoVerifyInfoExtended, 1);      \
                vinfo->status = MONO_VERIFY_ERROR;      \
                vinfo->message = (msg); \
                (list) = g_slist_prepend ((list), vinfo);       \
@@ -892,198 +1129,110 @@ ldelem_type [] = {
        } while (0)
 
 
-static void
-type_to_eval_stack_type (MonoType *type, ILStackDesc *stack, int take_addr) {
-       int t = type->type;
-
-       stack->type = type;
-       if (type->byref || take_addr) { /* fix double addr issue */
-               stack->stype = TYPE_COMPLEX;
-               return;
-       }
+static int
+in_any_block (MonoMethodHeader *header, guint offset)
+{
+       int i;
+       MonoExceptionClause *clause;
 
-handle_enum:
-       switch (t) {
-       case MONO_TYPE_I1:
-       case MONO_TYPE_U1:
-       case MONO_TYPE_BOOLEAN:
-       case MONO_TYPE_I2:
-       case MONO_TYPE_U2:
-       case MONO_TYPE_CHAR:
-       case MONO_TYPE_I4:
-       case MONO_TYPE_U4:
-               stack->stype = TYPE_I4;
-               return;
-       case MONO_TYPE_I:
-       case MONO_TYPE_U:
-       case MONO_TYPE_PTR:
-               stack->stype = TYPE_PTR;
-               return;
-       case MONO_TYPE_CLASS:
-       case MONO_TYPE_STRING:
-       case MONO_TYPE_OBJECT:
-       case MONO_TYPE_SZARRAY:
-       case MONO_TYPE_ARRAY:    
-               stack->stype = TYPE_COMPLEX;
-               return;
-       case MONO_TYPE_I8:
-       case MONO_TYPE_U8:
-               stack->stype = TYPE_I8;
-               return;
-       case MONO_TYPE_R4:
-       case MONO_TYPE_R8:
-               stack->stype = TYPE_R8;
-               return;
-       case MONO_TYPE_VALUETYPE:
-               if (type->data.klass->enumtype) {
-                       t = type->data.klass->enum_basetype->type;
-                       goto handle_enum;
-               } else {
-                       stack->stype = TYPE_COMPLEX;
-                       return;
-               }
-       default:
-               g_error ("unknown type %02x in eval stack type", type->type);
+       for (i = 0; i < header->num_clauses; ++i) {
+               clause = &header->clauses [i];
+               if (MONO_OFFSET_IN_CLAUSE (clause, offset))
+                       return 1;
+               if (MONO_OFFSET_IN_HANDLER (clause, offset))
+                       return 1;
+               if (MONO_OFFSET_IN_FILTER (clause, offset))
+                       return 1;
        }
-       return;
+       return 0;
 }
 
-static int
-type_from_op (int ins, ILStackDesc *arg) {
-       switch (ins) {
-       /* binops */
-       case CEE_ADD:
-       case CEE_SUB:
-       case CEE_MUL:
-       case CEE_DIV:
-       case CEE_REM:
-               /* FIXME: check unverifiable args for TYPE_COMPLEX */
-               return arg->stype = bin_num_table [arg->stype] [arg [1].stype];
-       case CEE_DIV_UN:
-       case CEE_REM_UN:
-       case CEE_AND:
-       case CEE_OR:
-       case CEE_XOR:
-               return arg->stype = bin_int_table [arg->stype] [arg [1].stype];
-       case CEE_SHL:
-       case CEE_SHR:
-       case CEE_SHR_UN:
-               return arg->stype = shift_table [arg->stype] [arg [1].stype];
-       case CEE_BEQ_S:
-       case CEE_BGE_S:
-       case CEE_BGT_S:
-       case CEE_BLE_S:
-       case CEE_BLT_S:
-       case CEE_BNE_UN_S:
-       case CEE_BGE_UN_S:
-       case CEE_BGT_UN_S:
-       case CEE_BLE_UN_S:
-       case CEE_BLT_UN_S:
-       case CEE_BEQ:
-       case CEE_BGE:
-       case CEE_BGT:
-       case CEE_BLE:
-       case CEE_BLT:
-       case CEE_BNE_UN:
-       case CEE_BGE_UN:
-       case CEE_BGT_UN:
-       case CEE_BLE_UN:
-       case CEE_BLT_UN:
-               /* FIXME: handle some specifics with ins->next->type */
-               return bin_comp_table [arg->stype] [arg [1].stype] ? TYPE_I4: TYPE_INV;
-       case 256+CEE_CEQ:
-       case 256+CEE_CGT:
-       case 256+CEE_CGT_UN:
-       case 256+CEE_CLT:
-       case 256+CEE_CLT_UN:
-               return arg->stype = bin_comp_table [arg->stype] [arg [1].stype] ? TYPE_I4: TYPE_INV;
-       /* unops */
-       case CEE_NEG:
-               return arg->stype = neg_table [arg->stype];
-       case CEE_NOT:
-               if (arg->stype >= TYPE_I4 && arg->stype <= TYPE_PTR)
-                       return arg->stype;
-               else
-                       return arg->stype = TYPE_INV;
-       case CEE_CONV_I1:
-       case CEE_CONV_U1:
-       case CEE_CONV_I2:
-       case CEE_CONV_U2:
-       case CEE_CONV_I4:
-       case CEE_CONV_U4:
-       case CEE_CONV_OVF_I1:
-       case CEE_CONV_OVF_U1:
-       case CEE_CONV_OVF_I2:
-       case CEE_CONV_OVF_U2:
-       case CEE_CONV_OVF_I4:
-       case CEE_CONV_OVF_U4:
-       case CEE_CONV_OVF_I1_UN:
-       case CEE_CONV_OVF_U1_UN:
-       case CEE_CONV_OVF_I2_UN:
-       case CEE_CONV_OVF_U2_UN:
-       case CEE_CONV_OVF_I4_UN:
-       case CEE_CONV_OVF_U4_UN:
-               if (arg->stype == TYPE_INV || arg->stype >= TYPE_COMPLEX)
-                       return arg->stype = TYPE_INV;
-               return arg->stype = TYPE_I4;
-       case CEE_CONV_I:
-       case CEE_CONV_U:
-       case CEE_CONV_OVF_I:
-       case CEE_CONV_OVF_U:
-       case CEE_CONV_OVF_I_UN:
-       case CEE_CONV_OVF_U_UN:
-               if (arg->stype == TYPE_INV || arg->stype == TYPE_COMPLEX)
-                       return arg->stype = TYPE_INV;
-               return arg->stype = TYPE_PTR;
-       case CEE_CONV_I8:
-       case CEE_CONV_U8:
-       case CEE_CONV_OVF_I8:
-       case CEE_CONV_OVF_U8:
-       case CEE_CONV_OVF_I8_UN:
-       case CEE_CONV_OVF_U8_UN:
-               return arg->stype = TYPE_I8;
-       case CEE_CONV_R4:
-       case CEE_CONV_R8:
-               return arg->stype = TYPE_R8;
-       default:
-               g_error ("opcode 0x%04x not handled in type from op", ins);
-               break;
+/*
+ * in_any_exception_block:
+ * 
+ * Returns TRUE is @offset is part of any exception clause (filter, handler, catch, finally or fault).
+ */
+static gboolean
+in_any_exception_block (MonoMethodHeader *header, guint offset)
+{
+       int i;
+       MonoExceptionClause *clause;
+
+       for (i = 0; i < header->num_clauses; ++i) {
+               clause = &header->clauses [i];
+               if (MONO_OFFSET_IN_HANDLER (clause, offset))
+                       return TRUE;
+               if (MONO_OFFSET_IN_FILTER (clause, offset))
+                       return TRUE;
        }
        return FALSE;
 }
 
+/*
+ * is_valid_branch_instruction:
+ *
+ * Verify if it's valid to perform a branch from @offset to @target.
+ * This should be used with br and brtrue/false.
+ * It returns 0 if valid, 1 for unverifiable and 2 for invalid.
+ * The major diferent from other similiar functions is that branching into a
+ * finally/fault block is invalid instead of just unverifiable.  
+ */
 static int
-in_any_block (MonoMethodHeader *header, guint offset)
+is_valid_branch_instruction (MonoMethodHeader *header, guint offset, guint target)
 {
        int i;
        MonoExceptionClause *clause;
 
        for (i = 0; i < header->num_clauses; ++i) {
                clause = &header->clauses [i];
-               if (MONO_OFFSET_IN_CLAUSE (clause, offset))
+               /*branching into a finally block is invalid*/
+               if ((clause->flags == MONO_EXCEPTION_CLAUSE_FINALLY || clause->flags == MONO_EXCEPTION_CLAUSE_FAULT) &&
+                       !MONO_OFFSET_IN_HANDLER (clause, offset) &&
+                       MONO_OFFSET_IN_HANDLER (clause, target))
+                       return 2;
+
+               if (clause->try_offset != target && (MONO_OFFSET_IN_CLAUSE (clause, offset) ^ MONO_OFFSET_IN_CLAUSE (clause, target)))
                        return 1;
-               if (MONO_OFFSET_IN_HANDLER (clause, offset))
+               if (MONO_OFFSET_IN_HANDLER (clause, offset) ^ MONO_OFFSET_IN_HANDLER (clause, target))
+                       return 1;
+               if (MONO_OFFSET_IN_FILTER (clause, offset) ^ MONO_OFFSET_IN_FILTER (clause, target))
                        return 1;
-               /* need to check filter ... */
        }
        return 0;
 }
 
+/*
+ * is_valid_cmp_branch_instruction:
+ * 
+ * Verify if it's valid to perform a branch from @offset to @target.
+ * This should be used with binary comparison branching instruction, like beq, bge and similars.
+ * It returns 0 if valid, 1 for unverifiable and 2 for invalid.
+ * 
+ * The major diferences from other similar functions are that most errors lead to invalid
+ * code and only branching out of finally, filter or fault clauses is unverifiable. 
+ */
 static int
-in_same_block (MonoMethodHeader *header, guint offset, guint target)
+is_valid_cmp_branch_instruction (MonoMethodHeader *header, guint offset, guint target)
 {
        int i;
        MonoExceptionClause *clause;
 
        for (i = 0; i < header->num_clauses; ++i) {
                clause = &header->clauses [i];
-               if (MONO_OFFSET_IN_CLAUSE (clause, offset) ^ MONO_OFFSET_IN_CLAUSE (clause, target))
-                       return 0;
+               /*branching out of a handler or finally*/
+               if (clause->flags != MONO_EXCEPTION_CLAUSE_NONE &&
+                       MONO_OFFSET_IN_HANDLER (clause, offset) &&
+                       !MONO_OFFSET_IN_HANDLER (clause, target))
+                       return 1;
+
+               if (clause->try_offset != target && (MONO_OFFSET_IN_CLAUSE (clause, offset) ^ MONO_OFFSET_IN_CLAUSE (clause, target)))
+                       return 2;
                if (MONO_OFFSET_IN_HANDLER (clause, offset) ^ MONO_OFFSET_IN_HANDLER (clause, target))
-                       return 0;
-               /* need to check filter ... */
+                       return 2;
+               if (MONO_OFFSET_IN_FILTER (clause, offset) ^ MONO_OFFSET_IN_FILTER (clause, target))
+                       return 2;
        }
-       return 1;
+       return 0;
 }
 
 /*
@@ -1099,32 +1248,97 @@ is_correct_leave (MonoMethodHeader *header, guint offset, guint target)
                clause = &header->clauses [i];
                if (clause->flags == MONO_EXCEPTION_CLAUSE_FINALLY && MONO_OFFSET_IN_HANDLER (clause, offset) && !MONO_OFFSET_IN_HANDLER (clause, target))
                        return 0;
-               /* need to check filter ... */
+               if (MONO_OFFSET_IN_FILTER (clause, offset))
+                       return 0;
        }
        return 1;
 }
 
-static int
-can_merge_stack (ILCodeDesc *a, ILCodeDesc *b)
+/*
+ * A rethrow can't happen outside of a catch handler.
+ */
+static int
+is_correct_rethrow (MonoMethodHeader *header, guint offset)
 {
-       if (!b->flags & IL_CODE_FLAG_SEEN) {
-               b->flags |= IL_CODE_FLAG_SEEN;
-               b->size = a->size;
-               /* merge types */
-               return 1;
+       int i;
+       MonoExceptionClause *clause;
+
+       for (i = 0; i < header->num_clauses; ++i) {
+               clause = &header->clauses [i];
+               if (MONO_OFFSET_IN_HANDLER (clause, offset))
+                       return 1;
+               if (MONO_OFFSET_IN_FILTER (clause, offset))
+                       return 1;
        }
-       if (a->size != b->size)
-               return 0;
-       /* merge types */
-       return 1;
+       return 0;
+}
+
+/*
+ * An endfinally can't happen outside of a finally/fault handler.
+ */
+static int
+is_correct_endfinally (MonoMethodHeader *header, guint offset)
+{
+       int i;
+       MonoExceptionClause *clause;
+
+       for (i = 0; i < header->num_clauses; ++i) {
+               clause = &header->clauses [i];
+               if (MONO_OFFSET_IN_HANDLER (clause, offset) && (clause->flags == MONO_EXCEPTION_CLAUSE_FAULT || clause->flags == MONO_EXCEPTION_CLAUSE_FINALLY))
+                       return 1;
+       }
+       return 0;
+}
+
+
+/*
+ * An endfilter can only happens inside a filter clause.
+ * In non-strict mode filter is allowed inside the handler clause too
+ */
+static MonoExceptionClause *
+is_correct_endfilter (VerifyContext *ctx, guint offset)
+{
+       int i;
+       MonoExceptionClause *clause;
+
+       for (i = 0; i < ctx->header->num_clauses; ++i) {
+               clause = &ctx->header->clauses [i];
+               if (clause->flags != MONO_EXCEPTION_CLAUSE_FILTER)
+                       continue;
+               if (MONO_OFFSET_IN_FILTER (clause, offset))
+                       return clause;
+               if (!IS_STRICT_MODE (ctx) && MONO_OFFSET_IN_HANDLER (clause, offset))
+                       return clause;
+       }
+       return NULL;
+}
+
+
+/*
+ * Non-strict endfilter can happens inside a try block or any handler block
+ */
+static int
+is_unverifiable_endfilter (VerifyContext *ctx, guint offset)
+{
+       int i;
+       MonoExceptionClause *clause;
+
+       for (i = 0; i < ctx->header->num_clauses; ++i) {
+               clause = &ctx->header->clauses [i];
+               if (MONO_OFFSET_IN_CLAUSE (clause, offset))
+                       return 1;
+       }
+       return 0;
 }
 
 static gboolean
 is_valid_bool_arg (ILStackDesc *arg)
 {
-       if (IS_MANAGED_POINTER (arg->stype))
+       if (stack_slot_is_managed_pointer (arg) || stack_slot_is_boxed_value (arg) || stack_slot_is_null_literal (arg))
                return TRUE;
-       switch (arg->stype) {
+
+
+       switch (stack_slot_get_underlying_type (arg)) {
        case TYPE_I4:
        case TYPE_I8:
        case TYPE_NATIVE_INT:
@@ -1154,89 +1368,14 @@ is_valid_bool_arg (ILStackDesc *arg)
 }
 
 
-static int
-can_store_type (ILStackDesc *arg, MonoType *type)
-{
-       int t = type->type;
-       if (type->byref && arg->stype != TYPE_COMPLEX)
-               return FALSE;
-handle_enum:
-       switch (t) {
-       case MONO_TYPE_VOID:
-               return FALSE;
-       case MONO_TYPE_I1:
-       case MONO_TYPE_U1:
-       case MONO_TYPE_BOOLEAN:
-       case MONO_TYPE_I2:
-       case MONO_TYPE_U2:
-       case MONO_TYPE_CHAR:
-       case MONO_TYPE_I4:
-       case MONO_TYPE_U4:
-               if (arg->stype == TYPE_I4 || arg->stype == TYPE_PTR)
-                       return TRUE;
-               return FALSE;
-       case MONO_TYPE_I:
-       case MONO_TYPE_U:
-       case MONO_TYPE_PTR:
-               return TRUE;
-       case MONO_TYPE_CLASS:
-       case MONO_TYPE_STRING:
-       case MONO_TYPE_OBJECT:
-       case MONO_TYPE_SZARRAY:
-       case MONO_TYPE_ARRAY:    
-               return TRUE; /* FIXME */
-       case MONO_TYPE_I8:
-       case MONO_TYPE_U8:
-               if (arg->stype == TYPE_I8)
-                       return TRUE;
-               return FALSE;
-       case MONO_TYPE_R4:
-       case MONO_TYPE_R8:
-               if (arg->stype == TYPE_R8)
-                       return TRUE;
-               return FALSE;
-       case MONO_TYPE_VALUETYPE:
-               if (type->data.klass->enumtype) {
-                       t = type->data.klass->enum_basetype->type;
-                       goto handle_enum;
-               } else {
-                       if (arg->type->data.klass != type->data.klass)
-                               return FALSE;
-                       return TRUE;
-               }
-       default:
-               g_error ("unknown type %02x in store type", type->type);
-       }
-       return FALSE;
-}
-
-static int
-stind_type (int op, int type) {
-       switch (op) {
-       case CEE_STIND_REF:
-               return type == TYPE_COMPLEX;
-       case CEE_STIND_I1:
-       case CEE_STIND_I2:
-       case CEE_STIND_I4:
-               return type == TYPE_I4;
-       case CEE_STIND_I8:
-               return type == TYPE_I8;
-       case CEE_STIND_R4:
-       case CEE_STIND_R8:
-               return type == TYPE_R8;
-       default:
-               g_assert_not_reached ();
-       }
-       return FALSE;
-}
-
-
 /*Type manipulation helper*/
 
 /*Returns the byref version of the supplied MonoType*/
 static MonoType*
 mono_type_get_type_byref (MonoType *type)
 {
+       if (type->byref)
+               return type;
        return &mono_class_from_mono_type (type)->this_arg;
 }
 
@@ -1245,19 +1384,30 @@ mono_type_get_type_byref (MonoType *type)
 static MonoType*
 mono_type_get_type_byval (MonoType *type)
 {
+       if (!type->byref)
+               return type;
        return &mono_class_from_mono_type (type)->byval_arg;
 }
 
+static MonoType*
+mono_type_from_stack_slot (ILStackDesc *slot)
+{
+       if (stack_slot_is_managed_pointer (slot))
+               return mono_type_get_type_byref (slot->type);
+       return slot->type;
+}
 
 /*Stack manipulation code*/
 
 static void
 stack_init (VerifyContext *ctx, ILCodeDesc *state) 
 {
+       if (state->flags & IL_CODE_FLAG_STACK_INITED)
+               return;
        state->size = 0;
-       if (!state->stack) {
+       state->flags |= IL_CODE_FLAG_STACK_INITED;
+       if (!state->stack)
                state->stack = g_new0 (ILStackDesc, ctx->max_stack);
-       }
 }
 
 static void
@@ -1272,6 +1422,7 @@ copy_stack_value (ILStackDesc *to, ILStackDesc *from)
 {
        to->stype = from->stype;
        to->type = from->type;
+       to->method = from->method;
 }
 
 static int
@@ -1297,7 +1448,7 @@ check_overflow (VerifyContext *ctx)
 static gboolean
 check_unmanaged_pointer (VerifyContext *ctx, ILStackDesc *value)
 {
-       if (value->stype == TYPE_PTR) {
+       if (stack_slot_get_type (value) == TYPE_PTR) {
                CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Unmanaged pointer is not a verifiable type at 0x%04x", ctx->ip_offset));
                return 0;
        }
@@ -1311,10 +1462,6 @@ check_unverifiable_type (VerifyContext *ctx, MonoType *type)
                CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Unmanaged pointer is not a verifiable type at 0x%04x", ctx->ip_offset));
                return 0;
        }
-       if (type->type == MONO_TYPE_TYPEDBYREF) {
-               CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("TypedByRef is not a verifiable type at 0x%04x", ctx->ip_offset));
-               return 0;
-       }
        return 1;
 }
 
@@ -1357,20 +1504,27 @@ stack_get (VerifyContext *ctx, int distance)
  * A boxable type can be either a reference or value type, but cannot be a byref type or an unmanaged pointer   
  * */
 static MonoType*
-get_boxable_mono_type (VerifyContext* ctx, int token)
+get_boxable_mono_type (VerifyContext* ctx, int token, const char *opcode)
 {
-       MonoType *type = mono_type_get_full (ctx->image, token, ctx->generic_context);
+       MonoType *type;
 
-       if (!type) {
-               ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Type (0x%08x) not found at 0x%04x", token, ctx->ip_offset));
+
+       if (!(type = verifier_load_type (ctx, token, opcode)))
                return NULL;
-       }
 
        if (type->byref && type->type != MONO_TYPE_TYPEDBYREF) {
-               ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid use of byref type at 0x%04x", ctx->ip_offset));
+               ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid use of byref type for %s at 0x%04x", opcode, ctx->ip_offset));
+               return NULL;
+       }
+
+       if (type->type == MONO_TYPE_VOID) {
+               ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid use of void type for %s at 0x%04x", opcode, ctx->ip_offset));
                return NULL;
        }
 
+       if (type->type == MONO_TYPE_TYPEDBYREF)
+               CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid use of typedbyref for %s at 0x%04x", opcode, ctx->ip_offset));
+
        check_unverifiable_type (ctx, type);
        return type;
 }
@@ -1441,19 +1595,57 @@ static const unsigned char cmp_br_eq_op [TYPE_MAX][TYPE_MAX] = {
        {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_I4},
 };
 
+static const unsigned char add_ovf_un_table [TYPE_MAX][TYPE_MAX] = {
+       {TYPE_I4, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV},
+       {TYPE_INV, TYPE_I8, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
+       {TYPE_NATIVE_INT, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV},
+       {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
+       {TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV, TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV, TYPE_INV, TYPE_INV},
+       {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
+};
+
+static const unsigned char sub_ovf_un_table [TYPE_MAX][TYPE_MAX] = {
+       {TYPE_I4, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV},
+       {TYPE_INV, TYPE_I8, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
+       {TYPE_NATIVE_INT, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV},
+       {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
+       {TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV, TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV, TYPE_NATIVE_INT | NON_VERIFIABLE_RESULT, TYPE_INV},
+       {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
+};
+
+static const unsigned char bin_ovf_table [TYPE_MAX][TYPE_MAX] = {
+       {TYPE_I4, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV},
+       {TYPE_INV, TYPE_I8, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
+       {TYPE_NATIVE_INT, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV},
+       {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
+       {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
+       {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
+};
+
+#ifdef MONO_VERIFIER_DEBUG
+
 /*debug helpers */
 static void
 dump_stack_value (ILStackDesc *value)
 {
-       printf ("[(%d)(%d)", value->type->type, value->stype);
+       printf ("[(%x)(%x)", value->type->type, value->stype);
+
+       if (stack_slot_is_this_pointer (value))
+               printf ("[this] ");
 
-       if (value->stype & CMMP_MASK)
+       if (stack_slot_is_boxed_value (value))
+               printf ("[boxed] ");
+
+       if (stack_slot_is_null_literal (value))
+               printf ("[null] ");
+
+       if (stack_slot_is_managed_mutability_pointer (value))
                printf ("Controled Mutability MP: ");
 
-       if (IS_MANAGED_POINTER (value->stype))
+       if (stack_slot_is_managed_pointer (value))
                printf ("Managed Pointer to: ");
 
-       switch (UNMASK_TYPE (value->stype)) {
+       switch (stack_slot_get_underlying_type (value)) {
                case TYPE_INV:
                        printf ("invalid type]"); 
                        return;
@@ -1497,12 +1689,22 @@ dump_stack_value (ILStackDesc *value)
                        case MONO_TYPE_GENERICINST:
                                printf ("complex] (inst of %s )", value->type->data.generic_class->container_class->name);
                                return;
-                       default:
-                               printf ("unknown complex %d type]\n", value->type->type);
-                               g_assert_not_reached ();
+                       case MONO_TYPE_VAR:
+                               printf ("complex] (type generic param !%d - %s) ", value->type->data.generic_param->num, value->type->data.generic_param->name);
+                               return;
+                       case MONO_TYPE_MVAR:
+                               printf ("complex] (method generic param !!%d - %s) ", value->type->data.generic_param->num, value->type->data.generic_param->name);
+                               return;
+                       default: {
+                               //should be a boxed value 
+                               char * name = mono_type_full_name (value->type);
+                               printf ("complex] %s", name);
+                               g_free (name);
+                               return;
+                               }
                        }
                default:
-                       printf ("unknown stack %d type]\n", value->stype);
+                       printf ("unknown stack %x type]\n", value->stype);
                        g_assert_not_reached ();
        }
 }
@@ -1517,19 +1719,7 @@ dump_stack_state (ILCodeDesc *state)
                dump_stack_value (state->stack + i);
        printf ("\n");
 }
-
-static void
-dump_context (VerifyContext *ctx, int code_size)
-{
-       int i;
-
-       for (i = 0; i < code_size; ++i) {
-               if (ctx->code [i].flags & IL_CODE_FLAG_SEEN) {
-                       printf ("opcode [%d]:\n\t", i);
-                       dump_stack_state (&ctx->code [i]);
-               }
-       }
-}
+#endif
 
 /*Returns TRUE if candidate array type can be assigned to target.
  *Both parameters MUST be of type MONO_TYPE_ARRAY (target->type == MONO_TYPE_ARRAY)
@@ -1592,14 +1782,25 @@ handle_enum:
        case MONO_TYPE_TYPEDBYREF:
                return TYPE_PTR | mask;
 
+       case MONO_TYPE_VAR:
+       case MONO_TYPE_MVAR:
+
        case MONO_TYPE_CLASS:
        case MONO_TYPE_STRING:
        case MONO_TYPE_OBJECT:
        case MONO_TYPE_SZARRAY:
        case MONO_TYPE_ARRAY:
-       case MONO_TYPE_GENERICINST:
                return TYPE_COMPLEX | mask;
 
+       case MONO_TYPE_GENERICINST:
+               if (mono_type_is_enum_type (type)) {
+                       type = mono_type_get_underlying_type_any (type);
+                       type_kind = type->type;
+                       goto handle_enum;
+               } else {
+                       return TYPE_COMPLEX | mask;
+               }
+
        case MONO_TYPE_I8:
        case MONO_TYPE_U8:
                return TYPE_I8 | mask;
@@ -1609,12 +1810,13 @@ handle_enum:
                return TYPE_R8 | mask;
 
        case MONO_TYPE_VALUETYPE:
-               if (type->data.klass->enumtype) {
-                       type = type->data.klass->enum_basetype;
+               if (mono_type_is_enum_type (type)) {
+                       type = mono_type_get_underlying_type_any (type);
                        type_kind = type->type;
                        goto handle_enum;
-               } else 
+               } else {
                        return TYPE_COMPLEX | mask;
+               }
 
        default:
                VERIFIER_DEBUG ( printf ("unknown type %02x in eval stack type\n", type->type); );
@@ -1624,13 +1826,13 @@ handle_enum:
 }
 
 /* convert MonoType to ILStackDesc format (stype) */
-static void
-set_stack_value (ILStackDesc *stack, MonoType *type, int take_addr, int override_byref)
+static gboolean
+set_stack_value (VerifyContext *ctx, ILStackDesc *stack, MonoType *type, int take_addr)
 {
        int mask = 0;
        int type_kind = type->type;
 
-       if ((type->byref && !override_byref) || take_addr)
+       if (type->byref || take_addr)
                mask = POINTER_MASK;
        /* TODO handle CMMP_MASK */
 
@@ -1647,18 +1849,18 @@ handle_enum:
        case MONO_TYPE_I4:
        case MONO_TYPE_U4:
                stack->stype = TYPE_I4 | mask;
-               return;
+               break;
        case MONO_TYPE_I:
        case MONO_TYPE_U:
                stack->stype = TYPE_NATIVE_INT | mask;
-               return;
+               break;
 
        /*FIXME: Do we need to check if it's a pointer to the method pointer? The spec says it' illegal to have that.*/
        case MONO_TYPE_FNPTR:
        case MONO_TYPE_PTR:
        case MONO_TYPE_TYPEDBYREF:
                stack->stype = TYPE_PTR | mask;
-               return;
+               break;
 
        case MONO_TYPE_CLASS:
        case MONO_TYPE_STRING:
@@ -1666,238 +1868,109 @@ handle_enum:
        case MONO_TYPE_SZARRAY:
        case MONO_TYPE_ARRAY:
 
-       case MONO_TYPE_GENERICINST:
+       case MONO_TYPE_VAR:
+       case MONO_TYPE_MVAR: 
                stack->stype = TYPE_COMPLEX | mask;
-               return;
+               break;
+               
+       case MONO_TYPE_GENERICINST:
+               if (mono_type_is_enum_type (type)) {
+                       type = mono_type_get_underlying_type_any (type);
+                       type_kind = type->type;
+                       goto handle_enum;
+               } else {
+                       stack->stype = TYPE_COMPLEX | mask;
+                       break;
+               }
+
        case MONO_TYPE_I8:
        case MONO_TYPE_U8:
                stack->stype = TYPE_I8 | mask;
-               return;
+               break;
        case MONO_TYPE_R4:
        case MONO_TYPE_R8:
                stack->stype = TYPE_R8 | mask;
-               return;
+               break;
        case MONO_TYPE_VALUETYPE:
-               if (type->data.klass->enumtype) {
-                       type = type->data.klass->enum_basetype;
+               if (mono_type_is_enum_type (type)) {
+                       type = mono_type_get_underlying_type_any (type);
                        type_kind = type->type;
                        goto handle_enum;
                } else {
                        stack->stype = TYPE_COMPLEX | mask;
-                       return;
+                       break;
                }
        default:
                VERIFIER_DEBUG ( printf ("unknown type 0x%02x in eval stack type\n", type->type); );
-               g_assert_not_reached ();
+               ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Illegal value set on stack 0x%02x at %d", type->type, ctx->ip_offset));
+               return FALSE;
        }
-       return;
+       return TRUE;
+}
+
+/* 
+ * init_stack_with_value_at_exception_boundary:
+ * 
+ * Initialize the stack and push a given type.
+ * The instruction is marked as been on the exception boundary.
+ */
+static void
+init_stack_with_value_at_exception_boundary (VerifyContext *ctx, ILCodeDesc *code, MonoClass *klass)
+{
+       stack_init (ctx, code);
+       set_stack_value (ctx, code->stack, &klass->byval_arg, FALSE);
+       code->size = 1;
+       code->flags |= IL_CODE_FLAG_WAS_TARGET;
 }
 
-/* Generics validation stuff, should be moved to another metadata/? file */
+/*Verify if type 'candidate' can be stored in type 'target'.
+ * 
+ * If strict, check for the underlying type and not the verification stack types
+ */
 static gboolean
-mono_is_generic_type_compatible (MonoType *target, MonoType *candidate)
+verify_type_compatibility_full (VerifyContext *ctx, MonoType *target, MonoType *candidate, gboolean strict)
 {
-       if (target->byref != candidate->byref)
+#define IS_ONE_OF3(T, A, B, C) (T == A || T == B || T == C)
+#define IS_ONE_OF2(T, A, B) (T == A || T == B)
+
+       MonoType *original_candidate = candidate;
+       VERIFIER_DEBUG ( printf ("checking type compatibility %p %p[%x][%x] %p[%x][%x]\n", ctx, target, target->type, target->byref, candidate, candidate->type, candidate->byref); );
+
+       /*only one is byref */
+       if (candidate->byref ^ target->byref) {
+               /* converting from native int to byref*/
+               if (get_stack_type (candidate) == TYPE_NATIVE_INT && target->byref) {
+                       CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("using byref native int at 0x%04x", ctx->ip_offset));
+                       return TRUE;
+               }
                return FALSE;
+       }
+       strict |= target->byref;
+       /*From now on we don't care about byref anymore, so it's ok to discard it here*/
+       candidate = mono_type_get_underlying_type_any (candidate);
 
 handle_enum:
        switch (target->type) {
-       case MONO_TYPE_STRING:
-               if (candidate->type == MONO_TYPE_STRING)
-                       return TRUE;
-               return FALSE;
-
-       case MONO_TYPE_CLASS:
-               if (candidate->type != MONO_TYPE_CLASS)
-                       return FALSE;
-
-               VERIFIER_DEBUG ( printf ("verifying type class %p %p\n", target->data.klass, candidate->data.klass); );
-               return mono_class_is_assignable_from (target->data.klass, candidate->data.klass);
-
-       case MONO_TYPE_OBJECT:
-               return MONO_TYPE_IS_REFERENCE (candidate);
-
-       case MONO_TYPE_SZARRAY:
-               if (candidate->type != MONO_TYPE_SZARRAY)
-                       return FALSE;
-               return mono_class_is_assignable_from (target->data.klass, candidate->data.klass);
-
-       case MONO_TYPE_VALUETYPE:
-               if (target->data.klass->enumtype) {
-                       target = target->data.klass->enum_basetype;
-                       goto handle_enum;
-               } else {
-                       if (candidate->type != MONO_TYPE_VALUETYPE)
-                               return FALSE;
-                       return candidate->data.klass == target->data.klass;
-               }
-
-       case MONO_TYPE_ARRAY:
-               if (candidate->type != MONO_TYPE_ARRAY)
-                       return FALSE;
-               return is_array_type_compatible (target, candidate);
-
-       default:
-               VERIFIER_DEBUG ( printf ("unknown target type %d\n", target->type); );
-               g_assert_not_reached ();
-       }
-
-       return FALSE;
-}
-
-
-static gboolean
-mono_is_generic_instance_compatible (MonoGenericClass *target, MonoGenericClass *candidate, MonoGenericClass *root_candidate) {
-       MonoGenericContainer *container;
-       int i;
-
-       VERIFIER_DEBUG ( printf ("candidate container %p\n", candidate->container_class->generic_container); );
-       if (target->container_class != candidate->container_class) {
-               MonoType *param_class;
-               MonoClass *cand_class;
-               VERIFIER_DEBUG ( printf ("generic class != target\n"); );
-               param_class = candidate->context.class_inst->type_argv [0];
-               VERIFIER_DEBUG ( printf ("param 0 %d\n", param_class->type); );
-               cand_class = candidate->container_class;
-
-               /* We must check if it's an interface type*/
-               if (MONO_CLASS_IS_INTERFACE (target->container_class)) {
-                       VERIFIER_DEBUG ( printf ("generic type is an interface\n"); );
-
-                       do {
-                               int iface_count = cand_class->interface_count;
-                               MonoClass **ifaces = cand_class->interfaces;
-                               int i;
-                               VERIFIER_DEBUG ( printf ("type has %d interfaces\n", iface_count); );
-                               for (i = 0; i< iface_count; ++i) {
-                                       MonoClass *ifc = ifaces[i];
-                                       VERIFIER_DEBUG ( printf ("analysing %s\n", ifc->name); );
-                                       if (ifc->generic_class) {
-                                               VERIFIER_DEBUG ( printf ("interface has generic info\n"); );
-                                       }
-                                       if (mono_is_generic_instance_compatible (target, ifc->generic_class, root_candidate)) {
-                                               VERIFIER_DEBUG ( printf ("we got compatible stuff!\n"); );
-                                               return TRUE;
-                                       }
-                               }
-
-                               cand_class = cand_class->parent;
-                       } while (cand_class);
-
-                       VERIFIER_DEBUG ( printf ("don't implements an interface\n"); );
-
-               } else {
-                       VERIFIER_DEBUG ( printf ("verifying upper classes\n"); );
-
-                       cand_class = cand_class->parent;
-
-                       while (cand_class) {
-                               VERIFIER_DEBUG ( printf ("verifying parent class name %s\n", cand_class->name); );      
-                               if (cand_class->generic_class) {
-                                       VERIFIER_DEBUG ( printf ("super type has generic context\n"); );
-
-                                       /* TODO break loop if target->container_class == cand_class->generic_class->container_class */
-                                       return mono_is_generic_instance_compatible (target, cand_class->generic_class, root_candidate);
-                               } else
-                                       VERIFIER_DEBUG ( printf ("super class has no generic context\n"); );
-                               cand_class = cand_class->parent;
-                       }
-               }
-               return FALSE;
-       }
-
-       /* now we verify if the instantiations are compatible*/ 
-       if (target->context.class_inst == candidate->context.class_inst) {
-               VERIFIER_DEBUG ( printf ("generic types are compatible, both have the same instantiation\n"); );
-               return TRUE;
-       }
-
-       if (target->context.class_inst->type_argc != candidate->context.class_inst->type_argc) {
-               VERIFIER_DEBUG ( printf ("generic instantiations with diferent arg counts\n"); );
-               return FALSE;
-       }
-
-       //verify if open instance -- none should be 
-
-       container = target->container_class->generic_container;
-
-       for (i = 0; i < container->type_argc; ++i) {
-               MonoGenericParam *param = container->type_params + i;
-               MonoType *target_type = target->context.class_inst->type_argv [i];
-               MonoType *candidate_type = candidate->context.class_inst->type_argv [i];
-               /* We resolve TYPE_VAR types before proceeding */
-
-               if (candidate_type->type == MONO_TYPE_VAR) {
-                       MonoGenericParam *var_param = candidate_type->data.generic_param;
-                       candidate_type = root_candidate->context.class_inst->type_argv [var_param->num];
-               }
-
-               if ((param->flags & GENERIC_PARAMETER_ATTRIBUTE_VARIANCE_MASK) == 0) {
-                       VERIFIER_DEBUG ( printf ("generic type have no variance flag, checking each type %d %d \n",target_type->type, candidate_type->type); );
-
-                       if (!mono_metadata_type_equal (target_type, candidate_type))
-                               return FALSE;
-               } else {
-                       VERIFIER_DEBUG ( printf ("generic type has variance flag, need to perform deeper check\n"); );
-                       /* first we check if they are the same kind */
-                       /* byref generic params are forbiden, but better safe than sorry.*/
-
-                       if ((param->flags & GENERIC_PARAMETER_ATTRIBUTE_COVARIANT) == GENERIC_PARAMETER_ATTRIBUTE_COVARIANT) {
-                               if (!mono_is_generic_type_compatible (target_type, candidate_type))
-                                       return FALSE;
-                       /* the attribute must be contravariant */
-                       } else if (!mono_is_generic_type_compatible (candidate_type, target_type))
-                               return FALSE;
-               }
-       }
-       return TRUE;
-}
-
-
-
-/*Verify if type 'candidate' can be stored in type 'target'.
- * 
- * If strict, check for the underlying type and not the verification stack types
- */
-static gboolean
-verify_stack_type_compatibility (VerifyContext *ctx, MonoType *target, MonoType *candidate, gboolean strict) {
-#define IS_ONE_OF3(T, A, B, C) (T == A || T == B || T == C)
-#define IS_ONE_OF2(T, A, B) (T == A || T == B)
-
-       VERIFIER_DEBUG ( printf ("checking type compatibility %p %p[%d][%d] %p[%d][%d]\n", ctx, target, target->type, target->byref, candidate, candidate->type, candidate->byref); );
-
-       /*only one is byref */
-       if (candidate->byref ^ target->byref) {
-               /* converting from native int to byref*/
-               if (get_stack_type (candidate) == TYPE_NATIVE_INT && target->byref) {
-                       CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("using byref native int at 0x%04x", ctx->ip_offset));
-                       return TRUE;
-               }
-               return FALSE;
-       }
-
-handle_enum:
-       switch (target->type) {
-       case MONO_TYPE_I1:
-       case MONO_TYPE_U1:
-       case MONO_TYPE_BOOLEAN:
-               if (strict)
-                       return IS_ONE_OF3 (candidate->type, MONO_TYPE_I1, MONO_TYPE_U1, MONO_TYPE_BOOLEAN);
-       case MONO_TYPE_I2:
-       case MONO_TYPE_U2:
-       case MONO_TYPE_CHAR:
-               if (strict)
-                       return IS_ONE_OF3 (candidate->type, MONO_TYPE_I2, MONO_TYPE_U2, MONO_TYPE_CHAR);
-               return get_stack_type (candidate) == TYPE_I4;
-
-       case MONO_TYPE_I4:
-       case MONO_TYPE_U4: {
-               gboolean is_native_int = IS_ONE_OF2 (candidate->type, MONO_TYPE_I, MONO_TYPE_U);
-               gboolean is_int4 = IS_ONE_OF2 (candidate->type, MONO_TYPE_I4, MONO_TYPE_U4);
-               if (strict)
-                       return is_native_int || is_int4;
-               return is_native_int || get_stack_type (candidate) == TYPE_I4;
-       }
+       case MONO_TYPE_VOID:
+               return candidate->type == MONO_TYPE_VOID;
+       case MONO_TYPE_I1:
+       case MONO_TYPE_U1:
+       case MONO_TYPE_BOOLEAN:
+               if (strict)
+                       return IS_ONE_OF3 (candidate->type, MONO_TYPE_I1, MONO_TYPE_U1, MONO_TYPE_BOOLEAN);
+       case MONO_TYPE_I2:
+       case MONO_TYPE_U2:
+       case MONO_TYPE_CHAR:
+               if (strict)
+                       return IS_ONE_OF3 (candidate->type, MONO_TYPE_I2, MONO_TYPE_U2, MONO_TYPE_CHAR);
+       case MONO_TYPE_I4:
+       case MONO_TYPE_U4: {
+               gboolean is_native_int = IS_ONE_OF2 (candidate->type, MONO_TYPE_I, MONO_TYPE_U);
+               gboolean is_int4 = IS_ONE_OF2 (candidate->type, MONO_TYPE_I4, MONO_TYPE_U4);
+               if (strict)
+                       return is_native_int || is_int4;
+               return is_native_int || get_stack_type (candidate) == TYPE_I4;
+       }
 
        case MONO_TYPE_I8:
        case MONO_TYPE_U8:
@@ -1913,14 +1986,18 @@ handle_enum:
        case MONO_TYPE_U: {
                gboolean is_native_int = IS_ONE_OF2 (candidate->type, MONO_TYPE_I, MONO_TYPE_U);
                gboolean is_int4 = IS_ONE_OF2 (candidate->type, MONO_TYPE_I4, MONO_TYPE_U4);
-               return is_native_int || is_int4;
+               if (strict)
+                       return is_native_int || is_int4;
+               return is_native_int || get_stack_type (candidate) == TYPE_I4;
        }
 
        case MONO_TYPE_PTR:
+               if (!IS_STRICT_MODE (ctx) && IS_ONE_OF2 (candidate->type, MONO_TYPE_I, MONO_TYPE_U))
+                       return TRUE;
                if (candidate->type != MONO_TYPE_PTR)
                        return FALSE;
                /* check the underlying type */
-               return verify_stack_type_compatibility (ctx, target->data.type, candidate->data.type, TRUE);
+               return verify_type_compatibility_full (ctx, target->data.type, candidate->data.type, TRUE);
 
        case MONO_TYPE_FNPTR: {
                MonoMethodSignature *left, *right;
@@ -1933,23 +2010,21 @@ handle_enum:
        }
 
        case MONO_TYPE_GENERICINST: {
-               MonoGenericClass *left;
-               MonoGenericClass *right;
-               if (candidate->type != MONO_TYPE_GENERICINST)
-                       return FALSE;
-               left = target->data.generic_class;
-               right = candidate->data.generic_class;
-
-               return mono_is_generic_instance_compatible (left, right, right);
+               if (mono_type_is_enum_type (target)) {
+                       target = mono_type_get_underlying_type_any (target);
+                       goto handle_enum;
+               }
+               return mono_class_is_assignable_from (mono_class_from_mono_type (target), mono_class_from_mono_type (candidate));
        }
 
        case MONO_TYPE_STRING:
                return candidate->type == MONO_TYPE_STRING;
 
        case MONO_TYPE_CLASS:
-               if (candidate->type != MONO_TYPE_CLASS)
-                       return FALSE;
-               return mono_class_is_assignable_from (target->data.klass, candidate->data.klass);
+               /* If candidate is an enum it should return true for System.Enum and supertypes.
+                * That's why here we use the original type and not the underlying type.
+                */ 
+               return mono_class_is_assignable_from (target->data.klass, mono_class_from_mono_type (original_candidate));
 
        case MONO_TYPE_OBJECT:
                return MONO_TYPE_IS_REFERENCE (candidate);
@@ -1970,19 +2045,27 @@ handle_enum:
                        return FALSE;
                return is_array_type_compatible (target, candidate);
 
-       //TODO verify aditional checks that needs to be done
        case MONO_TYPE_TYPEDBYREF:
                return candidate->type == MONO_TYPE_TYPEDBYREF;
 
        case MONO_TYPE_VALUETYPE:
-               if (target->data.klass->enumtype) {
-                       target = target->data.klass->enum_basetype;
+               if (candidate->type == MONO_TYPE_VALUETYPE && target->data.klass == candidate->data.klass)
+                       return TRUE;
+               if (mono_type_is_enum_type (target)) {
+                       target = mono_type_get_underlying_type_any (target);
                        goto handle_enum;
-               } else {
-                       if (candidate->type != MONO_TYPE_VALUETYPE)
-                               return FALSE;
-                       return target->data.klass == candidate->data.klass;
                }
+               return FALSE;
+
+       case MONO_TYPE_VAR:
+               if (candidate->type != MONO_TYPE_VAR)
+                       return FALSE;
+               return candidate->data.generic_param->num == target->data.generic_param->num;
+
+       case MONO_TYPE_MVAR:
+               if (candidate->type != MONO_TYPE_MVAR)
+                       return FALSE;
+               return candidate->data.generic_param->num == target->data.generic_param->num;
 
        default:
                VERIFIER_DEBUG ( printf ("unknown store type %d\n", target->type); );
@@ -1994,25 +2077,54 @@ handle_enum:
 #undef IS_ONE_OF2
 }
 
+static gboolean
+verify_type_compatibility (VerifyContext *ctx, MonoType *target, MonoType *candidate)
+{
+       return verify_type_compatibility_full (ctx, target, candidate, FALSE);
+}
+
+/*
+ * is_compatible_boxed_valuetype:
+ * 
+ * Returns TRUE if @candidate / @stack is a valid boxed valuetype. 
+ * 
+ * @type The source type. It it tested to be of the proper type.    
+ * @candidate type of the boxed valuetype.
+ * @stack stack slot of the boxed valuetype, separate from @candidade since one could be changed before calling this function
+ * @type_must_be_object if TRUE @type must be System.Object, otherwise can be any reference type.
+ * 
+ */
+static gboolean
+is_compatible_boxed_valuetype (MonoType *type, MonoType *candidate, ILStackDesc *stack, gboolean type_must_be_object)
+{
+       if (type_must_be_object && type->type != MONO_TYPE_OBJECT)
+               return FALSE;
+       if (!type_must_be_object && !MONO_TYPE_IS_REFERENCE (type))
+               return FALSE;
+       return !type->byref && !candidate->byref && stack_slot_is_boxed_value (stack);
+}
+
 static int
-verify_type_compat (VerifyContext *ctx, MonoType *type, ILStackDesc *stack) {
-       int stack_type = stack->stype;
-       VERIFIER_DEBUG ( printf ("checking compatibility %p %p[%d] %p[%d]\n", ctx, type, type->type, stack, stack_type ); );
+verify_stack_type_compatibility (VerifyContext *ctx, MonoType *type, ILStackDesc *stack)
+{
+       MonoType *candidate = mono_type_from_stack_slot (stack);
+       if (MONO_TYPE_IS_REFERENCE (type) && !type->byref && stack_slot_is_null_literal (stack))
+               return TRUE;
 
-       /*only one is byref */
-       if (type->byref ^ IS_MANAGED_POINTER (stack_type)) {
-               /* converting from native int to byref*/
-               if (type->byref && stack_type == TYPE_NATIVE_INT) {
-                       CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("using byref native int at 0x%04x", ctx->ip_offset));
-                       return TRUE;
-               }
+       if (is_compatible_boxed_valuetype (type, candidate, stack, TRUE))
+               return TRUE;
+
+       return verify_type_compatibility_full (ctx, type, candidate, FALSE);
+}
+
+static gboolean
+mono_delegate_type_equal (MonoType *target, MonoType *candidate)
+{
+       if (candidate->byref ^ target->byref)
                return FALSE;
-       }
-       if (type->byref)
-               return verify_stack_type_compatibility (ctx, type, mono_type_get_type_byref (stack->type), TRUE);
 
-handle_enum:
-       switch (type->type) {
+       switch (target->type) {
+       case MONO_TYPE_VOID:
        case MONO_TYPE_I1:
        case MONO_TYPE_U1:
        case MONO_TYPE_BOOLEAN:
@@ -2021,171 +2133,263 @@ handle_enum:
        case MONO_TYPE_CHAR:
        case MONO_TYPE_I4:
        case MONO_TYPE_U4:
-               return stack_type == TYPE_I4;
-
        case MONO_TYPE_I8:
        case MONO_TYPE_U8:
-               return stack_type == TYPE_I8;
-
        case MONO_TYPE_R4:
        case MONO_TYPE_R8:
-               return stack_type == TYPE_R8;
-
        case MONO_TYPE_I:
        case MONO_TYPE_U:
-               return stack_type == TYPE_NATIVE_INT || stack_type == TYPE_I4;
+       case MONO_TYPE_STRING:
+       case MONO_TYPE_TYPEDBYREF:
+               return candidate->type == target->type;
 
        case MONO_TYPE_PTR:
-               if (stack_type != TYPE_PTR || stack->type->type != MONO_TYPE_PTR)
-                       return FALSE;
-               return verify_stack_type_compatibility (ctx, type->data.type, stack->type->data.type, TRUE);
-
-       case MONO_TYPE_FNPTR: {
-               MonoMethodSignature *left, *right;
-               if (stack_type != TYPE_PTR || stack->type->type != MONO_TYPE_FNPTR)
-                       return FALSE;
-
-               left = mono_type_get_signature (type);
-               right = mono_type_get_signature (stack->type);
-               return mono_metadata_signature_equal (left, right) && left->call_convention == right->call_convention;
-       }
-
-       case MONO_TYPE_GENERICINST: {
-               MonoGenericClass *left;
-               MonoGenericClass *right;
-               if (stack_type != TYPE_COMPLEX)
-                       return FALSE;
-               g_assert (stack->type);
-               if (stack->type->type != MONO_TYPE_GENERICINST)
-                       return FALSE;
-               left = type->data.generic_class;
-               right = stack->type->data.generic_class;
-
-               return mono_is_generic_instance_compatible (left, right, right);
-       }
+               return mono_delegate_type_equal (target->data.type, candidate->data.type);
 
-       case MONO_TYPE_STRING:
-               if (stack_type != TYPE_COMPLEX)
-                       return FALSE;
-               g_assert (stack->type);
-               return stack->type->type == MONO_TYPE_STRING;
-
-       case MONO_TYPE_CLASS:
-               if (stack_type != TYPE_COMPLEX)
-                       return FALSE;
-               g_assert (stack->type);
-               if (stack->type->type != MONO_TYPE_CLASS)
+       case MONO_TYPE_FNPTR:
+               if (candidate->type != MONO_TYPE_FNPTR)
                        return FALSE;
+               return mono_delegate_signature_equal (mono_type_get_signature (target), mono_type_get_signature (candidate));
 
-               return mono_class_is_assignable_from (type->data.klass, stack->type->data.klass);
+       case MONO_TYPE_GENERICINST:
+               //TODO implement me
+               g_assert_not_reached ();
+               return FALSE;
 
+               return candidate->type == MONO_TYPE_STRING;
+       
        case MONO_TYPE_OBJECT:
-               if (stack_type != TYPE_COMPLEX)
-                       return FALSE;
-               g_assert (stack->type);
-               return MONO_TYPE_IS_REFERENCE (stack->type);
+               return MONO_TYPE_IS_REFERENCE (candidate);
 
-       case MONO_TYPE_SZARRAY: {
-               MonoClass *left;
-               MonoClass *right;
-               if (stack_type != TYPE_COMPLEX)
+       case MONO_TYPE_CLASS:
+               if (candidate->type != MONO_TYPE_CLASS)
                        return FALSE;
+               return mono_class_is_assignable_from(target->data.klass, candidate->data.klass);
 
-               g_assert (stack->type);
-
-               if (stack->type->type != type->type)
+       case MONO_TYPE_SZARRAY:
+               if (candidate->type != MONO_TYPE_SZARRAY)
                        return FALSE;
-               left = type->data.klass ;
-               right = stack->type->data.klass;
-               return mono_class_is_assignable_from (left, right);
-       }
+               return mono_class_is_assignable_from (target->data.array->eklass, candidate->data.array->eklass);
 
        case MONO_TYPE_ARRAY:
-               if (stack_type != TYPE_COMPLEX)
-                       return FALSE;
-               g_assert (stack->type);
-               if (stack->type->type != MONO_TYPE_ARRAY)
-                       return FALSE;
-               return is_array_type_compatible (type, stack->type);
-
-       /*TODO verify aditional checks that needs to be done */
-       case MONO_TYPE_TYPEDBYREF:
-               if (stack_type != TYPE_PTR)
-                       return FALSE;
-               g_assert (stack->type);
-               if (stack->type->type != MONO_TYPE_TYPEDBYREF)
+               if (candidate->type != MONO_TYPE_ARRAY)
                        return FALSE;
-               return TRUE;
+               return is_array_type_compatible (target, candidate);
 
        case MONO_TYPE_VALUETYPE:
-               if (type->data.klass->enumtype) {
-                       type = type->data.klass->enum_basetype;
-                       goto handle_enum;
-               } else {
-                       if (stack_type != TYPE_COMPLEX)
-                               return FALSE;
-                       g_assert (stack->type);
-                       if (stack->type->type != MONO_TYPE_VALUETYPE)
-                               return FALSE;
-                       return stack->type->data.klass == type->data.klass;
-               }
+               return candidate->type == MONO_TYPE_VALUETYPE && target->data.klass == candidate->data.klass;
+
+       case MONO_TYPE_VAR:
+               //TODO implement me
+               g_assert_not_reached ();
+               return FALSE;
+
+       case MONO_TYPE_MVAR:
+               //TODO implement me
+               g_assert_not_reached ();
+               return FALSE;
 
        default:
-               printf("unknown store type %d\n", type->type);
+               VERIFIER_DEBUG ( printf ("Unknown type %d. Implement me!\n", target->type); );
                g_assert_not_reached ();
                return FALSE;
        }
-       return 1;
 }
 
-/* implement the opcode checks*/
-static void
-push_arg (VerifyContext *ctx, unsigned int arg, int take_addr) 
+static gboolean
+mono_delegate_param_equal (MonoType *delegate, MonoType *method)
 {
-       if (arg >= ctx->max_args) {
-               if (take_addr) 
-                       ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Method doesn't have argument %d", arg + 1));
-               else {
-                       CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Method doesn't have argument %d", arg + 1));
-                       if (check_overflow (ctx)) //FIXME: what sane value could we ever push?
-                               stack_push_val (ctx, TYPE_I4, &mono_defaults.int32_class->byval_arg);
-               }
-       } else if (check_overflow (ctx)) {
-               gboolean override_byref;
-               /*We must let the value be pushed, otherwise we would get an underflow error*/
-               check_unverifiable_type (ctx, ctx->params [arg]);
-               if (ctx->params [arg]->byref && take_addr)
-                       CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("ByRef of ByRef at 0x%04x", ctx->ip_offset));
+       if (mono_metadata_type_equal_full (delegate, method, TRUE))
+               return TRUE;
 
-               /*the 'this' argument is byref, which is not right for reference types,
-                We override the byref only here, since it's the only point that push ctx->params values*/
-               override_byref = arg == 0 && ctx->method->klass && !(ctx->method->flags & METHOD_ATTRIBUTE_STATIC) && !ctx->method->klass->valuetype;   
-               set_stack_value (stack_push (ctx), ctx->params [arg], FALSE, override_byref);
-       } 
+       return mono_delegate_type_equal (method, delegate);
 }
 
-static void
-push_local (VerifyContext *ctx, guint32 arg, int take_addr) 
+static gboolean
+mono_delegate_ret_equal (MonoType *delegate, MonoType *method)
 {
-       if (arg >= ctx->num_locals) {
-               ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Method doesn't have local %d", arg + 1));
-       } else if (check_overflow (ctx)) {
-               /*We must let the value be pushed, otherwise we would get an underflow error*/
-               check_unverifiable_type (ctx, ctx->locals [arg]);
-               if (ctx->locals [arg]->byref && take_addr)
-                       CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("ByRef of ByRef at 0x%04x", ctx->ip_offset));
+       if (mono_metadata_type_equal_full (delegate, method, TRUE))
+               return TRUE;
 
-               set_stack_value (stack_push (ctx), ctx->locals [arg], take_addr, FALSE);
-       } 
+       return mono_delegate_type_equal (delegate, method);
 }
 
-static void
-store_arg (VerifyContext *ctx, guint32 arg)
+/*
+ * mono_delegate_signature_equal:
+ * 
+ * Compare two signatures in the way expected by delegates.
+ * 
+ * This function only exists due to the fact that it should ignore the 'has_this' part of the signature.
+ *
+ * FIXME can this function be eliminated and proper metadata functionality be used?
+ */
+static gboolean
+mono_delegate_signature_equal (MonoMethodSignature *sig1, MonoMethodSignature *sig2)
 {
-       ILStackDesc *value;
-
+       int i;
+       if (sig1->param_count != sig2->param_count) 
+               return FALSE;
+
+       if (sig1->generic_param_count != sig2->generic_param_count)
+               return FALSE;
+       
+       if (sig1->call_convention != sig2->call_convention)
+               return FALSE;
+
+       for (i = 0; i < sig1->param_count; i++) { 
+               MonoType *p1 = sig1->params [i];
+               MonoType *p2 = sig2->params [i];
+
+               if (!mono_delegate_param_equal (p1, p2))
+                       return FALSE;
+       }
+
+       if (!mono_delegate_ret_equal (sig1->ret, sig2->ret))
+               return FALSE;
+
+       return TRUE;
+}
+
+/* 
+ * verify_ldftn_delegate:
+ * 
+ * Verify properties of ldftn based delegates.
+ */
+static void
+verify_ldftn_delegate (VerifyContext *ctx, MonoClass *delegate, ILStackDesc *value, ILStackDesc *funptr)
+{
+       MonoMethod *method = funptr->method;
+
+       /*ldftn non-final virtuals only allowed if method is not static,
+        * the object is a this arg (comes from a ldarg.0), and there is no starg.0.
+        * This rules doesn't apply if the object on stack is a boxed valuetype.
+        */
+       if ((method->flags & METHOD_ATTRIBUTE_VIRTUAL) && !(method->flags & METHOD_ATTRIBUTE_FINAL) && !(method->klass->flags & TYPE_ATTRIBUTE_SEALED) && !stack_slot_is_boxed_value (value)) {
+               /*A stdarg 0 must not happen, we fail here only in fail fast mode to avoid double error reports*/
+               if (IS_FAIL_FAST_MODE (ctx) && ctx->has_this_store)
+                       CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid ldftn with virtual function in method with stdarg 0 at  0x%04x", ctx->ip_offset));
+
+               /*current method must not be static*/
+               if (ctx->method->flags & METHOD_ATTRIBUTE_STATIC)
+                       CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid ldftn with virtual function at 0x%04x", ctx->ip_offset));
+
+               /*value is the this pointer, loaded using ldarg.0 */
+               if (!stack_slot_is_this_pointer (value))
+                       CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid object argument, it is not the this pointer, to ldftn with virtual method at  0x%04x", ctx->ip_offset));
+
+               ctx->code [ctx->ip_offset].flags |= IL_CODE_LDFTN_DELEGATE_NONFINAL_VIRTUAL;
+       }
+}
+
+/*
+ * verify_delegate_compatibility:
+ * 
+ * Verify delegate creation sequence.
+ * 
+ */
+static void
+verify_delegate_compatibility (VerifyContext *ctx, MonoClass *delegate, ILStackDesc *value, ILStackDesc *funptr)
+{
+#define IS_VALID_OPCODE(offset, opcode) (ip [ip_offset - offset] == opcode && (ctx->code [ip_offset - offset].flags & IL_CODE_FLAG_SEEN))
+#define IS_LOAD_FUN_PTR(kind) (IS_VALID_OPCODE (6, CEE_PREFIX1) && ip [ip_offset - 5] == kind)
+
+       MonoMethod *invoke, *method;
+       const guint8 *ip = ctx->header->code;
+       guint32 ip_offset = ctx->ip_offset;
+       
+       if (stack_slot_get_type (funptr) != TYPE_PTR || !funptr->method) {
+               CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid function pointer parameter for delegate constructor at 0x%04x", ctx->ip_offset));
+               return;
+       }
+       
+       invoke = mono_get_delegate_invoke (delegate);
+       method = funptr->method;
+
+       if (!mono_delegate_signature_equal (mono_method_signature (invoke), mono_method_signature (method)))
+               CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Function pointer parameter for delegate constructor has diferent signature at 0x%04x", ctx->ip_offset));
+
+       /* 
+        * Delegate code sequences:
+        * [-6] ldftn token
+        * newobj ...
+        * 
+        * 
+        * [-7] dup
+        * [-6] ldvirtftn token
+        * newobj ...
+        * 
+        * ldftn sequence:*/
+       if (ip_offset > 5 && IS_LOAD_FUN_PTR (CEE_LDFTN)) {
+               verify_ldftn_delegate (ctx, delegate, value, funptr);
+       } else if (ip_offset > 6 && IS_VALID_OPCODE (7, CEE_DUP) && IS_LOAD_FUN_PTR (CEE_LDVIRTFTN)) {
+               ctx->code [ip_offset - 6].flags |= IL_CODE_DELEGATE_SEQUENCE;   
+       }else {
+               CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid code sequence for delegate creation at 0x%04x", ctx->ip_offset));
+       }
+       ctx->code [ip_offset].flags |= IL_CODE_DELEGATE_SEQUENCE;
+
+       //general tests
+       if (!verify_type_compatibility (ctx, &method->klass->byval_arg, value->type) && !stack_slot_is_null_literal (value))
+               CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("This object not compatible with function pointer for delegate creation at 0x%04x", ctx->ip_offset));
+
+       if (stack_slot_get_type (value) != TYPE_COMPLEX)
+               CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid first parameter for delegate creation at 0x%04x", ctx->ip_offset));
+
+#undef IS_VALID_OPCODE
+#undef IS_LOAD_FUN_PTR
+}
+
+/* implement the opcode checks*/
+static void
+push_arg (VerifyContext *ctx, unsigned int arg, int take_addr) 
+{
+       if (arg >= ctx->max_args) {
+               if (take_addr) 
+                       ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Method doesn't have argument %d", arg + 1));
+               else {
+                       CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Method doesn't have argument %d", arg + 1));
+                       if (check_overflow (ctx)) //FIXME: what sane value could we ever push?
+                               stack_push_val (ctx, TYPE_I4, &mono_defaults.int32_class->byval_arg);
+               }
+       } else if (check_overflow (ctx)) {
+               /*We must let the value be pushed, otherwise we would get an underflow error*/
+               check_unverifiable_type (ctx, ctx->params [arg]);
+               if (ctx->params [arg]->byref && take_addr)
+                       CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("ByRef of ByRef at 0x%04x", ctx->ip_offset));
+               if (!set_stack_value (ctx, stack_push (ctx), ctx->params [arg], take_addr))
+                       return;
+
+               if (arg == 0 && !(ctx->method->flags & METHOD_ATTRIBUTE_STATIC)) {
+                       if (take_addr)
+                               ctx->has_this_store = TRUE;
+                       else
+                               stack_top (ctx)->stype |= THIS_POINTER_MASK;
+               }
+       } 
+}
+
+static void
+push_local (VerifyContext *ctx, guint32 arg, int take_addr) 
+{
+       if (arg >= ctx->num_locals) {
+               ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Method doesn't have local %d", arg + 1));
+       } else if (check_overflow (ctx)) {
+               /*We must let the value be pushed, otherwise we would get an underflow error*/
+               check_unverifiable_type (ctx, ctx->locals [arg]);
+               if (ctx->locals [arg]->byref && take_addr)
+                       CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("ByRef of ByRef at 0x%04x", ctx->ip_offset));
+
+               set_stack_value (ctx, stack_push (ctx), ctx->locals [arg], take_addr);
+       } 
+}
+
+static void
+store_arg (VerifyContext *ctx, guint32 arg)
+{
+       ILStackDesc *value;
+
        if (arg >= ctx->max_args) {
-               CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Method doesn't have local var %d at 0x%04x", arg + 1, ctx->ip_offset));
+               CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Method doesn't have argument %d at 0x%04x", arg + 1, ctx->ip_offset));
                check_underflow (ctx, 1);
                stack_pop (ctx);
                return;
@@ -2193,10 +2397,12 @@ store_arg (VerifyContext *ctx, guint32 arg)
 
        if (check_underflow (ctx, 1)) {
                value = stack_pop (ctx);
-               if (!verify_type_compat (ctx, ctx->params [arg], value)) {
-                       CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Incompatible type %s in local store at 0x%04x", type_names [UNMASK_TYPE (value->stype)], ctx->ip_offset));
+               if (!verify_stack_type_compatibility (ctx, ctx->params [arg], value)) {
+                       CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Incompatible type %s in argument store at 0x%04x", stack_slot_get_name (value), ctx->ip_offset));
                }
        }
+       if (arg == 0 && !(ctx->method->flags & METHOD_ATTRIBUTE_STATIC))
+               ctx->has_this_store = 1;
 }
 
 static void
@@ -2211,12 +2417,16 @@ store_local (VerifyContext *ctx, guint32 arg)
        /*TODO verify definite assigment */             
        if (check_underflow (ctx, 1)) {
                value = stack_pop(ctx);
-               if (!verify_type_compat (ctx, ctx->locals [arg], value)) {
-                       CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Incompatible type %s in local store at 0x%04x", type_names [UNMASK_TYPE (value->stype)], ctx->ip_offset));  
+               if (!verify_stack_type_compatibility (ctx, ctx->locals [arg], value)) {
+                       CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Incompatible type [%s], type [%s] was expected in local store at 0x%04x",
+                                       stack_slot_get_name (value),
+                                       mono_type_get_stack_name (ctx->locals [arg]),
+                                       ctx->ip_offset));       
                }
        }
 }
 
+/*FIXME add and sub needs special care here*/
 static void
 do_binop (VerifyContext *ctx, unsigned int opcode, const unsigned char table [TYPE_MAX][TYPE_MAX])
 {
@@ -2229,14 +2439,14 @@ do_binop (VerifyContext *ctx, unsigned int opcode, const unsigned char table [TY
        a = stack_get (ctx, 1);
        b = stack_top (ctx);
 
-       idxa = a->stype;
-       if (IS_MANAGED_POINTER (idxa)) {
+       idxa = stack_slot_get_underlying_type (a);
+       if (stack_slot_is_managed_pointer (a)) {
                idxa = TYPE_PTR;
                complexMerge = 1;
        }
 
-       idxb = b->stype;
-       if (IS_MANAGED_POINTER (idxb)) {
+       idxb = stack_slot_get_underlying_type (b);
+       if (stack_slot_is_managed_pointer (b)) {
                idxb = TYPE_PTR;
                complexMerge = 2;
        }
@@ -2250,13 +2460,12 @@ do_binop (VerifyContext *ctx, unsigned int opcode, const unsigned char table [TY
 
        ctx->eval.size--;
        if (res == TYPE_INV) {
-               CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Binary instruction applyed to ill formed stack (%s x %s)", type_names [UNMASK_TYPE (idxa)], type_names [UNMASK_TYPE (idxb)]));
+               CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Binary instruction applyed to ill formed stack (%s x %s)", stack_slot_get_name (a), stack_slot_get_name (b)));
                return;
        }
 
        if (res & NON_VERIFIABLE_RESULT) {
-               CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Binary instruction is not verifiable (%s x %s)", 
-                       type_names [UNMASK_TYPE (idxa)], type_names [UNMASK_TYPE (idxb)]));
+               CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Binary instruction is not verifiable (%s x %s)", stack_slot_get_name (a), stack_slot_get_name (b)));
 
                res = res & ~NON_VERIFIABLE_RESULT;
        }
@@ -2291,7 +2500,11 @@ do_boolean_branch_op (VerifyContext *ctx, int delta)
                return;
        }
 
-       if (!in_same_block (ctx->header, ctx->ip_offset, target)) {
+       switch (is_valid_branch_instruction (ctx->header, ctx->ip_offset, target)) {
+       case 1:
+               CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Branch target escapes out of exception block at 0x%04x", ctx->ip_offset));
+               break;
+       case 2:
                ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Branch target escapes out of exception block at 0x%04x", ctx->ip_offset));
                return;
        }
@@ -2303,7 +2516,7 @@ do_boolean_branch_op (VerifyContext *ctx, int delta)
 
        top = stack_pop (ctx);
        if (!is_valid_bool_arg (top))
-               CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Argument type %s not valid for brtrue/brfalse at 0x%04x", type_names [UNMASK_TYPE (stack_get (ctx, -1)->stype)], ctx->ip_offset));
+               CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Argument type %s not valid for brtrue/brfalse at 0x%04x", stack_slot_get_name (stack_get (ctx, -1)), ctx->ip_offset));
 
        check_unmanaged_pointer (ctx, top);
 }
@@ -2324,7 +2537,11 @@ do_branch_op (VerifyContext *ctx, signed int delta, const unsigned char table [T
                return;
        }
 
-       if (!in_same_block (ctx->header, ctx->ip_offset, target)) {
+       switch (is_valid_cmp_branch_instruction (ctx->header, ctx->ip_offset, target)) {
+       case 1:
+               CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Branch target escapes out of exception block at 0x%04x", ctx->ip_offset));
+               break;
+       case 2:
                ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Branch target escapes out of exception block at 0x%04x", ctx->ip_offset));
                return;
        }
@@ -2337,12 +2554,12 @@ do_branch_op (VerifyContext *ctx, signed int delta, const unsigned char table [T
        b = stack_pop (ctx);
        a = stack_pop (ctx);
 
-       idxa = a->stype;
-       if (IS_MANAGED_POINTER (idxa))
+       idxa = stack_slot_get_underlying_type (a);
+       if (stack_slot_is_managed_pointer (a))
                idxa = TYPE_PTR;
 
-       idxb = b->stype;
-       if (IS_MANAGED_POINTER (idxb))
+       idxb = stack_slot_get_underlying_type (b);
+       if (stack_slot_is_managed_pointer (b))
                idxb = TYPE_PTR;
 
        --idxa;
@@ -2353,18 +2570,16 @@ do_branch_op (VerifyContext *ctx, signed int delta, const unsigned char table [T
        VERIFIER_DEBUG ( printf ("idxa %d idxb %d\n", idxa, idxb); );
 
        if (res == TYPE_INV) {
-               ADD_VERIFY_ERROR (ctx,
-                       g_strdup_printf ("Compare and Branch instruction applyed to ill formed stack (%s x %s) at 0x%04x",
-                               type_names [UNMASK_TYPE (idxa)], type_names [UNMASK_TYPE (idxb)], ctx->ip_offset));
+               CODE_NOT_VERIFIABLE (ctx,
+                       g_strdup_printf ("Compare and Branch instruction applyed to ill formed stack (%s x %s) at 0x%04x", stack_slot_get_name (a), stack_slot_get_name (b), ctx->ip_offset));
        } else if (res & NON_VERIFIABLE_RESULT) {
-                       CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Compare and Branch instruction is not verifiable (%s x %s) at 0x%04x",
-                               type_names [UNMASK_TYPE (idxa)], type_names [UNMASK_TYPE (idxb)], ctx->ip_offset)); 
+                       CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Compare and Branch instruction is not verifiable (%s x %s) at 0x%04x", stack_slot_get_name (a), stack_slot_get_name (b), ctx->ip_offset)); 
                res = res & ~NON_VERIFIABLE_RESULT;
        }
 }
 
 static void
-do_cmp_op (VerifyContext *ctx, const unsigned char table [TYPE_MAX][TYPE_MAX])
+do_cmp_op (VerifyContext *ctx, const unsigned char table [TYPE_MAX][TYPE_MAX], guint32 opcode)
 {
        ILStackDesc *a, *b;
        int idxa, idxb;
@@ -2375,12 +2590,19 @@ do_cmp_op (VerifyContext *ctx, const unsigned char table [TYPE_MAX][TYPE_MAX])
        b = stack_pop (ctx);
        a = stack_pop (ctx);
 
-       idxa = a->stype;
-       if (IS_MANAGED_POINTER (idxa))
+       if (opcode == CEE_CGT_UN) {
+               if (stack_slot_get_type (a) == TYPE_COMPLEX && stack_slot_get_type (b) == TYPE_COMPLEX) {
+                       stack_push_val (ctx, TYPE_I4, &mono_defaults.int32_class->byval_arg);
+                       return;
+               }
+       }
+
+       idxa = stack_slot_get_underlying_type (a);
+       if (stack_slot_is_managed_pointer (a))
                idxa = TYPE_PTR;
 
-       idxb = b->stype;
-       if (IS_MANAGED_POINTER (idxb)) 
+       idxb = stack_slot_get_underlying_type (b);
+       if (stack_slot_is_managed_pointer (b)) 
                idxb = TYPE_PTR;
 
        --idxa;
@@ -2388,10 +2610,9 @@ do_cmp_op (VerifyContext *ctx, const unsigned char table [TYPE_MAX][TYPE_MAX])
        res = table [idxa][idxb];
 
        if(res == TYPE_INV) {
-               CODE_NOT_VERIFIABLE (ctx, g_strdup_printf("Compare instruction applyed to ill formed stack (%s x %s) at 0x%04x", type_names [UNMASK_TYPE (idxa)], type_names [UNMASK_TYPE (idxb)], ctx->ip_offset));
+               CODE_NOT_VERIFIABLE (ctx, g_strdup_printf("Compare instruction applyed to ill formed stack (%s x %s) at 0x%04x", stack_slot_get_name (a), stack_slot_get_name (b), ctx->ip_offset));
        } else if (res & NON_VERIFIABLE_RESULT) {
-               CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Compare instruction is not verifiable (%s x %s) at 0x%04x",
-                       type_names [UNMASK_TYPE (idxa)], type_names [UNMASK_TYPE (idxb)], ctx->ip_offset)); 
+               CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Compare instruction is not verifiable (%s x %s) at 0x%04x", stack_slot_get_name (a), stack_slot_get_name (b), ctx->ip_offset)); 
                res = res & ~NON_VERIFIABLE_RESULT;
        }
        stack_push_val (ctx, TYPE_I4, &mono_defaults.int32_class->byval_arg);
@@ -2400,48 +2621,69 @@ do_cmp_op (VerifyContext *ctx, const unsigned char table [TYPE_MAX][TYPE_MAX])
 static void
 do_ret (VerifyContext *ctx)
 {
+       MonoType *ret = ctx->signature->ret;
        VERIFIER_DEBUG ( printf ("checking ret\n"); );
-       if (ctx->signature->ret->type != MONO_TYPE_VOID) {
+       if (ret->type != MONO_TYPE_VOID) {
                ILStackDesc *top;
                if (!check_underflow (ctx, 1))
                        return;
 
                top = stack_pop(ctx);
 
-               if (!verify_type_compat (ctx, ctx->signature->ret, top)) {
+               if (!verify_stack_type_compatibility (ctx, ctx->signature->ret, top)) {
                        CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Incompatible return value on stack with method signature ret at 0x%04x", ctx->ip_offset));
                        return;
                }
+
+               if (ret->byref || ret->type == MONO_TYPE_TYPEDBYREF || mono_type_is_value_type (ret, "System", "ArgIterator") || mono_type_is_value_type (ret, "System", "RuntimeArgumentHandle"))
+                       CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Method returns byref, TypedReference, ArgIterator or RuntimeArgumentHandle at 0x%04x", ctx->ip_offset));
        }
 
        if (ctx->eval.size > 0) {
                CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Stack not empty (%d) after ret at 0x%04x", ctx->eval.size, ctx->ip_offset));
        } 
        if (in_any_block (ctx->header, ctx->ip_offset))
-               ADD_VERIFY_ERROR (ctx, g_strdup_printf ("ret cannot escape exception blocks at 0x%04x", ctx->ip_offset));
+               CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("ret cannot escape exception blocks at 0x%04x", ctx->ip_offset));
 }
 
-/* FIXME: we could just load the signature instead of the whole MonoMethod
- * TODO handle vararg calls
- * TODO handle non virt calls to non-final virtual calls (from the verifiability clause in page 52 of partition 3)
- * TODO handle abstract calls
- * TODO handle calling .ctor outside one or calling the .ctor for other class but super
- * TODO handle call invoking virtual methods (only allowed to invoke super)  
+/*
+ * FIXME we need to fix the case of a non-virtual instance method defined in the parent but call using a token pointing to a subclass.
+ *     This is illegal but mono_get_method_full decoded it.
+ * TODO handle calling .ctor outside one or calling the .ctor for other class but super  
  */
 static void
-do_invoke_method (VerifyContext *ctx, int method_token)
+do_invoke_method (VerifyContext *ctx, int method_token, gboolean virtual)
 {
        int param_count, i;
        MonoMethodSignature *sig;
        ILStackDesc *value;
-       MonoMethod *method = mono_get_method_full (ctx->image, method_token, NULL, ctx->generic_context);
+       MonoMethod *method;
+       gboolean virt_check_this = FALSE;
+       gboolean constrained = ctx->prefix_set & PREFIX_CONSTRAINED;
 
-       if (!method) {
-               ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Method 0x%08x not found at 0x%04x", method_token, ctx->ip_offset));
+       if (!(method = verifier_load_method (ctx, method_token, virtual ? "callvirt" : "call")))
                return;
+
+       if (virtual) {
+               ctx->prefix_set &= ~PREFIX_CONSTRAINED;
+
+               if (method->klass->valuetype) // && !constrained ???
+                       CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use callvirtual with valuetype method at 0x%04x", ctx->ip_offset));
+
+               if ((method->flags & METHOD_ATTRIBUTE_STATIC))
+                       CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use callvirtual with static method at 0x%04x", ctx->ip_offset));
+
+       } else {
+               if (method->flags & METHOD_ATTRIBUTE_ABSTRACT) 
+                       CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use call with an abstract method at 0x%04x", ctx->ip_offset));
+               
+               if ((method->flags & METHOD_ATTRIBUTE_VIRTUAL) && !(method->flags & METHOD_ATTRIBUTE_FINAL)) {
+                       virt_check_this = TRUE;
+                       ctx->code [ctx->ip_offset].flags |= IL_CODE_CALL_NONFINAL_VIRTUAL;
+               }
        }
 
-       if (!(sig = mono_method_signature (method)))
+       if (!(sig = mono_method_get_signature_full (method, ctx->image, method_token, ctx->generic_context)))
                sig = mono_method_get_signature (method, ctx->image, method_token);
 
        param_count = sig->param_count + sig->hasthis;
@@ -2451,31 +2693,63 @@ do_invoke_method (VerifyContext *ctx, int method_token)
        for (i = sig->param_count - 1; i >= 0; --i) {
                VERIFIER_DEBUG ( printf ("verifying argument %d\n", i); );
                value = stack_pop (ctx);
-               if (!verify_type_compat (ctx, sig->params[i], value)) {
-                       if (sig->params [i]->type == MONO_TYPE_TYPEDBYREF) {
-                               ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Typedbyref field is an unverfiable type for a call parameter at 0x%04x", ctx->ip_offset));
-                               return;
-                       }
+               if (!verify_stack_type_compatibility (ctx, sig->params[i], value))
                        CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Incompatible parameter value with function signature at 0x%04x", ctx->ip_offset));
-               }
+
+               if (stack_slot_is_managed_mutability_pointer (value))
+                       CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use a readonly pointer as argument of %s at 0x%04x", virtual ? "callvirt" : "call",  ctx->ip_offset));
        }
 
        if (sig->hasthis) {
-               MonoType * type = method->klass->valuetype ? &method->klass->this_arg : &method->klass->byval_arg;
-
-               VERIFIER_DEBUG ( printf ("verifying this argument\n"); );
+               MonoType *type = &method->klass->byval_arg;
+               ILStackDesc copy;
                value = stack_pop (ctx);
-               if (!verify_type_compat (ctx, type, value)) {
-                       ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Incompatible this argument on stack with method signature ret at 0x%04x", ctx->ip_offset));
-                       return;
+               copy_stack_value (&copy, value);
+               //TODO we should extract this to a 'drop_byref_argument' and use everywhere
+               //Other parts of the code suffer from the same issue of 
+               copy.type = mono_type_get_type_byval (copy.type);
+               copy.stype &= ~POINTER_MASK;
+
+               if (virt_check_this && !stack_slot_is_this_pointer (value) && !(method->klass->valuetype || stack_slot_is_boxed_value (value)))
+                       CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot call a non-final virtual method from an objet diferent thant the this pointer at 0x%04x", ctx->ip_offset));
+
+               if (constrained && virtual) {
+                       if (!stack_slot_is_managed_pointer (value))
+                               CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Object is not a managed pointer for a constrained call at 0x%04x", ctx->ip_offset));
+                       if (!mono_metadata_type_equal_full (mono_type_get_type_byval (value->type), ctx->constrained_type, TRUE))
+                               CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Object not compatible with constrained type at 0x%04x", ctx->ip_offset));
+                       copy.stype |= BOXED_MASK;
+               } else {
+                       if (stack_slot_is_managed_pointer (value) && !mono_class_from_mono_type (value->type)->valuetype)
+                               CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot call a reference type using a managed pointer to the this arg at 0x%04x", ctx->ip_offset));
+       
+                       if (!virtual && mono_class_from_mono_type (value->type)->valuetype && !method->klass->valuetype && !stack_slot_is_boxed_value (value))
+                               CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot call a valuetype baseclass at 0x%04x", ctx->ip_offset));
+       
+                       if (virtual && mono_class_from_mono_type (value->type)->valuetype && !stack_slot_is_boxed_value (value))
+                               CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use a valuetype with callvirt at 0x%04x", ctx->ip_offset));
+       
+                       if (method->klass->valuetype && (stack_slot_is_boxed_value (value) || !stack_slot_is_managed_pointer (value)))
+                               CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use a boxed or literal valuetype to call a valuetype method at 0x%04x", ctx->ip_offset));
                }
-       }
-       if (!mono_method_can_access_method (ctx->method, method))
-               CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Method is not accessible at 0x%04x", ctx->ip_offset));
+               if (!verify_stack_type_compatibility (ctx, type, &copy))
+                       CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Incompatible this argument on stack with method signature at 0x%04x", ctx->ip_offset));
+
+               if (!IS_SKIP_VISIBILITY (ctx) && !mono_method_can_access_method_full (ctx->method, method, value->type->data.klass))
+                       CODE_NOT_VERIFIABLE2 (ctx, g_strdup_printf ("Method is not accessible at 0x%04x", ctx->ip_offset), MONO_EXCEPTION_METHOD_ACCESS);
+
+       } else if (!IS_SKIP_VISIBILITY (ctx) && !mono_method_can_access_method_full (ctx->method, method, NULL))
+               CODE_NOT_VERIFIABLE2 (ctx, g_strdup_printf ("Method is not accessible at 0x%04x", ctx->ip_offset), MONO_EXCEPTION_METHOD_ACCESS);
 
        if (sig->ret->type != MONO_TYPE_VOID) {
-               if (check_overflow (ctx))
-                       set_stack_value (stack_push (ctx), sig->ret, FALSE, FALSE);
+               if (check_overflow (ctx)) {
+                       value = stack_push (ctx);
+                       set_stack_value (ctx, value, sig->ret, FALSE);
+                       if ((ctx->prefix_set & PREFIX_READONLY) && method->klass->rank && !strcmp (method->name, "Address")) {
+                               ctx->prefix_set &= ~PREFIX_READONLY;
+                               value->stype |= CMMP_MASK;
+                       }
+               }
        }
 }
 
@@ -2485,11 +2759,8 @@ do_push_static_field (VerifyContext *ctx, int token, gboolean take_addr)
        MonoClassField *field;
        MonoClass *klass;
 
-       field = mono_field_from_token (ctx->image, token, &klass, ctx->generic_context);
-       if (!field) {
-               ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Cannot load field from token 0x%08x at 0x%04x", token, ctx->ip_offset));
+       if (!(field = verifier_load_field (ctx, token, &klass, take_addr ? "ldsflda" : "ldsfld")))
                return;
-       }
 
        if (!(field->type->attrs & FIELD_ATTRIBUTE_STATIC)) { 
                ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Cannot load non static field at 0x%04x", ctx->ip_offset));
@@ -2500,10 +2771,10 @@ do_push_static_field (VerifyContext *ctx, int token, gboolean take_addr)
                !(field->parent == ctx->method->klass && (ctx->method->flags & (METHOD_ATTRIBUTE_SPECIAL_NAME | METHOD_ATTRIBUTE_STATIC)) && !strcmp (".cctor", ctx->method->name)))
                CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot take the address of a init-only field at 0x%04x", ctx->ip_offset));
 
-       if (!mono_method_can_access_field (ctx->method, field))
-               CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Type at stack is not accessible at 0x%04x", ctx->ip_offset));
+       if (!IS_SKIP_VISIBILITY (ctx) && !mono_method_can_access_field_full (ctx->method, field, NULL))
+               CODE_NOT_VERIFIABLE2 (ctx, g_strdup_printf ("Type at stack is not accessible at 0x%04x", ctx->ip_offset), MONO_EXCEPTION_FIELD_ACCESS);
 
-       set_stack_value (stack_push (ctx), field->type, take_addr, FALSE);
+       set_stack_value (ctx, stack_push (ctx), field->type, take_addr);
 }
 
 static void
@@ -2517,11 +2788,8 @@ do_store_static_field (VerifyContext *ctx, int token) {
 
        value = stack_pop (ctx);
 
-       field = mono_field_from_token (ctx->image, token, &klass, ctx->generic_context);
-       if (!field) {
-               ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Cannot store field from token 0x%08x at 0x%04x", token, ctx->ip_offset));
+       if (!(field = verifier_load_field (ctx, token, &klass, "stsfld")))
                return;
-       }
 
        if (!(field->type->attrs & FIELD_ATTRIBUTE_STATIC)) { 
                ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Cannot store non static field at 0x%04x", ctx->ip_offset));
@@ -2533,35 +2801,30 @@ do_store_static_field (VerifyContext *ctx, int token) {
                return;
        }
 
-       if (!mono_method_can_access_field (ctx->method, field))
-               CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Type at stack is not accessible at 0x%04x", ctx->ip_offset));
+       if (!IS_SKIP_VISIBILITY (ctx) && !mono_method_can_access_field_full (ctx->method, field, NULL))
+               CODE_NOT_VERIFIABLE2 (ctx, g_strdup_printf ("Type at stack is not accessible at 0x%04x", ctx->ip_offset), MONO_EXCEPTION_FIELD_ACCESS);
 
-       if (!verify_type_compat (ctx, field->type, value))
-               CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Incompatible type %s in static field store at 0x%04x", type_names [UNMASK_TYPE (value->stype)], ctx->ip_offset));   
+       if (!verify_stack_type_compatibility (ctx, field->type, value))
+               CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Incompatible type %s in static field store at 0x%04x", stack_slot_get_name (value), ctx->ip_offset));       
 }
 
 static gboolean
-check_is_valid_type_for_field_ops (VerifyContext *ctx, int token, ILStackDesc *obj, MonoClassField **ret_field)
+check_is_valid_type_for_field_ops (VerifyContext *ctx, int token, ILStackDesc *obj, MonoClassField **ret_field, const char *opcode)
 {
        MonoClassField *field;
        MonoClass *klass;
 
-       /*must be one of: object type, managed pointer, unmanaged pointer (native int) or an instance of a value type */
-       if (!((obj->stype == TYPE_COMPLEX)
-               /* the managed reference must be to an object or value type */
-               || (( IS_MANAGED_POINTER (obj->stype)) && (UNMASK_TYPE (obj->stype) == TYPE_COMPLEX))
-               || (obj->stype == TYPE_NATIVE_INT)
-               || (obj->stype == TYPE_PTR)
-               || (obj->stype == TYPE_COMPLEX))) {
-               CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid argument %s to load field at 0x%04x", type_names [UNMASK_TYPE (obj->stype)], ctx->ip_offset));
+       /*must be one of: complex type, managed pointer (to complex type), unmanaged pointer (native int) or an instance of a value type */
+       if (!(stack_slot_get_underlying_type (obj) == TYPE_COMPLEX
+               || stack_slot_get_type (obj) == TYPE_NATIVE_INT
+               || stack_slot_get_type (obj) == TYPE_PTR)) {
+               CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid argument %s to load field at 0x%04x", stack_slot_get_name (obj), ctx->ip_offset));
        }
 
-       field = mono_field_from_token (ctx->image, token, &klass, ctx->generic_context);
-       if (!field) {
-               ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Cannot load field from token 0x%08x at 0x%04x", token, ctx->ip_offset));
+       if (!(field = verifier_load_field (ctx, token, &klass, opcode)))
                return FALSE;
-       }
 
+       //TODO verify if type loaded correctly.
        *ret_field = field;
 
        if (field->type->type == MONO_TYPE_TYPEDBYREF) {
@@ -2572,327 +2835,1210 @@ check_is_valid_type_for_field_ops (VerifyContext *ctx, int token, ILStackDesc *o
 
        /*The value on the stack must be a subclass of the defining type of the field*/ 
        /* we need to check if we can load the field from the stack value*/
-       if (UNMASK_TYPE (obj->stype) == TYPE_COMPLEX) {
-               MonoType *type = obj->type->byref ? &field->parent->this_arg : &field->parent->byval_arg;
+       if (stack_slot_get_underlying_type (obj) == TYPE_COMPLEX) {
+               if (!field->parent->valuetype && stack_slot_is_managed_pointer (obj))
+                       CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Type at stack is a managed pointer to a reference type and is not compatible to reference the field at 0x%04x", ctx->ip_offset));
+
+               /*a value type can be loaded from a value or a managed pointer, but not a boxed object*/
+               if (field->parent->valuetype && stack_slot_is_boxed_value (obj))
+                       CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Type at stack is a boxed valuetype and is not compatible to reference the field at 0x%04x", ctx->ip_offset));
+
+               if (!stack_slot_is_null_literal (obj) && !verify_type_compatibility (ctx, &field->parent->byval_arg, mono_type_get_type_byval (obj->type)))
+                       CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Type at stack is not compatible to reference the field at 0x%04x", ctx->ip_offset));
+
+               if (!IS_SKIP_VISIBILITY (ctx) && !mono_method_can_access_field_full (ctx->method, field, obj->type->data.klass))
+                       CODE_NOT_VERIFIABLE2 (ctx, g_strdup_printf ("Type at stack is not accessible at 0x%04x", ctx->ip_offset), MONO_EXCEPTION_FIELD_ACCESS);
+       } else if (!IS_SKIP_VISIBILITY (ctx) && !mono_method_can_access_field_full (ctx->method, field, NULL))
+               CODE_NOT_VERIFIABLE2 (ctx, g_strdup_printf ("Type at stack is not accessible at 0x%04x", ctx->ip_offset), MONO_EXCEPTION_FIELD_ACCESS);
+
+       if (stack_slot_get_underlying_type (obj) == TYPE_NATIVE_INT)
+               CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Native int is not a verifiable type to reference a field at 0x%04x", ctx->ip_offset));
+
+       check_unmanaged_pointer (ctx, obj);
+       return TRUE;
+}
+
+static void
+do_push_field (VerifyContext *ctx, int token, gboolean take_addr)
+{
+       ILStackDesc *obj;
+       MonoClassField *field;
+
+       if (!check_underflow (ctx, 1))
+               return;
+       obj = stack_pop (ctx);
+
+       if (!check_is_valid_type_for_field_ops (ctx, token, obj, &field, take_addr ? "ldflda" : "ldfld"))
+               return;
+
+       if (take_addr && field->parent->valuetype && !stack_slot_is_managed_pointer (obj))
+               CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot take the address of a temporary value-type at 0x%04x", ctx->ip_offset));
+
+       if (take_addr && (field->type->attrs & FIELD_ATTRIBUTE_INIT_ONLY) &&
+               !(field->parent == ctx->method->klass && mono_method_is_constructor (ctx->method)))
+               CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot take the address of a init-only field at 0x%04x", ctx->ip_offset));
+
+       set_stack_value (ctx, stack_push (ctx), field->type, take_addr);
+}
+
+static void
+do_store_field (VerifyContext *ctx, int token)
+{
+       ILStackDesc *value, *obj;
+       MonoClassField *field;
+
+       if (!check_underflow (ctx, 2))
+               return;
+
+       value = stack_pop (ctx);
+       obj = stack_pop (ctx);
+
+       if (!check_is_valid_type_for_field_ops (ctx, token, obj, &field, "stfld"))
+               return;
+
+       if (!verify_stack_type_compatibility (ctx, field->type, value))
+               CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Incompatible type %s in field store at 0x%04x", stack_slot_get_name (value), ctx->ip_offset));      
+}
+
+/*TODO proper handle for Nullable<T>*/
+static void
+do_box_value (VerifyContext *ctx, int klass_token)
+{
+       ILStackDesc *value;
+       MonoType *type = get_boxable_mono_type (ctx, klass_token, "box");
+
+       if (!type)
+               return;
+
+       if (!check_underflow (ctx, 1))
+               return;
+
+       value = stack_top (ctx);
+       /*box is a nop for reference types*/
+
+       if (stack_slot_get_underlying_type (value) == TYPE_COMPLEX && MONO_TYPE_IS_REFERENCE (value->type) && MONO_TYPE_IS_REFERENCE (type)) {
+               value->stype |= BOXED_MASK;
+               return;
+       }
+
+       value = stack_pop (ctx);
+
+       if (!verify_stack_type_compatibility (ctx, type, value))
+               CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid type at stack for boxing operation at 0x%04x", ctx->ip_offset));
+
+       stack_push_val (ctx, TYPE_COMPLEX | BOXED_MASK, type);
+}
+
+static void
+do_unbox_value (VerifyContext *ctx, int klass_token)
+{
+       ILStackDesc *value;
+       MonoType *type = get_boxable_mono_type (ctx, klass_token, "unbox");
+
+       if (!type)
+               return;
+       if (!check_underflow (ctx, 1))
+               return;
+
+       if (!mono_class_from_mono_type (type)->valuetype)
+               CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid reference type for unbox at 0x%04x", ctx->ip_offset));
+
+       value = stack_pop (ctx);
+
+       /*Value should be: a boxed valuetype or a reference type*/
+       if (!(stack_slot_get_type (value) == TYPE_COMPLEX &&
+               (stack_slot_is_boxed_value (value) || !mono_class_from_mono_type (value->type)->valuetype)))
+               CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid type %s at stack for unbox operation at 0x%04x", stack_slot_get_name (value), ctx->ip_offset));
+
+       set_stack_value (ctx, value = stack_push (ctx), mono_type_get_type_byref (type), FALSE);
+       value->stype |= CMMP_MASK;
+}
+
+static void
+do_unbox_any (VerifyContext *ctx, int klass_token)
+{
+       ILStackDesc *value;
+       MonoType *type = get_boxable_mono_type (ctx, klass_token, "unbox.any");
+
+       if (!type)
+               return;
+       if (!check_underflow (ctx, 1))
+               return;
+
+       value = stack_pop (ctx);
+
+       /*Value should be: a boxed valuetype or a reference type*/
+       if (!(stack_slot_get_type (value) == TYPE_COMPLEX &&
+               (stack_slot_is_boxed_value (value) || !mono_class_from_mono_type (value->type)->valuetype)))
+               CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid type %s at stack for unbox.any operation at 0x%04x", stack_slot_get_name (value), ctx->ip_offset));
+       set_stack_value (ctx, stack_push (ctx), type, FALSE);
+}
+
+static void
+do_unary_math_op (VerifyContext *ctx, int op)
+{
+       ILStackDesc *value;
+       if (!check_underflow (ctx, 1))
+               return;
+       value = stack_top (ctx);
+       switch (stack_slot_get_type (value)) {
+       case TYPE_I4:
+       case TYPE_I8:
+       case TYPE_NATIVE_INT:
+               break;
+       case TYPE_R8:
+               if (op == CEE_NEG)
+                       break;
+       case TYPE_COMPLEX: /*only enums are ok*/
+               if (mono_type_is_enum_type (value->type))
+                       break;
+       default:
+               CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid type at stack for unary not at 0x%04x", ctx->ip_offset));
+       }
+}
+
+static void
+do_conversion (VerifyContext *ctx, int kind) 
+{
+       ILStackDesc *value;
+       if (!check_underflow (ctx, 1))
+               return;
+       value = stack_pop (ctx);
+
+       switch (stack_slot_get_type (value)) {
+       case TYPE_I4:
+       case TYPE_I8:
+       case TYPE_NATIVE_INT:
+       case TYPE_R8:
+               break;
+       default:
+               CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid type (%s) at stack for conversion operation at 0x%04x", stack_slot_get_name (value), ctx->ip_offset));
+       }
+
+       switch (kind) {
+       case TYPE_I4:
+               stack_push_val (ctx, TYPE_I4, &mono_defaults.int32_class->byval_arg);
+               break;
+       case TYPE_I8:
+               stack_push_val (ctx,TYPE_I8, &mono_defaults.int64_class->byval_arg);
+               break;
+       case TYPE_R8:
+               stack_push_val (ctx, TYPE_R8, &mono_defaults.double_class->byval_arg);
+               break;
+       case TYPE_NATIVE_INT:
+               stack_push_val (ctx, TYPE_NATIVE_INT, &mono_defaults.int_class->byval_arg);
+               break;
+       default:
+               g_error ("unknown type %02x in conversion", kind);
+
+       }
+}
+
+static void
+do_load_token (VerifyContext *ctx, int token) 
+{
+       gpointer handle;
+       MonoClass *handle_class;
+       if (!check_overflow (ctx))
+               return;
+       handle = mono_ldtoken (ctx->image, token, &handle_class, ctx->generic_context);
+       if (!handle) {
+               ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid token 0x%x for ldtoken at 0x%04x", token, ctx->ip_offset));
+               return;
+       }
+       stack_push_val (ctx, TYPE_COMPLEX, mono_class_get_type (handle_class));
+}
+
+static void
+do_ldobj_value (VerifyContext *ctx, int token) 
+{
+       ILStackDesc *value;
+       MonoType *type = get_boxable_mono_type (ctx, token, "ldobj");
+
+       if (!type)
+               return;
+
+       if (!check_underflow (ctx, 1))
+               return;
+
+       value = stack_pop (ctx);
+       if (!stack_slot_is_managed_pointer (value) 
+                       && stack_slot_get_type (value) != TYPE_NATIVE_INT
+                       && !(stack_slot_get_type (value) == TYPE_PTR && value->type->type != MONO_TYPE_FNPTR)) {
+               ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid argument %s to ldobj at 0x%04x", stack_slot_get_name (value), ctx->ip_offset));
+               return;
+       }
+
+       if (stack_slot_get_type (value) == TYPE_NATIVE_INT)
+               CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Using native pointer to ldobj at 0x%04x", ctx->ip_offset));
+
+       /*We have a byval on the stack, but the comparison must be strict. */
+       if (!verify_type_compatibility_full (ctx, type, mono_type_get_type_byval (value->type), TRUE))
+               CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid type at stack for ldojb operation at 0x%04x", ctx->ip_offset));
+
+       set_stack_value (ctx, stack_push (ctx), type, FALSE);
+}
+
+static void
+do_stobj (VerifyContext *ctx, int token) 
+{
+       ILStackDesc *dest, *src;
+       MonoType *type = get_boxable_mono_type (ctx, token, "stobj");
+       if (!type)
+               return;
+
+       if (!check_underflow (ctx, 2))
+               return;
+
+       src = stack_pop (ctx);
+       dest = stack_pop (ctx);
+
+       if (stack_slot_is_managed_mutability_pointer (dest))
+               CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use a readonly pointer with stobj at 0x%04x", ctx->ip_offset));
+
+       if (!stack_slot_is_managed_pointer (dest)) 
+               CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid destination of stobj operation at 0x%04x", ctx->ip_offset));
+
+       if (!verify_stack_type_compatibility (ctx, type, src))
+               CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Token and source types of stobj don't match at 0x%04x", ctx->ip_offset));
+
+       if (!verify_type_compatibility (ctx, mono_type_get_type_byval (dest->type), type))
+               CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Destination and token types of stobj don't match at 0x%04x", ctx->ip_offset));
+}
+
+static void
+do_cpobj (VerifyContext *ctx, int token)
+{
+       ILStackDesc *dest, *src;
+       MonoType *type = get_boxable_mono_type (ctx, token, "cpobj");
+       if (!type)
+               return;
+
+       if (!check_underflow (ctx, 2))
+               return;
+
+       src = stack_pop (ctx);
+       dest = stack_pop (ctx);
+
+       if (!stack_slot_is_managed_pointer (src)) 
+               CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid source of cpobj operation at 0x%04x", ctx->ip_offset));
+
+       if (!stack_slot_is_managed_pointer (dest)) 
+               CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid destination of cpobj operation at 0x%04x", ctx->ip_offset));
+
+       if (stack_slot_is_managed_mutability_pointer (dest))
+               CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use a readonly pointer with cpobj at 0x%04x", ctx->ip_offset));
+
+       if (!verify_type_compatibility (ctx, type, mono_type_get_type_byval (src->type)))
+               CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Token and source types of cpobj don't match at 0x%04x", ctx->ip_offset));
+
+       if (!verify_type_compatibility (ctx, mono_type_get_type_byval (dest->type), type))
+               CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Destination and token types of cpobj don't match at 0x%04x", ctx->ip_offset));
+}
+
+static void
+do_initobj (VerifyContext *ctx, int token)
+{
+       ILStackDesc *obj;
+       MonoType *stack, *type = get_boxable_mono_type (ctx, token, "initobj");
+       if (!type)
+               return;
+
+       if (!check_underflow (ctx, 1))
+               return;
+
+       obj = stack_pop (ctx);
+
+       if (!stack_slot_is_managed_pointer (obj)) 
+               CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid object address for initobj at 0x%04x", ctx->ip_offset));
+
+       if (stack_slot_is_managed_mutability_pointer (obj))
+               CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use a readonly pointer with initobj at 0x%04x", ctx->ip_offset));
+
+       stack = mono_type_get_type_byval (obj->type);
+       if (MONO_TYPE_IS_REFERENCE (stack)) {
+               if (!verify_type_compatibility (ctx, stack, type)) 
+                       CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Type token of initobj not compatible with value on stack at 0x%04x", ctx->ip_offset));
+               else if (IS_STRICT_MODE (ctx) && !mono_metadata_type_equal (type, stack)) 
+                       CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Type token of initobj not compatible with value on stack at 0x%04x", ctx->ip_offset));
+       } else if (!verify_type_compatibility (ctx, stack, type)) {
+               CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Type token of initobj not compatible with value on stack at 0x%04x", ctx->ip_offset));
+       }
+}
+
+static void
+do_newobj (VerifyContext *ctx, int token) 
+{
+       ILStackDesc *value;
+       int i;
+       MonoMethodSignature *sig;
+       MonoMethod *method;
+       gboolean is_delegate = FALSE;
+
+       if (!(method = verifier_load_method (ctx, token, "newobj")))
+               return;
+
+       if (!mono_method_is_constructor (method)) {
+               ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Method from token 0x%08x not a constructor at 0x%04x", token, ctx->ip_offset));
+               return;
+       }
+
+       if (method->klass->flags & (TYPE_ATTRIBUTE_ABSTRACT | TYPE_ATTRIBUTE_INTERFACE))
+               CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Trying to instantiate an abstract or interface type at 0x%04x", ctx->ip_offset));
+
+       if (!mono_method_can_access_method_full (ctx->method, method, NULL))
+               CODE_NOT_VERIFIABLE2 (ctx, g_strdup_printf ("Constructor not visible at 0x%04x", ctx->ip_offset), MONO_EXCEPTION_METHOD_ACCESS);
+
+       //FIXME use mono_method_get_signature_full
+       sig = mono_method_signature (method);
+       if (!check_underflow (ctx, sig->param_count))
+               return;
+
+       is_delegate = method->klass->parent == mono_defaults.multicastdelegate_class;
+
+       if (is_delegate) {
+               ILStackDesc *funptr;
+               //first arg is object, second arg is fun ptr
+               if (sig->param_count != 2) {
+                       ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid delegate constructor at 0x%04x", ctx->ip_offset));
+                       return;
+               }
+               funptr = stack_pop (ctx);
+               value = stack_pop (ctx);
+               verify_delegate_compatibility (ctx, method->klass, value, funptr);
+       } else {
+               for (i = sig->param_count - 1; i >= 0; --i) {
+                       VERIFIER_DEBUG ( printf ("verifying constructor argument %d\n", i); );
+                       value = stack_pop (ctx);
+                       if (!verify_stack_type_compatibility (ctx, sig->params [i], value))
+                               CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Incompatible parameter value with function signature at 0x%04x", ctx->ip_offset));
+
+                       if (stack_slot_is_managed_mutability_pointer (value))
+                               CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use a readonly pointer as argument of newobj at 0x%04x", ctx->ip_offset));
+               }
+       }
+
+       if (check_overflow (ctx))
+               set_stack_value (ctx, stack_push (ctx),  &method->klass->byval_arg, FALSE);
+}
+
+static void
+do_cast (VerifyContext *ctx, int token, const char *opcode) {
+       ILStackDesc *value;
+       MonoType *type;
+       gboolean is_boxed;
+
+       if (!check_underflow (ctx, 1))
+               return;
+
+       if (!(type = verifier_load_type (ctx, token, opcode)))
+               return;
+
+       if (type->byref) {
+               ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid %s type at 0x%04x", opcode, ctx->ip_offset));
+               return;
+       }
+
+       value = stack_pop (ctx);
+       is_boxed = stack_slot_is_boxed_value (value);
+
+       if (stack_slot_is_managed_pointer (value))
+               CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid value for %s at 0x%04x", opcode, ctx->ip_offset));
+       else if (mono_class_from_mono_type (value->type)->valuetype && !is_boxed)
+               CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Value cannot be a valuetype for %s at 0x%04x", opcode, ctx->ip_offset));
+
+       switch (value->type->type) {
+       case MONO_TYPE_FNPTR:
+       case MONO_TYPE_PTR:
+       case MONO_TYPE_TYPEDBYREF: 
+               CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid value for %s at 0x%04x", opcode, ctx->ip_offset));
+       }
+
+       stack_push_val (ctx, TYPE_COMPLEX | (mono_class_from_mono_type (type)->valuetype || is_boxed ? BOXED_MASK : 0), type);
+}
+
+static MonoType *
+mono_type_from_opcode (int opcode) {
+       switch (opcode) {
+       case CEE_LDIND_I1:
+       case CEE_LDIND_U1:
+       case CEE_STIND_I1:
+       case CEE_LDELEM_I1:
+       case CEE_LDELEM_U1:
+       case CEE_STELEM_I1:
+               return &mono_defaults.sbyte_class->byval_arg;
+
+       case CEE_LDIND_I2:
+       case CEE_LDIND_U2:
+       case CEE_STIND_I2:
+       case CEE_LDELEM_I2:
+       case CEE_LDELEM_U2:
+       case CEE_STELEM_I2:
+               return &mono_defaults.int16_class->byval_arg;
+
+       case CEE_LDIND_I4:
+       case CEE_LDIND_U4:
+       case CEE_STIND_I4:
+       case CEE_LDELEM_I4:
+       case CEE_LDELEM_U4:
+       case CEE_STELEM_I4:
+               return &mono_defaults.int32_class->byval_arg;
+
+       case CEE_LDIND_I8:
+       case CEE_STIND_I8:
+       case CEE_LDELEM_I8:
+       case CEE_STELEM_I8:
+               return &mono_defaults.int64_class->byval_arg;
+
+       case CEE_LDIND_R4:
+       case CEE_STIND_R4:
+       case CEE_LDELEM_R4:
+       case CEE_STELEM_R4:
+               return &mono_defaults.single_class->byval_arg;
+
+       case CEE_LDIND_R8:
+       case CEE_STIND_R8:
+       case CEE_LDELEM_R8:
+       case CEE_STELEM_R8:
+               return &mono_defaults.double_class->byval_arg;
+
+       case CEE_LDIND_I:
+       case CEE_STIND_I:
+       case CEE_LDELEM_I:
+       case CEE_STELEM_I:
+               return &mono_defaults.int_class->byval_arg;
+
+       case CEE_LDIND_REF:
+       case CEE_STIND_REF:
+       case CEE_LDELEM_REF:
+       case CEE_STELEM_REF:
+               return &mono_defaults.object_class->byval_arg;
+
+       default:
+               g_error ("unknown opcode %02x in mono_type_from_opcode ", opcode);
+               return NULL;
+       }
+}
+
+static void
+do_load_indirect (VerifyContext *ctx, int opcode)
+{
+       ILStackDesc *value;
+       if (!check_underflow (ctx, 1))
+               return;
+       
+       value = stack_pop (ctx);
+       if (!stack_slot_is_managed_pointer (value)) {
+               CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Load indirect not using a manager pointer at 0x%04x", ctx->ip_offset));
+               set_stack_value (ctx, stack_push (ctx), mono_type_from_opcode (opcode), FALSE);
+               return;
+       }
+
+       if (opcode == CEE_LDIND_REF) {
+               if (stack_slot_get_underlying_type (value) != TYPE_COMPLEX || mono_class_from_mono_type (value->type)->valuetype)
+                       CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid type at stack for ldind_ref expected object byref operation at 0x%04x", ctx->ip_offset));
+               set_stack_value (ctx, stack_push (ctx), mono_type_get_type_byval (value->type), FALSE);
+       } else {
+               if (!verify_type_compatibility_full (ctx, mono_type_from_opcode (opcode), mono_type_get_type_byval (value->type), TRUE))
+                       CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid type at stack for ldind 0x%x operation at 0x%04x", opcode, ctx->ip_offset));
+               set_stack_value (ctx, stack_push (ctx), mono_type_from_opcode (opcode), FALSE);
+       }
+}
+
+static void
+do_store_indirect (VerifyContext *ctx, int opcode)
+{
+       ILStackDesc *addr, *val;
+       if (!check_underflow (ctx, 2))
+               return;
+
+       val = stack_pop (ctx);
+       addr = stack_pop (ctx); 
+
+       check_unmanaged_pointer (ctx, addr);
+
+       if (!stack_slot_is_managed_pointer (addr) && stack_slot_get_type (addr) != TYPE_PTR) {
+               CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid non-pointer argument to stind at 0x%04x", ctx->ip_offset));
+               return;
+       }
+
+       if (stack_slot_is_managed_mutability_pointer (addr)) {
+               CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use a readonly pointer with stind at 0x%04x", ctx->ip_offset));
+               return;
+       }
+
+       if (!verify_type_compatibility_full (ctx, mono_type_from_opcode (opcode), mono_type_get_type_byval (addr->type), TRUE))
+               CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid addr type at stack for stind 0x%x operation at 0x%04x", opcode, ctx->ip_offset));
+
+       if (!verify_stack_type_compatibility (ctx, mono_type_from_opcode (opcode), val))
+               CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid value type at stack for stind 0x%x operation at 0x%04x", opcode, ctx->ip_offset));
+}
+
+static void
+do_newarr (VerifyContext *ctx, int token) 
+{
+       ILStackDesc *value;
+       MonoType *type = get_boxable_mono_type (ctx, token, "newarr");
+
+       if (!type)
+               return;
+
+       if (!check_underflow (ctx, 1))
+               return;
+
+       value = stack_pop (ctx);
+       if (stack_slot_get_type (value) != TYPE_I4 && stack_slot_get_type (value) != TYPE_NATIVE_INT)
+               CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Array size type on stack (%s) is not a verifiable type at 0x%04x", stack_slot_get_name (value), ctx->ip_offset));
+
+       set_stack_value (ctx, stack_push (ctx), mono_class_get_type (mono_array_class_get (mono_class_from_mono_type (type), 1)), FALSE);
+}
+
+/*FIXME handle arrays that are not 0-indexed*/
+static void
+do_ldlen (VerifyContext *ctx)
+{
+       ILStackDesc *value;
+
+       if (!check_underflow (ctx, 1))
+               return;
+
+       value = stack_pop (ctx);
+
+       if (stack_slot_get_type (value) != TYPE_COMPLEX || value->type->type != MONO_TYPE_SZARRAY)
+               CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type for ldlen at 0x%04x", ctx->ip_offset));
+
+       stack_push_val (ctx, TYPE_NATIVE_INT, &mono_defaults.int_class->byval_arg);     
+}
+
+/*FIXME handle arrays that are not 0-indexed*/
+/*FIXME handle readonly prefix and CMMP*/
+static void
+do_ldelema (VerifyContext *ctx, int klass_token)
+{
+       ILStackDesc *index, *array, *res;
+       MonoType *type = get_boxable_mono_type (ctx, klass_token, "ldelema");
+       gboolean valid; 
+
+       if (!type)
+               return;
+
+       if (!check_underflow (ctx, 2))
+               return;
+
+       index = stack_pop (ctx);
+       array = stack_pop (ctx);
+
+       if (stack_slot_get_type (index) != TYPE_I4 && stack_slot_get_type (index) != TYPE_NATIVE_INT)
+               CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Index type(%s) for ldelema is not an int or a native int at 0x%04x", stack_slot_get_name (index), ctx->ip_offset));
+
+       if (!stack_slot_is_null_literal (array)) {
+               if (stack_slot_get_type (array) != TYPE_COMPLEX || array->type->type != MONO_TYPE_SZARRAY)
+                       CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type(%s) for ldelema at 0x%04x", stack_slot_get_name (array), ctx->ip_offset));
+               else {
+                       if (get_stack_type (type) == TYPE_I4 || get_stack_type (type) == TYPE_NATIVE_INT) {
+                                       valid = verify_type_compatibility_full (ctx, type, &array->type->data.klass->byval_arg, TRUE);
+                       } else {
+                               valid = mono_metadata_type_equal (type, &array->type->data.klass->byval_arg);
+                       }
+                       if (!valid)
+                               CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type on stack for ldelema at 0x%04x", ctx->ip_offset));
+               }
+       }
+
+       res = stack_push (ctx);
+       set_stack_value (ctx, res, type, TRUE);
+       if (ctx->prefix_set & PREFIX_READONLY) {
+               ctx->prefix_set &= ~PREFIX_READONLY;
+               res->stype |= CMMP_MASK;
+       }
+}
+
+/*
+ * FIXME handle arrays that are not 0-indexed
+ * FIXME handle readonly prefix and CMMP
+ */
+static void
+do_ldelem (VerifyContext *ctx, int opcode, int token)
+{
+#define IS_ONE_OF2(T, A, B) (T == A || T == B)
+       ILStackDesc *index, *array;
+       MonoType *type;
+       if (!check_underflow (ctx, 2))
+               return;
+
+       if (opcode == CEE_LDELEM_ANY) {
+               if (!(type = verifier_load_type (ctx, token, "ldelem.any"))) {
+                       ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Type (0x%08x) not found at 0x%04x", token, ctx->ip_offset));
+                       return;
+               }
+       } else {
+               type = mono_type_from_opcode (opcode);
+       }
+
+       index = stack_pop (ctx);
+       array = stack_pop (ctx);
+
+       if (stack_slot_get_type (index) != TYPE_I4 && stack_slot_get_type (index) != TYPE_NATIVE_INT)
+               CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Index type(%s) for ldelem.X is not an int or a native int at 0x%04x", stack_slot_get_name (index), ctx->ip_offset));
+
+       if (!stack_slot_is_null_literal (array)) {
+               if (stack_slot_get_type (array) != TYPE_COMPLEX || array->type->type != MONO_TYPE_SZARRAY)
+                       CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type(%s) for ldelem.X at 0x%04x", stack_slot_get_name (array), ctx->ip_offset));
+               else {
+                       if (opcode == CEE_LDELEM_REF) {
+                               if (array->type->data.klass->valuetype)
+                                       CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type is not a reference type for ldelem.ref 0x%04x", ctx->ip_offset));
+                               type = &array->type->data.klass->byval_arg;
+                       } else {
+                               MonoType *candidate = &array->type->data.klass->byval_arg;
+                               if (IS_STRICT_MODE (ctx)) {
+                                       MonoType *underlying_type = mono_type_get_underlying_type_any (type);
+                                       MonoType *underlying_candidate = mono_type_get_underlying_type_any (candidate);
+                                       if ((IS_ONE_OF2 (underlying_type->type, MONO_TYPE_I4, MONO_TYPE_U4) && IS_ONE_OF2 (underlying_candidate->type, MONO_TYPE_I, MONO_TYPE_U)) ||
+                                               (IS_ONE_OF2 (underlying_candidate->type, MONO_TYPE_I4, MONO_TYPE_U4) && IS_ONE_OF2 (underlying_type->type, MONO_TYPE_I, MONO_TYPE_U)))
+                                               CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type on stack for ldelem.X at 0x%04x", ctx->ip_offset));
+                               }
+                               if (!verify_type_compatibility_full (ctx, type, candidate, TRUE))
+                                       CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type on stack for ldelem.X at 0x%04x", ctx->ip_offset));
+                       }
+               }
+       }
+
+       set_stack_value (ctx, stack_push (ctx), type, FALSE);
+#undef IS_ONE_OF2
+}
+
+/*
+ * FIXME handle arrays that are not 0-indexed
+ */
+static void
+do_stelem (VerifyContext *ctx, int opcode, int token)
+{
+       ILStackDesc *index, *array, *value;
+       MonoType *type;
+       if (!check_underflow (ctx, 3))
+               return;
+
+       if (opcode == CEE_STELEM_ANY) {
+               if (!(type = verifier_load_type (ctx, token, "stelem.any"))) {
+                       ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Type (0x%08x) not found at 0x%04x", token, ctx->ip_offset));
+                       return;
+               }
+       } else {
+               type = mono_type_from_opcode (opcode);
+       }
+       
+       value = stack_pop (ctx);
+       index = stack_pop (ctx);
+       array = stack_pop (ctx);
+
+       if (stack_slot_get_type (index) != TYPE_I4 && stack_slot_get_type (index) != TYPE_NATIVE_INT)
+               CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Index type(%s) for stdelem.X is not an int or a native int at 0x%04x", stack_slot_get_name (index), ctx->ip_offset));
+
+       if (!stack_slot_is_null_literal (array)) {
+               if (stack_slot_get_type (array) != TYPE_COMPLEX || array->type->type != MONO_TYPE_SZARRAY) {
+                       CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type(%s) for stelem.X at 0x%04x", stack_slot_get_name (array), ctx->ip_offset));
+               } else {
+                       if (opcode == CEE_STELEM_REF) {
+                               if (array->type->data.klass->valuetype)
+                                       CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type is not a reference type for stelem.ref 0x%04x", ctx->ip_offset));
+                       } else if (!verify_type_compatibility_full (ctx, &array->type->data.klass->byval_arg, type, TRUE)) {
+                                       CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type on stack for stdelem.X at 0x%04x", ctx->ip_offset));
+                       }
+               }
+       }
+
+       if (opcode == CEE_STELEM_REF) {
+               if (!stack_slot_is_boxed_value (value) && mono_class_from_mono_type (value->type)->valuetype)
+                       CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid value is not a reference type for stelem.ref 0x%04x", ctx->ip_offset));
+       } else if (opcode != CEE_STELEM_REF && !verify_type_compatibility_full (ctx, type, mono_type_from_stack_slot (value), FALSE)) {
+               CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid value on stack for stdelem.X at 0x%04x", ctx->ip_offset));
+       }
+}
+
+static void
+do_throw (VerifyContext *ctx)
+{
+       ILStackDesc *exception;
+       if (!check_underflow (ctx, 1))
+               return;
+       exception = stack_pop (ctx);
+
+       if (!stack_slot_is_null_literal (exception) && !(stack_slot_get_type (exception) == TYPE_COMPLEX && !mono_class_from_mono_type (exception->type)->valuetype))
+               CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid type on stack for throw, expected reference type at 0x%04x", ctx->ip_offset));
+
+       /*The stack is left empty after a throw*/
+       ctx->eval.size = 0;
+}
+
+
+static void
+do_endfilter (VerifyContext *ctx)
+{
+       MonoExceptionClause *clause;
 
-               if (!verify_stack_type_compatibility (ctx, type, obj->type, FALSE)) {
-                       CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Type at stack is not compatible to reference the field at 0x%04x", ctx->ip_offset));
-               }
+       if (IS_STRICT_MODE (ctx)) {
+               if (ctx->eval.size != 1)
+                       CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Stack size must have one item for endfilter at 0x%04x", ctx->ip_offset));
 
-               if (!mono_method_can_access_field (ctx->method, field))
-                       CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Type at stack is not accessible at 0x%04x", ctx->ip_offset));
+               if (ctx->eval.size >= 1 && stack_slot_get_type (stack_pop (ctx)) != TYPE_I4)
+                       CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Stack item type is not an int32 for endfilter at 0x%04x", ctx->ip_offset));
        }
 
-       if (!mono_method_can_access_field (ctx->method, field))
-               CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Type at stack is not accessible at 0x%04x", ctx->ip_offset));
-
-       if (obj->stype == TYPE_NATIVE_INT)
-               CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Native int is not a verifiable type to reference a field at 0x%04x", ctx->ip_offset));
+       if ((clause = is_correct_endfilter (ctx, ctx->ip_offset))) {
+               if (IS_STRICT_MODE (ctx)) {
+                       if (ctx->ip_offset != clause->handler_offset - 2)
+                               ADD_VERIFY_ERROR (ctx, g_strdup_printf ("endfilter is not the last instruction of the filter clause at 0x%04x", ctx->ip_offset));                       
+               } else {
+                       if ((ctx->ip_offset != clause->handler_offset - 2) && !MONO_OFFSET_IN_HANDLER (clause, ctx->ip_offset))
+                               ADD_VERIFY_ERROR (ctx, g_strdup_printf ("endfilter is not the last instruction of the filter clause at 0x%04x", ctx->ip_offset));
+               }
+       } else {
+               if (IS_STRICT_MODE (ctx) && !is_unverifiable_endfilter (ctx, ctx->ip_offset))
+                       ADD_VERIFY_ERROR (ctx, g_strdup_printf ("endfilter outside filter clause at 0x%04x", ctx->ip_offset));
+               else
+                       CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("endfilter outside filter clause at 0x%04x", ctx->ip_offset));
+       }
 
-       check_unmanaged_pointer (ctx, obj);
-       return TRUE;
+       ctx->eval.size = 0;
 }
 
 static void
-do_push_field (VerifyContext *ctx, int token, gboolean take_addr)
+do_leave (VerifyContext *ctx, int delta)
 {
-       ILStackDesc *obj;
-       MonoClassField *field;
+       int target = ((gint32)ctx->ip_offset) + delta;
+       if (target >= ctx->code_size || target < 0)
+               ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Branch target out of code at 0x%04x", ctx->ip_offset));
 
-       if (!check_underflow (ctx, 1))
-               return;
-       obj = stack_pop (ctx);
+       if (!is_correct_leave (ctx->header, ctx->ip_offset, target))
+               CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Leave not allowed in finally block at 0x%04x", ctx->ip_offset));
+}
 
-       if (!check_is_valid_type_for_field_ops (ctx, token, obj, &field))
+/* 
+ * do_static_branch:
+ * 
+ * Verify br and br.s opcodes.
+ */
+static void
+do_static_branch (VerifyContext *ctx, int delta)
+{
+       int target = ctx->ip_offset + delta;
+       if (target < 0 || target >= ctx->code_size) {
+               ADD_VERIFY_ERROR (ctx, g_strdup_printf ("branch target out of code at 0x%04x", ctx->ip_offset));
                return;
+       }
 
-       if (take_addr && field->parent->valuetype && !IS_MANAGED_POINTER (obj->stype))
-               CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot take the address of a temporary value-type at 0x%04x", ctx->ip_offset));
-
-       if (take_addr && (field->type->attrs & FIELD_ATTRIBUTE_INIT_ONLY) &&
-               !(field->parent == ctx->method->klass && (ctx->method->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) && !strcmp (".ctor", ctx->method->name)))
-               CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot take the address of a init-only field at 0x%04x", ctx->ip_offset));
+       switch (is_valid_branch_instruction (ctx->header, ctx->ip_offset, target)) {
+       case 1:
+               CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Branch target escapes out of exception block at 0x%04x", ctx->ip_offset));
+               break;
+       case 2:
+               ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Branch target escapes out of exception block at 0x%04x", ctx->ip_offset));
+               break;
+       }
 
-       set_stack_value (stack_push (ctx), field->type, take_addr, FALSE);
+       ctx->target = target;
 }
 
 static void
-do_store_field (VerifyContext *ctx, int token)
+do_switch (VerifyContext *ctx, int count, const unsigned char *data)
 {
-       ILStackDesc *value, *obj;
-       MonoClassField *field;
+       int i, base = ctx->ip_offset + 5 + count * 4;
+       ILStackDesc *value;
 
-       if (!check_underflow (ctx, 2))
+       if (!check_underflow (ctx, 1))
                return;
 
        value = stack_pop (ctx);
-       obj = stack_pop (ctx);
 
-       if (!check_is_valid_type_for_field_ops (ctx, token, obj, &field))
-               return;
+       if (stack_slot_get_type (value) != TYPE_I4 && stack_slot_get_type (value) != TYPE_NATIVE_INT)
+               CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid argument to switch at 0x%04x", ctx->ip_offset));
+
+       for (i = 0; i < count; ++i) {
+               int target = base + read32 (data + i * 4);
 
-       if (!verify_type_compat (ctx, field->type, value))
-               CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Incompatible type %s in field store at 0x%04x", type_names [UNMASK_TYPE (value->stype)], ctx->ip_offset));  
+               if (target < 0 || target >= ctx->code_size)
+                       ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Switch target %x out of code at 0x%04x", i, ctx->ip_offset));
+
+               switch (is_valid_branch_instruction (ctx->header, ctx->ip_offset, target)) {
+               case 1:
+                       CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Switch target %x escapes out of exception block at 0x%04x", i, ctx->ip_offset));
+                       break;
+               case 2:
+                       ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Switch target %x escapes out of exception block at 0x%04x", i, ctx->ip_offset));
+                       break;
+               }
+               merge_stacks (ctx, &ctx->eval, &ctx->code [target], FALSE, TRUE);
+       }
 }
 
-/*TODO proper handle for Nullable<T>*/
 static void
-do_box_value (VerifyContext *ctx, int klass_token)
+do_load_function_ptr (VerifyContext *ctx, guint32 token, gboolean virtual)
 {
-       ILStackDesc *value;
-       MonoType *type = get_boxable_mono_type (ctx, klass_token);
+       ILStackDesc *top;
+       MonoMethod *method;
 
-       if (!type)
+       if (virtual && !check_underflow (ctx, 1))
                return;
 
-       if (!check_underflow (ctx, 1))
+       if (!virtual && !check_overflow (ctx))
                return;
 
-       value = stack_top (ctx);
-       /*box is a nop for reference types*/
-       if (value->stype == TYPE_COMPLEX && MONO_TYPE_IS_REFERENCE (value->type) && MONO_TYPE_IS_REFERENCE (type))
+       if (!IS_METHOD_DEF_OR_REF_OR_SPEC (token) || !token_bounds_check (ctx->image, token)) {
+               ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid token %x for ldftn  at 0x%04x", token, ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE);
                return;
+       }
 
-       value = stack_pop (ctx);
+       if (!(method = verifier_load_method (ctx, token, virtual ? "ldvirtfrn" : "ldftn")))
+               return;
 
-       if (!verify_type_compat (ctx, type, value))
-               CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid type at stack for boxing operation at 0x%04x", ctx->ip_offset));
+       if (mono_method_is_constructor (method))
+               CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use ldftn with a constructor at 0x%04x", ctx->ip_offset));
+
+       if (virtual) {
+               ILStackDesc *top = stack_pop (ctx);
+       
+               if (stack_slot_get_type (top) != TYPE_COMPLEX || top->type->type == MONO_TYPE_VALUETYPE)
+                       CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid argument to ldvirtftn at 0x%04x", ctx->ip_offset));
+       
+               if (method->flags & METHOD_ATTRIBUTE_STATIC)
+                       CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use ldvirtftn with a constructor at 0x%04x", ctx->ip_offset));
+       
+               if (!verify_type_compatibility (ctx, &method->klass->byval_arg, top->type))
+                       CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Unexpected object for ldvirtftn at 0x%04x", ctx->ip_offset));
+       }
+       
+       if (!mono_method_can_access_method_full (ctx->method, method, NULL))
+               CODE_NOT_VERIFIABLE2 (ctx, g_strdup_printf ("Loaded method is not visible for ldftn/ldvirtftn at 0x%04x", ctx->ip_offset), MONO_EXCEPTION_METHOD_ACCESS);
 
-       stack_push_val (ctx, TYPE_COMPLEX, mono_class_get_type (mono_defaults.object_class));
+       top = stack_push_val(ctx, TYPE_PTR, mono_type_create_fnptr_from_mono_method (ctx, method));
+       top->method = method;
 }
 
 static void
-do_unbox_value (VerifyContext *ctx, int klass_token)
+do_sizeof (VerifyContext *ctx, int token)
 {
-       ILStackDesc *value;
-       MonoType *type = get_boxable_mono_type (ctx, klass_token);
+       MonoType *type;
 
-       if (!type)
+       if (!IS_TYPE_DEF_OR_REF_OR_SPEC (token) || !token_bounds_check (ctx->image, token)) {
+               ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid type token %x at 0x%04x", token, ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE);
                return;
-       if (!check_underflow (ctx, 1))
+       }
+       
+       if (!(type = verifier_load_type (ctx, token, "sizeof")))
                return;
 
-       value = stack_pop (ctx);
+       if (type->byref && type->type != MONO_TYPE_TYPEDBYREF) {
+               ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid use of byref type at 0x%04x", ctx->ip_offset));
+               return;
+       }
 
-       if (value->stype != TYPE_COMPLEX || value->type->type != MONO_TYPE_OBJECT)
-               CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid type %s at stack for unbox operation at 0x%04x", type_names [UNMASK_TYPE (value->stype)], ctx->ip_offset));
+       if (type->type == MONO_TYPE_VOID) {
+               ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid use of void type at 0x%04x", ctx->ip_offset));
+               return;
+       }
 
-       //TODO Pushed managed pointer is haver controled mutability (CMMP) 
-       set_stack_value (stack_push (ctx), mono_type_get_type_byref (type), FALSE, FALSE);
+       if (check_overflow (ctx))
+               set_stack_value (ctx, stack_push (ctx), &mono_defaults.uint32_class->byval_arg, FALSE);
 }
 
+/* Stack top can be of any type, the runtime doesn't care and treat everything as an int. */
 static void
-do_unary_math_op (VerifyContext *ctx, int op)
+do_localloc (VerifyContext *ctx)
 {
-       ILStackDesc *value;
-       if (!check_underflow (ctx, 1))
+       if (ctx->eval.size != 1) {
+               ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Stack must have only size item in localloc at 0x%04x", ctx->ip_offset));
+               return;         
+       }
+
+       if (in_any_exception_block (ctx->header, ctx->ip_offset)) {
+               ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Stack must have only size item in localloc at 0x%04x", ctx->ip_offset));
                return;
-       value = stack_top (ctx);
-       switch(value->stype) {
-       case TYPE_I4:
-       case TYPE_I8:
-       case TYPE_NATIVE_INT:
-               break;
-       case TYPE_R8:
-               if (op == CEE_NEG)
-                       break;
-       case TYPE_COMPLEX: /*only enums are ok*/
-               if (value->type->type == MONO_TYPE_VALUETYPE && value->type->data.klass->enumtype)
-                       break;
-       default:
-               CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid type at stack for unary not at 0x%04x", ctx->ip_offset));
        }
+
+       set_stack_value (ctx, stack_top (ctx), &mono_defaults.int_class->byval_arg, FALSE);
+       CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Instruction localloc in never verifiable at 0x%04x", ctx->ip_offset));
 }
 
 static void
-do_conversion (VerifyContext *ctx, int kind) 
+do_ldstr (VerifyContext *ctx, guint32 token)
 {
-       ILStackDesc *value;
-       if (!check_underflow (ctx, 1))
+       if (mono_metadata_token_code (token) != MONO_TOKEN_STRING) {
+               ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid string token %x at 0x%04x", token, ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE);
                return;
-       value = stack_pop (ctx);
-
-       switch(value->stype) {
-       case TYPE_I4:
-       case TYPE_I8:
-       case TYPE_NATIVE_INT:
-       case TYPE_R8:
-               break;
-       default:
-               CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid type at stack for conversion operation at 0x%04x", ctx->ip_offset));
        }
 
-       switch (kind) {
-       case TYPE_I4:
-               stack_push_val (ctx, TYPE_I4, &mono_defaults.int32_class->byval_arg);
-               break;
-       case TYPE_I8:
-               stack_push_val (ctx,TYPE_I8, &mono_defaults.int64_class->byval_arg);
-               break;
-       case TYPE_R8:
-               stack_push_val (ctx, TYPE_R8, &mono_defaults.double_class->byval_arg);
-               break;
-       case TYPE_NATIVE_INT:
-               stack_push_val (ctx, TYPE_NATIVE_INT, &mono_defaults.int_class->byval_arg);
-               break;
-       default:
-               g_error ("unknown type %02x in conversion", kind);
-
+       if (mono_metadata_token_index (token) >= ctx->image->heap_us.size) {
+               ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid string index %x at 0x%04x", token, ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE);
+               return;
        }
+
+       if (check_overflow (ctx))
+               stack_push_val (ctx, TYPE_COMPLEX,  &mono_defaults.string_class->byval_arg);
 }
 
 static void
-do_load_token (VerifyContext *ctx, int token) 
+do_refanyval (VerifyContext *ctx, int token)
 {
-       gpointer handle;
-       MonoClass *handle_class;
-       if (!check_overflow (ctx))
+       ILStackDesc *top;
+       MonoType *type;
+       if (!check_underflow (ctx, 1))
                return;
-       handle = mono_ldtoken (ctx->image, token, &handle_class, ctx->generic_context);
-       if (!handle) {
-               ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid token 0x%x for ldtoken at 0x%04x", token, ctx->ip_offset));
+
+       if (!(type = get_boxable_mono_type (ctx, token, "refanyval")))
                return;
-       }
-       stack_push_val (ctx, TYPE_COMPLEX, mono_class_get_type (handle_class));
+
+       top = stack_pop (ctx);
+
+       if (top->stype != TYPE_PTR || top->type->type != MONO_TYPE_TYPEDBYREF)
+               ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Expected a typedref as argument for refanyval, but found %s at 0x%04x", stack_slot_get_name (top), ctx->ip_offset));
+
+       set_stack_value (ctx, stack_push (ctx), type, TRUE);
 }
 
 static void
-do_ldobj_value (VerifyContext *ctx, int token) 
+do_refanytype (VerifyContext *ctx)
 {
-       ILStackDesc *value;
-       MonoType *type = get_boxable_mono_type (ctx, token);
-
-       if (!type)
-               return;
+       ILStackDesc *top;
 
        if (!check_underflow (ctx, 1))
                return;
 
-       value = stack_pop (ctx);
-       if (!IS_MANAGED_POINTER (value->stype) 
-                       && value->stype != TYPE_NATIVE_INT
-                       && !(value->stype == TYPE_PTR && value->type->type != MONO_TYPE_FNPTR)) {
-               ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid argument %s to ldobj at 0x%04x", type_names [UNMASK_TYPE (value->stype)], ctx->ip_offset));
-               return;
-       }
+       top = stack_pop (ctx);
 
-       if (value->stype == TYPE_NATIVE_INT)
-               CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Using native pointer to ldobj at 0x%04x", ctx->ip_offset));
+       if (top->stype != TYPE_PTR || top->type->type != MONO_TYPE_TYPEDBYREF)
+               ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Expected a typedref as argument for refanytype, but found %s at 0x%04x", stack_slot_get_name (top), ctx->ip_offset));
 
-       /*We have a byval on the stack, we */
-       if (!verify_stack_type_compatibility (ctx, type, mono_type_get_type_byval (value->type), TRUE))
-               CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid type at stack for ldojb operation at 0x%04x", ctx->ip_offset));
+       set_stack_value (ctx, stack_push (ctx), &mono_defaults.typehandle_class->byval_arg, FALSE);
 
-       set_stack_value (stack_push (ctx), type, FALSE, FALSE);
 }
 
 static void
-do_newarr (VerifyContext *ctx, int token) 
+do_mkrefany (VerifyContext *ctx, int token)
 {
-       ILStackDesc *value;
-       MonoType *type = get_boxable_mono_type (ctx, token);
-
-       if (!type)
+       ILStackDesc *top;
+       MonoType *type;
+       if (!check_underflow (ctx, 1))
                return;
 
-       if (!check_underflow (ctx, 1))
+       if (!(type = get_boxable_mono_type (ctx, token, "refanyval")))
                return;
 
-       value = stack_pop (ctx);
-       if (value->stype != TYPE_I4 && value->stype != TYPE_NATIVE_INT)
-               CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Array size type on stack (%s) is not a verifiable type at 0x%04x", type_names [UNMASK_TYPE (value->stype)], ctx->ip_offset));
+       top = stack_pop (ctx);
+
+       if (stack_slot_is_managed_mutability_pointer (top))
+               CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use a readonly pointer with mkrefany at 0x%04x", ctx->ip_offset));
+
+       if (!stack_slot_is_managed_pointer (top)) {
+               CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Expected a managed pointer for mkrefany, but found %s at 0x%04x", stack_slot_get_name (top), ctx->ip_offset));
+       }else {
+               MonoType *stack_type = mono_type_get_type_byval (top->type);
+               if (MONO_TYPE_IS_REFERENCE (type) && !mono_metadata_type_equal (type, stack_type))
+                       CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Type not compatible for mkrefany at 0x%04x", ctx->ip_offset));
+                       
+               if (!MONO_TYPE_IS_REFERENCE (type) && !verify_type_compatibility_full (ctx, type, stack_type, TRUE))
+                       CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Type not compatible for mkrefany at 0x%04x", ctx->ip_offset));
+       }
 
-       set_stack_value (stack_push (ctx), mono_class_get_type (mono_array_class_get (mono_class_from_mono_type (type), 1)), FALSE, FALSE);
+       set_stack_value (ctx, stack_push (ctx), &mono_defaults.typed_reference_class->byval_arg, FALSE);
 }
 
-/*Merge the stacks and perform compat checks*/
+/*
+ * merge_stacks:
+ * Merge the stacks and perform compat checks. The merge check if types of @from are mergeable with type of @to 
+ * 
+ * @from holds new values for a given control path
+ * @to holds the current values of a given control path
+ * 
+ * TODO we can eliminate the from argument as all callers pass &ctx->eval
+ */
 static void
-merge_stacks (VerifyContext *ctx, ILCodeDesc *from, ILCodeDesc *to, int start) 
+merge_stacks (VerifyContext *ctx, ILCodeDesc *from, ILCodeDesc *to, int start, gboolean external
 {
-       int i;
-
-       if (to->flags == IL_CODE_FLAG_NOT_PROCESSED) 
-                       stack_init (ctx, to);
+       int i, j, k;
+       stack_init (ctx, to);
 
        if (start) {
                if (to->flags == IL_CODE_FLAG_NOT_PROCESSED) 
                        from->size = 0;
                else
-                       stack_copy (&ctx->eval, to); 
+                       stack_copy (&ctx->eval, to);
                goto end_verify;
-       } else if (to->flags == IL_CODE_FLAG_NOT_PROCESSED) {
-               stack_copy (to, from);
+       } else if (!(to->flags & IL_CODE_STACK_MERGED)) {
+               stack_copy (to, &ctx->eval);
                goto end_verify;
        }
        VERIFIER_DEBUG ( printf ("performing stack merge %d x %d\n", from->size, to->size); );
 
        if (from->size != to->size) {
-               VERIFIER_DEBUG ( printf ("diferent stack sizes %d x %d\n", from->size, to->size); );
-               CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Could not merge stacks, diferent sizes (%d x %d)", from->size, to->size)); 
+               VERIFIER_DEBUG ( printf ("different stack sizes %d x %d at 0x%04x\n", from->size, to->size, ctx->ip_offset); );
+               ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Could not merge stacks, different sizes (%d x %d) at 0x%04x", from->size, to->size, ctx->ip_offset)); 
                goto end_verify;
        }
 
+       //FIXME we need to preserve CMMP attributes
+       //FIXME we must take null literals into consideration.
        for (i = 0; i < from->size; ++i) {
-               ILStackDesc *from_slot = from->stack + i;
-               ILStackDesc *to_slot = to->stack + i;
-               int from_stype = from_slot->stype;
-               int to_stype = to_slot->stype;
-
-#define IS_NATIVE_INT_AND_I4(val0, val1) (UNMASK_TYPE(val0) == TYPE_NATIVE_INT && \
-                       UNMASK_TYPE(val1->stype) == TYPE_I4 && (val1->type->type == MONO_TYPE_I4 || val1->type->type == MONO_TYPE_U4))
-               /* This is the only case of merging between verification types.
-                * Both stack values must be either native int or int4, and both must be either byref or not.*/
-               if ((IS_NATIVE_INT_AND_I4 (from_stype, to_slot) || IS_NATIVE_INT_AND_I4 (to_stype, from_slot)) &&
-                       !(IS_MANAGED_POINTER (from_stype) ^ IS_MANAGED_POINTER (to_stype))) {
-                       printf ("----is native int\n");
-                       to_slot->stype = TYPE_NATIVE_INT;
-                       if (UNMASK_TYPE(from_stype) == TYPE_NATIVE_INT)
-                               to_slot->type = from_slot->type;
+               ILStackDesc *new_slot = from->stack + i;
+               ILStackDesc *old_slot = to->stack + i;
+               MonoType *new_type = mono_type_from_stack_slot (new_slot);
+               MonoType *old_type = mono_type_from_stack_slot (old_slot);
+               MonoClass *old_class = mono_class_from_mono_type (old_type);
+               MonoClass *new_class = mono_class_from_mono_type (new_type);
+               MonoClass *match_class = NULL;
+
+               // S := T then U = S (new value is compatible with current value, keep current)
+               if (verify_type_compatibility (ctx, old_type, new_type)) {
+                       copy_stack_value (new_slot, old_slot);
                        continue;
                }
-#undef IS_NATIVE_INT_OR_I4
-
-               if (from_stype != to_stype) {
-                       VERIFIER_DEBUG ( printf ("diferent stack types %d x %d\n", from_stype, to_stype); );
-                       CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Could not merge stacks, diferent verification types (%s x %s)",
-                               type_names [UNMASK_TYPE (from_stype)], type_names [UNMASK_TYPE (to_stype)])); 
-                       goto end_verify;
-               }
-
-               if (IS_MANAGED_POINTER (from_stype)) {
-                       from_stype = UNMASK_TYPE (from_stype);
-                       to_stype = UNMASK_TYPE (to_stype);
 
-                       if (from_slot->type && !verify_stack_type_compatibility (ctx, to_slot->type, from_slot->type, TRUE)) {
-                               CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Could not merge stacks, managed pointer types not compatible")); 
-                               goto end_verify;
-                       } else
-                               copy_stack_value (to_slot, from_slot);
+               // T := S then U = T (old value is compatible with current value, use new)
+               if (verify_type_compatibility (ctx, new_type, old_type)) {
+                       copy_stack_value (old_slot, new_slot);
                        continue;
                }
 
-               if (from_stype == TYPE_COMPLEX) {
-                       if (!to->stack [i].type) {
-                               ctx->verifiable = 0;
-                               g_assert (0);
-                       } else if (!verify_type_compat (ctx, to_slot->type, from_slot)) {
-                               CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Could not merge stacks, types not compatible")); 
-                               goto end_verify;
-                       } else { 
-                               /*TODO we need to choose the base class for merging */
-                               copy_stack_value (to_slot, from_slot);
+               //both are reference types, use closest common super type
+               if (!mono_class_from_mono_type (old_type)->valuetype 
+                       && !mono_class_from_mono_type (new_type)->valuetype
+                       && !stack_slot_is_managed_pointer (old_slot)
+                       && !stack_slot_is_managed_pointer (new_slot)) {
+                       
+                       for (j = MIN (old_class->idepth, new_class->idepth) - 1; j > 0; --j) {
+                               if (mono_metadata_type_equal (&old_class->supertypes [j]->byval_arg, &new_class->supertypes [j]->byval_arg)) {
+                                       match_class = old_class->supertypes [j];
+                                       goto match_found;
+                               }
                        }
-                       continue;
+
+                       for (j = 0; j < old_class->interface_count; ++j) {
+                               for (k = 0; k < new_class->interface_count; ++k) {
+                                       if (mono_metadata_type_equal (&old_class->interfaces [j]->byval_arg, &new_class->interfaces [k]->byval_arg)) {
+                                               match_class = old_class->interfaces [j];
+                                               goto match_found;
+                                       }
+                               }
+                       }
+
+                       //No decent super type found, use object
+                       match_class = mono_defaults.object_class;
+                       goto match_found;
+               } else if (is_compatible_boxed_valuetype (old_type, new_type, new_slot, FALSE) || is_compatible_boxed_valuetype (new_type, old_type, old_slot, FALSE)) {
+                       match_class = mono_defaults.object_class;
+                       goto match_found;
                } 
 
-               copy_stack_value (to_slot, from_slot);
+               CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Could not merge stack at depth %d, types not compatible old [%s] new [%s] at 0x%04x", i, stack_slot_get_name (old_slot), stack_slot_get_name (new_slot), ctx->ip_offset)); 
+               goto end_verify;
+
+match_found:
+               g_assert (match_class);
+               set_stack_value (ctx, old_slot, &match_class->byval_arg, stack_slot_is_managed_pointer (old_slot));
+               set_stack_value (ctx, new_slot, &match_class->byval_arg, stack_slot_is_managed_pointer (old_slot));
+               continue;
        }
 
 end_verify:
-       to->flags = IL_CODE_FLAG_SEEN;
+       if (external)
+               to->flags |= IL_CODE_FLAG_WAS_TARGET;
+       to->flags |= IL_CODE_STACK_MERGED;
+}
+
+#define HANDLER_START(clause) ((clause)->flags == MONO_EXCEPTION_CLAUSE_FILTER ? (clause)->data.filter_offset : clause->handler_offset)
+#define IS_CATCH_OR_FILTER(clause) ((clause)->flags == MONO_EXCEPTION_CLAUSE_FILTER || (clause)->flags == MONO_EXCEPTION_CLAUSE_NONE)
+
+/*
+ * is_clause_in_range :
+ * 
+ * Returns TRUE if either the protected block or the handler of @clause is in the @start - @end range.  
+ */
+static gboolean
+is_clause_in_range (MonoExceptionClause *clause, guint32 start, guint32 end)
+{
+       if (clause->try_offset >= start && clause->try_offset < end)
+               return TRUE;
+       if (HANDLER_START (clause) >= start && HANDLER_START (clause) < end)
+               return TRUE;
+       return FALSE;
+}
+
+/*
+ * is_clause_inside_range :
+ * 
+ * Returns TRUE if @clause lies completely inside the @start - @end range.  
+ */
+static gboolean
+is_clause_inside_range (MonoExceptionClause *clause, guint32 start, guint32 end)
+{
+       if (clause->try_offset < start || (clause->try_offset + clause->try_len) > end)
+               return FALSE;
+       if (HANDLER_START (clause) < start || (clause->handler_offset + clause->handler_len) > end)
+               return FALSE;
+       return TRUE;
+}
+
+/*
+ * is_clause_nested :
+ * 
+ * Returns TRUE if @nested is nested in @clause.   
+ */
+static gboolean
+is_clause_nested (MonoExceptionClause *clause, MonoExceptionClause *nested)
+{
+       if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER && is_clause_inside_range (nested, clause->data.filter_offset, clause->handler_offset))
+               return TRUE;
+       return is_clause_inside_range (nested, clause->try_offset, clause->try_offset + clause->try_len) ||
+       is_clause_inside_range (nested, clause->handler_offset, clause->handler_offset + clause->handler_len);
 }
 
+/* Test the relationship between 2 exception clauses. Follow  P.1 12.4.2.7 of ECMA
+ * the each pair of exception must have the following properties:
+ *  - one is fully nested on another (the outer must not be a filter clause) (the nested one must come earlier)
+ *  - completely disjoin (none of the 3 regions of each entry overlap with the other 3)
+ *  - mutual protection (protected block is EXACT the same, handlers are disjoin and all handler are catch or all handler are filter)
+ */
+static void
+verify_clause_relationship (VerifyContext *ctx, MonoExceptionClause *clause, MonoExceptionClause *to_test)
+{
+       /*clause is nested*/
+       if (is_clause_nested (to_test, clause)) {
+               if (to_test->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
+                       ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Exception clause inside filter"));
+               }
+               return;
+       }
+
+       /*wrong nesting order.*/
+       if (is_clause_nested (clause, to_test)) {
+               ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Nested exception clause appears after enclosing clause"));
+               return;
+       }
+
+       /*mutual protection*/
+       if (clause->try_offset == to_test->try_offset && clause->try_len == to_test->try_len) {
+               /*handlers are not disjoint*/
+               if (is_clause_in_range (to_test, HANDLER_START (clause), clause->handler_offset + clause->handler_len)) {
+                       ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Exception handlers overlap"));
+                       return;
+               }
+               /* handlers are not catch or filter */
+               if (!IS_CATCH_OR_FILTER (clause) || !IS_CATCH_OR_FILTER (to_test)) {
+                       ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Exception clauses with shared protected block are neither catch or filter"));
+                       return;
+               }
+               /*OK*/
+               return;
+       }
+
+       /*not completelly disjoint*/
+       if (is_clause_in_range (to_test, clause->try_offset, clause->try_offset + clause->try_len) ||
+               is_clause_in_range (to_test, HANDLER_START (clause), clause->handler_offset + clause->handler_len))
+               ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Exception clauses overlap"));
+}
 
 /*
  * FIXME: need to distinguish between valid and verifiable.
@@ -2902,18 +4048,16 @@ end_verify:
 GSList*
 mono_method_verify (MonoMethod *method, int level)
 {
-       MonoMethodSignature *csig;
        const unsigned char *ip;
        const unsigned char *end;
-       const unsigned char *target = NULL; /* branch target */
        int i, n, need_merge = 0, start = 0;
        guint token, ip_offset = 0, prefix = 0;
-       MonoClass *klass;
-       MonoMethod *cmethod;
        MonoGenericContext *generic_context = NULL;
        MonoImage *image;
        VerifyContext ctx;
-       VERIFIER_DEBUG ( printf ("Verify IL for method %s %s\n",  method->klass->name, method->name); );
+       GSList *tmp;
+
+       VERIFIER_DEBUG ( printf ("Verify IL for method %s %s %s\n",  method->klass->name_space,  method->klass->name, method->name); );
 
        if (method->iflags & (METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL | METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
                        (method->flags & (METHOD_ATTRIBUTE_PINVOKE_IMPL | METHOD_ATTRIBUTE_ABSTRACT))) {
@@ -2922,6 +4066,7 @@ mono_method_verify (MonoMethod *method, int level)
 
        memset (&ctx, 0, sizeof (VerifyContext));
 
+       //FIXME use mono_method_get_signature_full
        ctx.signature = mono_method_signature (method);
        if (!ctx.signature) {
                ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Could not decode method signature"));
@@ -2941,6 +4086,7 @@ mono_method_verify (MonoMethod *method, int level)
        ctx.max_args = ctx.signature->param_count + ctx.signature->hasthis;
        ctx.max_stack = ctx.header->max_stack;
        ctx.verifiable = ctx.valid = 1;
+       ctx.level = level;
 
        ctx.code = g_new0 (ILCodeDesc, ctx.header->code_size);
        ctx.code_size = ctx.header->code_size;
@@ -2951,59 +4097,120 @@ mono_method_verify (MonoMethod *method, int level)
        ctx.num_locals = ctx.header->num_locals;
        ctx.locals = ctx.header->locals;
 
+       if (ctx.num_locals > 0 && !ctx.header->init_locals)
+               CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Method with locals variable but without init locals set"));
+
+       if (ctx.signature->hasthis) {
+               ctx.params = g_new0 (MonoType*, ctx.max_args);
+               ctx.params [0] = method->klass->valuetype ? &method->klass->this_arg : &method->klass->byval_arg;
+               memcpy (ctx.params + 1, ctx.signature->params, sizeof (MonoType *) * ctx.signature->param_count);
+       } else {
+               ctx.params = ctx.signature->params;
+       }
+
+       if (ctx.signature->is_inflated)
+               ctx.generic_context = generic_context = mono_method_get_context (method);
+
+       if (!generic_context && (method->klass->generic_container || method->generic_container)) {
+               if (method->generic_container)
+                       ctx.generic_context = generic_context = &method->generic_container->context;
+               else
+                       ctx.generic_context = generic_context = &method->klass->generic_container->context;
+       }
+
+       stack_init (&ctx, &ctx.eval);
+
+       for (i = 0; i < ctx.header->num_clauses && ctx.valid; ++i) {
+               MonoExceptionClause *clause = ctx.header->clauses + i;
+               VERIFIER_DEBUG (printf ("clause try %x len %x filter at %x handler at %x len %x\n", clause->try_offset, clause->try_len, clause->data.filter_offset, clause->handler_offset, clause->handler_len); );
+
+               if (clause->try_offset > ctx.code_size)
+                       ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("try clause out of bounds at 0x%04x", clause->try_offset));
+
+               if (clause->try_len <= 0)
+                       ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("try clause len <= 0 at 0x%04x", clause->try_offset));
+
+               if (clause->handler_offset > ctx.code_size)
+                       ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("try clause out of bounds at 0x%04x", clause->try_offset));
+
+               if (clause->handler_len <= 0)
+                       ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("try clause len <= 0 at 0x%04x", clause->try_offset));
 
-       if (ctx.signature->hasthis) {
-               ctx.params = g_new0 (MonoType*, ctx.max_args);
-               ctx.params [0] = &method->klass->this_arg;
-               memcpy (ctx.params + 1, ctx.signature->params, sizeof (MonoType *) * ctx.signature->param_count);
-       } else {
-               ctx.params = ctx.signature->params;
-       }
+               if (clause->try_offset < clause->handler_offset && clause->try_offset + clause->try_len > HANDLER_START (clause))
+                       ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("try block (at 0x%04x) includes handler block (at 0x%04x)", clause->try_offset, clause->handler_offset));
 
-       if (ctx.signature->is_inflated)
-               ctx.generic_context = generic_context = mono_method_get_context (method);
+               for (n = i + 1; n < ctx.header->num_clauses && ctx.valid; ++n)
+                       verify_clause_relationship (&ctx, clause, ctx.header->clauses + n);
 
-       stack_init (&ctx, &ctx.eval);
+               if (!ctx.valid)
+                       break;
 
+               ctx.code [clause->try_offset].flags |= IL_CODE_FLAG_WAS_TARGET;
+               ctx.code [clause->try_offset + clause->try_len].flags |= IL_CODE_FLAG_WAS_TARGET;
+               ctx.code [clause->handler_offset + clause->handler_len].flags |= IL_CODE_FLAG_WAS_TARGET;
 
-       for (i = 0; i < ctx.header->num_clauses; ++i) {
-               MonoExceptionClause *clause = ctx.header->clauses + i;
-               /* catch blocks and filter have the exception on the stack. */
-               /* must check boundaries for handler_offset and handler_start < handler_start*/
                if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE) {
-                       ILCodeDesc *code = ctx.code + clause->handler_offset;
-                       stack_init (&ctx, code);
-                       code->stack [0].stype = TYPE_COMPLEX;
-                       code->stack [0].type = &clause->data.catch_class->byval_arg;
-                       code->size = 1;
-                       code->flags = IL_CODE_FLAG_SEEN;
+                       init_stack_with_value_at_exception_boundary (&ctx, ctx.code + clause->handler_offset, clause->data.catch_class);
                }
                else if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
-                       ILCodeDesc *code = ctx.code + clause->data.filter_offset;
-                       stack_init (&ctx, code);
-                       code->stack [0].stype = TYPE_COMPLEX;
-                       code->stack [0].type = &mono_defaults.exception_class->byval_arg;
-                       code->size = 1;
-                       code->flags = IL_CODE_FLAG_SEEN;
+                       init_stack_with_value_at_exception_boundary (&ctx, ctx.code + clause->data.filter_offset, mono_defaults.exception_class);
+                       init_stack_with_value_at_exception_boundary (&ctx, ctx.code + clause->handler_offset, mono_defaults.exception_class);   
                }
        }
 
        while (ip < end && ctx.valid) {
                ctx.ip_offset = ip_offset = ip - ctx.header->code;
 
-               /*TODO id stack merge fails, we break, should't we - or only on errors??
-               TODO verify need_merge
-               */
+               /*We need to check against fallthrou in and out of protected blocks.
+                * For fallout we check the once a protected block ends, if the start flag is not set.
+                * Likewise for fallthru in, we check if ip is the start of a protected block and start is not set
+                * TODO convert these checks to be done using flags and not this loop
+                */
+               for (i = 0; i < ctx.header->num_clauses && ctx.valid; ++i) {
+                       MonoExceptionClause *clause = ctx.header->clauses + i;
+
+                       if ((clause->try_offset + clause->try_len == ip_offset) && start == 0) {
+                               CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("fallthru off try block at 0x%04x", ip_offset));
+                               start = 1;
+                       }
+
+                       if ((clause->handler_offset + clause->handler_len == ip_offset) && start == 0) {
+                               if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER)
+                                       ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("fallout of handler block at 0x%04x", ip_offset));
+                               else
+                                       CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("fallout of handler block at 0x%04x", ip_offset));
+                               start = 1;
+                       }
+
+                       if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER && clause->handler_offset == ip_offset && start == 0) {
+                               ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("fallout of filter block at 0x%04x", ip_offset));
+                               start = 1;
+                       }
+
+                       if (clause->handler_offset == ip_offset && start == 0) {
+                               CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("fallthru handler block at 0x%04x", ip_offset));
+                               start = 1;
+                       }
+
+                       if (clause->try_offset == ip_offset && ctx.eval.size > 0) {
+                               ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Try to enter try block with a non-empty stack at 0x%04x", ip_offset));
+                               start = 1;
+                       }
+               }
+
+               if (!ctx.valid)
+                       break;
+
                if (need_merge) {
-                       VERIFIER_DEBUG ( printf ("extra merge needed! %d \n", ctx.target); );
-                       merge_stacks (&ctx, &ctx.eval, &ctx.code [ctx.target], FALSE);
+                       VERIFIER_DEBUG ( printf ("extra merge needed! 0x%04x \n", ctx.target); );
+                       merge_stacks (&ctx, &ctx.eval, &ctx.code [ctx.target], FALSE, TRUE);
                        need_merge = 0; 
                }
-               merge_stacks (&ctx, &ctx.eval, &ctx.code[ip_offset], start);
+               merge_stacks (&ctx, &ctx.eval, &ctx.code[ip_offset], start, FALSE);
                start = 0;
 
-/*TODO rename to zero */
-#if 1
+               /*TODO we can fast detect a forward branch or exception block targeting code after prefix, we should fail fast*/
+#ifdef MONO_VERIFIER_DEBUG
                {
                        char *discode;
                        discode = mono_disasm_code_one (NULL, method, ip, NULL);
@@ -3011,7 +4218,8 @@ mono_method_verify (MonoMethod *method, int level)
                        g_print ("[%d] %-29s (%d)\n",  ip_offset, discode, ctx.eval.size);
                        g_free (discode);
                }
-               dump_stack_state(&ctx.code[ip_offset]);
+               dump_stack_state (&ctx.code [ip_offset]);
+               dump_stack_state (&ctx.eval);
 #endif
 
                switch (*ip) {
@@ -3034,6 +4242,24 @@ mono_method_verify (MonoMethod *method, int level)
                        ip += 2;
                        break;
 
+               case CEE_ADD_OVF_UN:
+                       do_binop (&ctx, *ip, add_ovf_un_table);
+                       ++ip;
+                       break;
+
+               case CEE_SUB_OVF_UN:
+                       do_binop (&ctx, *ip, sub_ovf_un_table);
+                       ++ip;
+                       break;
+
+               case CEE_ADD_OVF:
+               case CEE_SUB_OVF:
+               case CEE_MUL_OVF:
+               case CEE_MUL_OVF_UN:
+                       do_binop (&ctx, *ip, bin_ovf_table);
+                       ++ip;
+                       break;
+
                case CEE_ADD:
                        do_binop (&ctx, *ip, add_table);
                        ++ip;
@@ -3154,7 +4380,7 @@ mono_method_verify (MonoMethod *method, int level)
 
                case CEE_LDNULL:
                        if (check_overflow (&ctx))
-                               stack_push_val (&ctx,TYPE_COMPLEX, &mono_defaults.object_class->byval_arg);
+                               stack_push_val (&ctx, TYPE_COMPLEX | NULL_LITERAL_MASK, &mono_defaults.object_class->byval_arg);
                        ++ip;
                        break;
 
@@ -3234,7 +4460,7 @@ mono_method_verify (MonoMethod *method, int level)
                        break;
                case CEE_CALL:
                case CEE_CALLVIRT:
-                       do_invoke_method (&ctx, read32 (ip + 1));
+                       do_invoke_method (&ctx, read32 (ip + 1), *ip == CEE_CALLVIRT);
                        ip += 5;
                        break;
 
@@ -3246,11 +4472,8 @@ mono_method_verify (MonoMethod *method, int level)
                        ip += 5;
                        break;
                case CEE_BR_S:
-                       target = ip + (signed char)ip [1] + 2;
-                       if (target >= end || target < ctx.header->code)
-                               ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Branch target out of code at 0x%04x", ip_offset));
-                       if (!in_same_block (ctx.header, ip_offset, target - ctx.header->code))
-                               ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Branch target escapes out of exception block at 0x%04x", ip_offset));
+                       do_static_branch (&ctx, (signed char)ip [1] + 2);
+                       need_merge = 1;
                        ip += 2;
                        start = 1;
                        break;
@@ -3263,11 +4486,8 @@ mono_method_verify (MonoMethod *method, int level)
                        break;
 
                case CEE_BR:
-                       target = ip + (gint32)read32 (ip + 1) + 5;
-                       if (target >= end || target < ctx.header->code)
-                               ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Branch target out of code at 0x%04x", ip_offset));
-                       if (!in_same_block (ctx.header, ip_offset, target - ctx.header->code))
-                               ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Branch target escapes out of exception block at 0x%04x", ip_offset));
+                       do_static_branch (&ctx, (gint32)read32 (ip + 1) + 5);
+                       need_merge = 1;
                        ip += 5;
                        start = 1;
                        break;
@@ -3281,17 +4501,11 @@ mono_method_verify (MonoMethod *method, int level)
 
                case CEE_SWITCH:
                        n = read32 (ip + 1);
-                       target = ip + sizeof (guint32) * n;
-                       /* FIXME: check that ip is in range (and within the same exception block) */
-                       for (i = 0; i < n; ++i)
-                               if (target + (gint32) read32 (ip + 5 + i * sizeof (gint32)) >= end || target + (gint32) read32 (ip + 5 + i * sizeof (gint32)) < ctx.header->code)
-                                       ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Branch target out of code at 0x%04x", ip_offset));
-                       if (!check_underflow (&ctx, 1))
-                               break;
-                       if (stack_pop (&ctx)->stype != TYPE_I4)
-                               ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid argument to switch at 0x%04x", ip_offset));
+                       do_switch (&ctx, n, (ip + 5));
+                       start = 1;
                        ip += 5 + sizeof (guint32) * n;
                        break;
+
                case CEE_LDIND_I1:
                case CEE_LDIND_U1:
                case CEE_LDIND_I2:
@@ -3303,13 +4517,10 @@ mono_method_verify (MonoMethod *method, int level)
                case CEE_LDIND_R4:
                case CEE_LDIND_R8:
                case CEE_LDIND_REF:
-                       if (!check_underflow (&ctx, 1))
-                               break;
-                       if (stack_top (&ctx)->stype != TYPE_PTR && stack_top (&ctx)->stype != TYPE_COMPLEX)
-                               ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid argument to ldind at 0x%04x", ip_offset));
-                       stack_top (&ctx)->stype = ldind_type [*ip - CEE_LDIND_I1];
+                       do_load_indirect (&ctx, *ip);
                        ++ip;
                        break;
+                       
                case CEE_STIND_REF:
                case CEE_STIND_I1:
                case CEE_STIND_I2:
@@ -3317,13 +4528,8 @@ mono_method_verify (MonoMethod *method, int level)
                case CEE_STIND_I8:
                case CEE_STIND_R4:
                case CEE_STIND_R8:
-                       if (!check_underflow (&ctx, 2))
-                               break;
-                       ctx.eval.size -= 2;
-                       if (stack_top (&ctx)->stype != TYPE_PTR && stack_top (&ctx)->stype != TYPE_COMPLEX)
-                               ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid pointer argument to stind at 0x%04x", ip_offset));
-                       if (!stind_type (*ip, stack_get (&ctx, -1)->stype))
-                               ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Incompatible value argument to stind at 0x%04x", ip_offset));
+               case CEE_STIND_I:
+                       do_store_indirect (&ctx, *ip);
                        ++ip;
                        break;
 
@@ -3333,7 +4539,6 @@ mono_method_verify (MonoMethod *method, int level)
                        ++ip;
                        break;
 
-               //TODO: implement proper typecheck
                case CEE_CONV_I1:
                case CEE_CONV_I2:
                case CEE_CONV_I4:
@@ -3364,10 +4569,7 @@ mono_method_verify (MonoMethod *method, int level)
                        break;
 
                case CEE_CPOBJ:
-                       token = read32 (ip + 1);
-                       if (!check_underflow (&ctx, 2))
-                               break;
-                       ctx.eval.size -= 2;
+                       do_cpobj (&ctx, read32 (ip + 1));
                        ip += 5;
                        break;
 
@@ -3377,36 +4579,21 @@ mono_method_verify (MonoMethod *method, int level)
                        break;
 
                case CEE_LDSTR:
-                       /*TODO verify if token is a valid string literal*/
-                       token = read32 (ip + 1);
-                       if (check_overflow (&ctx))
-                               stack_push_val (&ctx, TYPE_COMPLEX,  &mono_defaults.string_class->byval_arg);
+                       do_ldstr (&ctx, read32 (ip + 1));
                        ip += 5;
                        break;
-               case CEE_NEWOBJ:
-                       token = read32 (ip + 1);
-                       /*
-                        * FIXME: we could just load the signature ...
-                        */
-                       cmethod = mono_get_method_full (image, token, NULL, generic_context);
-                       if (!cmethod)
-                               ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Constructor 0x%08x not found at 0x%04x", token, ip_offset));
-                       csig = mono_method_signature (cmethod);
-                       if (!check_underflow (&ctx, csig->param_count))
-                               break;
-                       ctx.eval.size -= csig->param_count;
-                       if (check_overflow (&ctx))
-                               stack_push_val (&ctx, cmethod->klass->valuetype? TYPE_COMPLEX: TYPE_COMPLEX, &cmethod->klass->byval_arg);
 
+               case CEE_NEWOBJ:
+                       do_newobj (&ctx, read32 (ip + 1));
                        ip += 5;
                        break;
+
                case CEE_CASTCLASS:
                case CEE_ISINST:
-                       token = read32 (ip + 1);
-                       if (!check_underflow (&ctx, 1))
-                               break;
+                       do_cast (&ctx, read32 (ip + 1), *ip == CEE_CASTCLASS ? "castclass" : "isinst");
                        ip += 5;
                        break;
+
                case CEE_UNUSED58:
                case CEE_UNUSED1:
                        ++ip; /* warn, error ? */
@@ -3415,12 +4602,11 @@ mono_method_verify (MonoMethod *method, int level)
                        do_unbox_value (&ctx, read32 (ip + 1));
                        ip += 5;
                        break;
+
                case CEE_THROW:
-                       if (!check_underflow (&ctx, 1))
-                               break;
-                       stack_pop (&ctx);
-                       ++ip;
+                       do_throw (&ctx);
                        start = 1;
+                       ++ip;
                        break;
 
                case CEE_LDFLD:
@@ -3444,11 +4630,9 @@ mono_method_verify (MonoMethod *method, int level)
                        do_store_static_field (&ctx, read32 (ip + 1));
                        ip += 5;
                        break;
+
                case CEE_STOBJ:
-                       if (!check_underflow (&ctx, 2))
-                               break;
-                       ctx.eval.size -= 2;
-                       token = read32 (ip + 1);
+                       do_stobj (&ctx, read32 (ip + 1));
                        ip += 5;
                        break;
 
@@ -3485,26 +4669,15 @@ mono_method_verify (MonoMethod *method, int level)
                        break;
 
                case CEE_LDLEN:
-                       if (!check_underflow (&ctx, 1))
-                               break;
-                       if (stack_top (&ctx)->stype != TYPE_COMPLEX)
-                               ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid argument to ldlen at 0x%04x", ip_offset));
-                       stack_top (&ctx)->type = &mono_defaults.int32_class->byval_arg; /* FIXME: use a native int type */
-                       stack_top (&ctx)->stype = TYPE_PTR;
+                       do_ldlen (&ctx);
                        ++ip;
                        break;
+
                case CEE_LDELEMA:
-                       if (check_underflow (&ctx, 2))
-                               break;
-                       --ctx.eval.size;
-                       if (stack_top (&ctx)->stype != TYPE_COMPLEX)
-                               ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid array argument to ldelema at 0x%04x", ip_offset));
-                       if (stack_top (&ctx)->stype != TYPE_I4 && stack_top (&ctx)->stype != TYPE_PTR)
-                               ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Array index needs to be Int32 or IntPtr at 0x%04x", ip_offset));
-                       stack_top (&ctx)->stype = TYPE_COMPLEX;
-                       token = read32 (ip + 1);
+                       do_ldelema (&ctx, read32 (ip + 1));
                        ip += 5;
                        break;
+
                case CEE_LDELEM_I1:
                case CEE_LDELEM_U1:
                case CEE_LDELEM_I2:
@@ -3516,16 +4689,10 @@ mono_method_verify (MonoMethod *method, int level)
                case CEE_LDELEM_R4:
                case CEE_LDELEM_R8:
                case CEE_LDELEM_REF:
-                       if (!check_underflow (&ctx, 2))
-                               break;
-                       --ctx.eval.size;
-                       if (stack_top (&ctx)->stype != TYPE_COMPLEX)
-                               ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid array argument to ldelem at 0x%04x", ip_offset));
-                       if (stack_top (&ctx)->stype != TYPE_I4 && stack_top (&ctx)->stype != TYPE_PTR)
-                               ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Array index needs to be Int32 or IntPtr at 0x%04x", ip_offset));
-                       stack_top (&ctx)->stype = ldelem_type [*ip - CEE_LDELEM_I1];
+                       do_ldelem (&ctx, *ip, 0);
                        ++ip;
                        break;
+
                case CEE_STELEM_I:
                case CEE_STELEM_I1:
                case CEE_STELEM_I2:
@@ -3534,14 +4701,25 @@ mono_method_verify (MonoMethod *method, int level)
                case CEE_STELEM_R4:
                case CEE_STELEM_R8:
                case CEE_STELEM_REF:
-                       if (!check_underflow (&ctx, 3))
-                               break;
-                       ctx.eval.size -= 3;
+                       do_stelem (&ctx, *ip, 0);
                        ++ip;
                        break;
+
                case CEE_LDELEM_ANY:
+                       do_ldelem (&ctx, *ip, read32 (ip + 1));
+                       ip += 5;
+                       break;
+
                case CEE_STELEM_ANY:
+                       do_stelem (&ctx, *ip, read32 (ip + 1));
+                       ip += 5;
+                       break;
+                       
                case CEE_UNBOX_ANY:
+                       do_unbox_any (&ctx, read32 (ip + 1));
+                       ip += 5;
+                       break;
+
                case CEE_UNUSED5:
                case CEE_UNUSED6:
                case CEE_UNUSED7:
@@ -3590,9 +4768,8 @@ mono_method_verify (MonoMethod *method, int level)
                        ++ip; /* warn, error ? */
                        break;
                case CEE_REFANYVAL:
-                       if (!check_underflow (&ctx, 1))
-                               break;
-                       ++ip;
+                       do_refanyval (&ctx, read32 (ip + 1));
+                       ip += 5;
                        break;
                case CEE_CKFINITE:
                        if (!check_underflow (&ctx, 1))
@@ -3603,12 +4780,12 @@ mono_method_verify (MonoMethod *method, int level)
                case CEE_UNUSED25:
                        ++ip; /* warn, error ? */
                        break;
+
                case CEE_MKREFANY:
-                       if (!check_underflow (&ctx, 1))
-                               break;
-                       token = read32 (ip + 1);
+                       do_mkrefany (&ctx,  read32 (ip + 1));
                        ip += 5;
                        break;
+
                case CEE_UNUSED59:
                case CEE_UNUSED60:
                case CEE_UNUSED61:
@@ -3625,45 +4802,26 @@ mono_method_verify (MonoMethod *method, int level)
                        ip += 5;
                        break;
 
-               case CEE_ADD_OVF:
-               case CEE_ADD_OVF_UN:
-               case CEE_MUL_OVF:
-               case CEE_MUL_OVF_UN:
-               case CEE_SUB_OVF:
-               case CEE_SUB_OVF_UN:
-                       if (!check_underflow (&ctx, 2))
-                               break;
-                       stack_pop (&ctx);
-                       ++ip;
-                       break;
                case CEE_ENDFINALLY:
-                       ++ip;
+                       if (!is_correct_endfinally (ctx.header, ip_offset))
+                               ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("endfinally must be used inside a finally/fault handler at 0x%04x", ctx.ip_offset));
+                       ctx.eval.size = 0;
                        start = 1;
+                       ++ip;
                        break;
+
                case CEE_LEAVE:
-                       target = ip + (gint32)read32(ip + 1) + 5;
-                       if (target >= end || target < ctx.header->code)
-                               ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Branch target out of code at 0x%04x", ip_offset));
-                       if (!is_correct_leave (ctx.header, ip_offset, target - ctx.header->code))
-                               ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Leave not allowed in finally block at 0x%04x", ip_offset));
+                       do_leave (&ctx, read32 (ip + 1) + 5);
                        ip += 5;
                        start = 1;
                        break;
+
                case CEE_LEAVE_S:
-                       target = ip + (signed char)ip [1] + 2;
-                       if (target >= end || target < ctx.header->code)
-                               ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Branch target out of code at 0x%04x", ip_offset));
-                       if (!is_correct_leave (ctx.header, ip_offset, target - ctx.header->code))
-                               ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Leave not allowed in finally block at 0x%04x", ip_offset));
+                       do_leave (&ctx, (signed char)ip [1] + 2);
                        ip += 2;
                        start = 1;
                        break;
-               case CEE_STIND_I:
-                       if (!check_underflow (&ctx, 2))
-                               break;
-                       ctx.eval.size -= 2;
-                       ++ip;
-                       break;
+                       
                case CEE_UNUSED26:
                case CEE_UNUSED27:
                case CEE_UNUSED28:
@@ -3707,7 +4865,7 @@ mono_method_verify (MonoMethod *method, int level)
                                break;
 
                        case CEE_CEQ:
-                               do_cmp_op (&ctx, cmp_br_eq_op);
+                               do_cmp_op (&ctx, cmp_br_eq_op, *ip);
                                ++ip;
                                break;
 
@@ -3715,7 +4873,7 @@ mono_method_verify (MonoMethod *method, int level)
                        case CEE_CGT_UN:
                        case CEE_CLT:
                        case CEE_CLT_UN:
-                               do_cmp_op (&ctx, cmp_br_op);
+                               do_cmp_op (&ctx, cmp_br_op, *ip);
                                ++ip;
                                break;
 
@@ -3727,24 +4885,22 @@ mono_method_verify (MonoMethod *method, int level)
 
                        case CEE_ARGLIST:
                                check_overflow (&ctx);
+                               if (ctx.signature->call_convention != MONO_CALL_VARARG)
+                                       ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Cannot use arglist on method without VARGARG calling convention at 0x%04x", ctx.ip_offset));
+                               set_stack_value (&ctx, stack_push (&ctx), &mono_defaults.argumenthandle_class->byval_arg, FALSE);
                                ++ip;
+                               break;
+       
                        case CEE_LDFTN:
-                               if (!check_overflow (&ctx))
-                                       break;
-                               token = read32 (ip + 1);
+                               do_load_function_ptr (&ctx, read32 (ip + 1), FALSE);
                                ip += 5;
-                               stack_top (&ctx)->stype = TYPE_PTR;
-                               ctx.eval.size++;
                                break;
+
                        case CEE_LDVIRTFTN:
-                               if (!check_underflow (&ctx, 1))
-                                       break;
-                               token = read32 (ip + 1);
+                               do_load_function_ptr (&ctx, read32 (ip + 1), TRUE);
                                ip += 5;
-                               if (stack_top (&ctx)->stype != TYPE_COMPLEX)
-                                       ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid argument to ldvirtftn at 0x%04x", ip_offset));
-                               stack_top (&ctx)->stype = TYPE_PTR;
                                break;
+
                        case CEE_UNUSED56:
                                ++ip;
                                break;
@@ -3762,24 +4918,21 @@ mono_method_verify (MonoMethod *method, int level)
                                break;
 
                        case CEE_LOCALLOC:
-                               if (ctx.eval.size != 1)
-                                       ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Stack must have only size item in localloc at 0x%04x", ip_offset));
-                               if (stack_top (&ctx)->stype != TYPE_I4 && stack_top (&ctx)->stype != TYPE_PTR)
-                                       ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid argument to localloc at 0x%04x", ip_offset));
-                               stack_top (&ctx)->stype = TYPE_COMPLEX;
+                               do_localloc (&ctx);
                                ++ip;
                                break;
+
                        case CEE_UNUSED57:
                                ++ip;
                                break;
                        case CEE_ENDFILTER:
-                               if (ctx.eval.size != 1)
-                                       ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Stack must have only filter result in endfilter at 0x%04x", ip_offset));
+                               do_endfilter (&ctx);
+                               start = 1;
                                ++ip;
                                break;
                        case CEE_UNALIGNED_:
                                prefix |= PREFIX_UNALIGNED;
-                               ++ip;
+                               ip += 2;
                                break;
                        case CEE_VOLATILE_:
                                prefix |= PREFIX_VOLATILE;
@@ -3791,17 +4944,23 @@ mono_method_verify (MonoMethod *method, int level)
                                if (ip < end && (*ip != CEE_CALL && *ip != CEE_CALLI && *ip != CEE_CALLVIRT))
                                        ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("tail prefix must be used only with call opcodes at 0x%04x", ip_offset));
                                break;
+
                        case CEE_INITOBJ:
-                               if (!check_underflow (&ctx, 1))
-                                       break;
-                               token = read32 (ip + 1);
+                               do_initobj (&ctx, read32 (ip + 1));
                                ip += 5;
-                               stack_pop (&ctx);
                                break;
+
                        case CEE_CONSTRAINED_:
-                               token = read32 (ip + 1);
+                               ctx.constrained_type = get_boxable_mono_type (&ctx, read32 (ip + 1), "constrained.");
+                               prefix |= PREFIX_CONSTRAINED;
                                ip += 5;
                                break;
+       
+                       case CEE_READONLY_:
+                               prefix |= PREFIX_READONLY;
+                               ip++;
+                               break;
+
                        case CEE_CPBLK:
                                if (!check_underflow (&ctx, 3))
                                        break;
@@ -3816,25 +4975,25 @@ mono_method_verify (MonoMethod *method, int level)
                                ip += 2;
                                break;
                        case CEE_RETHROW:
+                               if (!is_correct_rethrow (ctx.header, ip_offset))
+                                       ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("rethrow must be used inside a catch handler at 0x%04x", ctx.ip_offset));
+                               ctx.eval.size = 0;
                                ++ip;
                                break;
                        case CEE_UNUSED:
                                ++ip;
                                break;
+
                        case CEE_SIZEOF:
-                               if (!check_overflow (&ctx))
-                                       break;
-                               token = read32 (ip + 1);
+                               do_sizeof (&ctx, read32 (ip + 1));
                                ip += 5;
-                               stack_top (&ctx)->type = &mono_defaults.uint32_class->byval_arg;
-                               stack_top (&ctx)->stype = TYPE_I4;
-                               ctx.eval.size++;
                                break;
+
                        case CEE_REFANYTYPE:
-                               if (!check_underflow (&ctx, 1))
-                                       break;
+                               do_refanytype (&ctx);
                                ++ip;
                                break;
+
                        case CEE_UNUSED53:
                        case CEE_UNUSED54:
                        case CEE_UNUSED55:
@@ -3843,6 +5002,21 @@ mono_method_verify (MonoMethod *method, int level)
                                break;
                        }
                }
+
+               /*TODO we can fast detect a forward branch or exception block targeting code after prefix, we should fail fast*/
+               if (prefix) {
+                       if (!ctx.prefix_set) //first prefix
+                               ctx.code [ctx.ip_offset].flags |= IL_CODE_FLAG_SEEN;
+                       ctx.prefix_set |= prefix;
+                       prefix = 0;
+               } else {
+                       ctx.code [ctx.ip_offset].flags |= IL_CODE_FLAG_SEEN;
+                       if (ctx.prefix_set & PREFIX_CONSTRAINED)
+                               ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid instruction after constrained prefix at 0x%04x", ctx.ip_offset));
+                       if (ctx.prefix_set & PREFIX_READONLY)
+                               ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid instruction after readonly prefix at 0x%04x", ctx.ip_offset));
+                       ctx.prefix_set = prefix = 0;
+               }
        }
        /*
         * if ip != end we overflowed: mark as error.
@@ -3851,7 +5025,21 @@ mono_method_verify (MonoMethod *method, int level)
                ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Run ahead of method code at 0x%04x", ip_offset));
        }
 
-invalid_cil:
+       /*We should guard against the last decoded opcode, otherwise we might add errors that doesn't make sense.*/
+       for (i = 0; i < ctx.code_size && i < ip_offset; ++i) {
+               if (ctx.code [i].flags & IL_CODE_FLAG_WAS_TARGET) {
+                       if (!(ctx.code [i].flags & IL_CODE_FLAG_SEEN))
+                               ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Branch or exception block target middle of intruction at 0x%04x", i));
+
+                       if (ctx.code [i].flags & IL_CODE_DELEGATE_SEQUENCE)
+                               CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Branch to delegate code sequence at 0x%04x", i));
+               }
+               if ((ctx.code [i].flags & IL_CODE_LDFTN_DELEGATE_NONFINAL_VIRTUAL) && ctx.has_this_store)
+                       CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Invalid ldftn with virtual function in method with stdarg 0 at  0x%04x", i));
+
+               if ((ctx.code [i].flags & IL_CODE_CALL_NONFINAL_VIRTUAL) && ctx.has_this_store)
+                       CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Invalid call to a non-final virtual function in method with stdarg.0 or ldarga.0 at  0x%04x", i));
+       }
 
        if (ctx.code) {
                for (i = 0; i < ctx.header->code_size; ++i) {
@@ -3860,6 +5048,10 @@ invalid_cil:
                }
        }
 
+       for (tmp = ctx.funptrs; tmp; tmp = tmp->next)
+               g_free (tmp->data);
+       g_slist_free (ctx.funptrs);
+
        if (ctx.eval.stack)
                g_free (ctx.eval.stack);
        if (ctx.code)
@@ -3870,510 +5062,11 @@ invalid_cil:
        return ctx.list;
 }
 
-typedef struct {
-       const char *name;
-       guint64 offset;
-} FieldDesc;
-
-typedef struct {
-       const char *name;
-       const FieldDesc *fields;
-} ClassDesc;
-
-static const FieldDesc 
-typebuilder_fields[] = {
-       {"tname", G_STRUCT_OFFSET (MonoReflectionTypeBuilder, name)},
-       {"nspace", G_STRUCT_OFFSET (MonoReflectionTypeBuilder, nspace)},
-       {"parent", G_STRUCT_OFFSET (MonoReflectionTypeBuilder, parent)},
-       {"interfaces", G_STRUCT_OFFSET (MonoReflectionTypeBuilder, interfaces)},
-       {"methods", G_STRUCT_OFFSET (MonoReflectionTypeBuilder, methods)},
-       {"properties", G_STRUCT_OFFSET (MonoReflectionTypeBuilder, properties)},
-       {"fields", G_STRUCT_OFFSET (MonoReflectionTypeBuilder, fields)},
-       {"attrs", G_STRUCT_OFFSET (MonoReflectionTypeBuilder, attrs)},
-       {"table_idx", G_STRUCT_OFFSET (MonoReflectionTypeBuilder, table_idx)},
-       {NULL, 0}
-};
-
-static const FieldDesc 
-modulebuilder_fields[] = {
-       {"types", G_STRUCT_OFFSET (MonoReflectionModuleBuilder, types)},
-       {"cattrs", G_STRUCT_OFFSET (MonoReflectionModuleBuilder, cattrs)},
-       {"guid", G_STRUCT_OFFSET (MonoReflectionModuleBuilder, guid)},
-       {"table_idx", G_STRUCT_OFFSET (MonoReflectionModuleBuilder, table_idx)},
-       {NULL, 0}
-};
-
-static const FieldDesc 
-assemblybuilder_fields[] = {
-       {"entry_point", G_STRUCT_OFFSET (MonoReflectionAssemblyBuilder, entry_point)},
-       {"modules", G_STRUCT_OFFSET (MonoReflectionAssemblyBuilder, modules)},
-       {"name", G_STRUCT_OFFSET (MonoReflectionAssemblyBuilder, name)},
-       {"resources", G_STRUCT_OFFSET (MonoReflectionAssemblyBuilder, resources)},
-       {"version", G_STRUCT_OFFSET (MonoReflectionAssemblyBuilder, version)},
-       {"culture", G_STRUCT_OFFSET (MonoReflectionAssemblyBuilder, culture)},
-       {NULL, 0}
-};
-
-static const FieldDesc 
-ctorbuilder_fields[] = {
-       {"ilgen", G_STRUCT_OFFSET (MonoReflectionCtorBuilder, ilgen)},
-       {"parameters", G_STRUCT_OFFSET (MonoReflectionCtorBuilder, parameters)},
-       {"attrs", G_STRUCT_OFFSET (MonoReflectionCtorBuilder, attrs)},
-       {"iattrs", G_STRUCT_OFFSET (MonoReflectionCtorBuilder, iattrs)},
-       {"table_idx", G_STRUCT_OFFSET (MonoReflectionCtorBuilder, table_idx)},
-       {"call_conv", G_STRUCT_OFFSET (MonoReflectionCtorBuilder, call_conv)},
-       {"type", G_STRUCT_OFFSET (MonoReflectionCtorBuilder, type)},
-       {NULL, 0}
-};
-
-static const FieldDesc 
-methodbuilder_fields[] = {
-       {"mhandle", G_STRUCT_OFFSET (MonoReflectionMethodBuilder, mhandle)},
-       {"rtype", G_STRUCT_OFFSET (MonoReflectionMethodBuilder, rtype)},
-       {"parameters", G_STRUCT_OFFSET (MonoReflectionMethodBuilder, parameters)},
-       {"attrs", G_STRUCT_OFFSET (MonoReflectionMethodBuilder, attrs)},
-       {"iattrs", G_STRUCT_OFFSET (MonoReflectionMethodBuilder, iattrs)},
-       {"name", G_STRUCT_OFFSET (MonoReflectionMethodBuilder, name)},
-       {"table_idx", G_STRUCT_OFFSET (MonoReflectionMethodBuilder, table_idx)},
-       {"code", G_STRUCT_OFFSET (MonoReflectionMethodBuilder, code)},
-       {"ilgen", G_STRUCT_OFFSET (MonoReflectionMethodBuilder, ilgen)},
-       {"type", G_STRUCT_OFFSET (MonoReflectionMethodBuilder, type)},
-       {"pinfo", G_STRUCT_OFFSET (MonoReflectionMethodBuilder, pinfo)},
-       {"pi_dll", G_STRUCT_OFFSET (MonoReflectionMethodBuilder, dll)},
-       {"pi_entry", G_STRUCT_OFFSET (MonoReflectionMethodBuilder, dllentry)},
-       {"charset", G_STRUCT_OFFSET (MonoReflectionMethodBuilder, charset)},
-       {"extra_flags", G_STRUCT_OFFSET (MonoReflectionMethodBuilder, extra_flags)},
-       {"native_cc", G_STRUCT_OFFSET (MonoReflectionMethodBuilder, native_cc)},
-       {"call_conv", G_STRUCT_OFFSET (MonoReflectionMethodBuilder, call_conv)},
-       {NULL, 0}
-};
-
-static const FieldDesc 
-fieldbuilder_fields[] = {
-       {"attrs", G_STRUCT_OFFSET (MonoReflectionFieldBuilder, attrs)},
-       {"type", G_STRUCT_OFFSET (MonoReflectionFieldBuilder, type)},
-       {"name", G_STRUCT_OFFSET (MonoReflectionFieldBuilder, name)},
-       {"def_value", G_STRUCT_OFFSET (MonoReflectionFieldBuilder, def_value)},
-       {"offset", G_STRUCT_OFFSET (MonoReflectionFieldBuilder, offset)},
-       {"table_idx", G_STRUCT_OFFSET (MonoReflectionFieldBuilder, table_idx)},
-       {NULL, 0}
-};
-
-static const FieldDesc 
-propertybuilder_fields[] = {
-       {"attrs", G_STRUCT_OFFSET (MonoReflectionPropertyBuilder, attrs)},
-       {"name", G_STRUCT_OFFSET (MonoReflectionPropertyBuilder, name)},
-       {"type", G_STRUCT_OFFSET (MonoReflectionPropertyBuilder, type)},
-       {"parameters", G_STRUCT_OFFSET (MonoReflectionPropertyBuilder, parameters)},
-       {"def_value", G_STRUCT_OFFSET (MonoReflectionPropertyBuilder, def_value)},
-       {"set_method", G_STRUCT_OFFSET (MonoReflectionPropertyBuilder, set_method)},
-       {"get_method", G_STRUCT_OFFSET (MonoReflectionPropertyBuilder, get_method)},
-       {"table_idx", G_STRUCT_OFFSET (MonoReflectionPropertyBuilder, table_idx)},
-       {NULL, 0}
-};
-
-static const FieldDesc 
-ilgenerator_fields[] = {
-       {"code", G_STRUCT_OFFSET (MonoReflectionILGen, code)},
-       {"code_len", G_STRUCT_OFFSET (MonoReflectionILGen, code_len)},
-       {"max_stack", G_STRUCT_OFFSET (MonoReflectionILGen, max_stack)},
-       {"cur_stack", G_STRUCT_OFFSET (MonoReflectionILGen, cur_stack)},
-       {"locals", G_STRUCT_OFFSET (MonoReflectionILGen, locals)},
-       {"ex_handlers", G_STRUCT_OFFSET (MonoReflectionILGen, ex_handlers)},
-       {NULL, 0}
-};
-
-static const FieldDesc 
-ilexinfo_fields[] = {
-       {"handlers", G_STRUCT_OFFSET (MonoILExceptionInfo, handlers)},
-       {"start", G_STRUCT_OFFSET (MonoILExceptionInfo, start)},
-       {"len", G_STRUCT_OFFSET (MonoILExceptionInfo, len)},
-       {"end", G_STRUCT_OFFSET (MonoILExceptionInfo, label)},
-       {NULL, 0}
-};
-
-static const FieldDesc 
-ilexblock_fields[] = {
-       {"extype", G_STRUCT_OFFSET (MonoILExceptionBlock, extype)},
-       {"type", G_STRUCT_OFFSET (MonoILExceptionBlock, type)},
-       {"start", G_STRUCT_OFFSET (MonoILExceptionBlock, start)},
-       {"len", G_STRUCT_OFFSET (MonoILExceptionBlock, len)},
-       {"filter_offset", G_STRUCT_OFFSET (MonoILExceptionBlock, filter_offset)},
-       {NULL, 0}
-};
-
-static const ClassDesc
-emit_classes_to_check [] = {
-       {"TypeBuilder", typebuilder_fields},
-       {"ModuleBuilder", modulebuilder_fields},
-       {"AssemblyBuilder", assemblybuilder_fields},
-       {"ConstructorBuilder", ctorbuilder_fields},
-       {"MethodBuilder", methodbuilder_fields},
-       {"FieldBuilder", fieldbuilder_fields},
-       {"PropertyBuilder", propertybuilder_fields},
-       {"ILGenerator", ilgenerator_fields},
-       {"ILExceptionBlock", ilexblock_fields},
-       {"ILExceptionInfo", ilexinfo_fields},
-       {NULL, NULL}
-};
-
-static const FieldDesc 
-monoevent_fields[] = {
-       {"klass", G_STRUCT_OFFSET (MonoReflectionEvent, klass)},
-       {"handle", G_STRUCT_OFFSET (MonoReflectionEvent, event)},
-       {NULL, 0}
-};
-
-static const FieldDesc 
-monoproperty_fields[] = {
-       {"klass", G_STRUCT_OFFSET (MonoReflectionProperty, klass)},
-       {"prop", G_STRUCT_OFFSET (MonoReflectionProperty, property)},
-       {NULL, 0}
-};
-
-static const FieldDesc 
-monofield_fields[] = {
-       {"klass", G_STRUCT_OFFSET (MonoReflectionField, klass)},
-       {"fhandle", G_STRUCT_OFFSET (MonoReflectionField, field)},
-       {NULL, 0}
-};
-
-static const FieldDesc 
-monomethodinfo_fields[] = {
-       {"parent", G_STRUCT_OFFSET (MonoMethodInfo, parent)},
-       {"ret", G_STRUCT_OFFSET (MonoMethodInfo, ret)},
-       {"attrs", G_STRUCT_OFFSET (MonoMethodInfo, attrs)},
-       {"iattrs", G_STRUCT_OFFSET (MonoMethodInfo, implattrs)},
-       {NULL, 0}
-};
-
-static const FieldDesc 
-monopropertyinfo_fields[] = {
-       {"parent", G_STRUCT_OFFSET (MonoPropertyInfo, parent)},
-       {"name", G_STRUCT_OFFSET (MonoPropertyInfo, name)},
-       {"get_method", G_STRUCT_OFFSET (MonoPropertyInfo, get)},
-       {"set_method", G_STRUCT_OFFSET (MonoPropertyInfo, set)},
-       {"attrs", G_STRUCT_OFFSET (MonoPropertyInfo, attrs)},
-       {NULL, 0}
-};
-
-static const FieldDesc 
-monomethod_fields[] = {
-       {"mhandle", G_STRUCT_OFFSET (MonoReflectionMethod, method)},
-       {NULL, 0}
-};
-
-static const FieldDesc 
-monocmethod_fields[] = {
-       {"mhandle", G_STRUCT_OFFSET (MonoReflectionMethod, method)},
-       {NULL, 0}
-};
-
-static const FieldDesc 
-pinfo_fields[] = {
-       {"ClassImpl", G_STRUCT_OFFSET (MonoReflectionParameter, ClassImpl)},
-       {"DefaultValueImpl", G_STRUCT_OFFSET (MonoReflectionParameter, DefaultValueImpl)},
-       {"MemberImpl", G_STRUCT_OFFSET (MonoReflectionParameter, MemberImpl)},
-       {"NameImpl", G_STRUCT_OFFSET (MonoReflectionParameter, NameImpl)},
-       {"PositionImpl", G_STRUCT_OFFSET (MonoReflectionParameter, PositionImpl)},
-       {"AttrsImpl", G_STRUCT_OFFSET (MonoReflectionParameter, AttrsImpl)},
-       {NULL, 0}
-};
-
-static const ClassDesc
-reflection_classes_to_check [] = {
-       {"MonoEvent", monoevent_fields},
-       {"MonoProperty", monoproperty_fields},
-       {"MonoField", monofield_fields},
-       {"MonoMethodInfo", monomethodinfo_fields},
-       {"MonoPropertyInfo", monopropertyinfo_fields},
-       {"MonoMethod", monomethod_fields},
-       {"MonoCMethod", monocmethod_fields},
-       {"ParameterInfo", pinfo_fields},
-       {NULL, NULL}
-};
-
-static FieldDesc 
-enuminfo_fields[] = {
-       {"utype", G_STRUCT_OFFSET (MonoEnumInfo, utype)},
-       {"values", G_STRUCT_OFFSET (MonoEnumInfo, values)},
-       {"names", G_STRUCT_OFFSET (MonoEnumInfo, names)},
-       {NULL, 0}
-};
-
-static FieldDesc 
-delegate_fields[] = {
-       {"target_type", G_STRUCT_OFFSET (MonoDelegate, target_type)},
-       {"m_target", G_STRUCT_OFFSET (MonoDelegate, target)},
-       {"method_name", G_STRUCT_OFFSET (MonoDelegate, method_name)},
-       {"method_ptr", G_STRUCT_OFFSET (MonoDelegate, method_ptr)},
-       {"delegate_trampoline", G_STRUCT_OFFSET (MonoDelegate, delegate_trampoline)},
-       {"method_info", G_STRUCT_OFFSET (MonoDelegate, method_info)},
-       {NULL, 0}
-};
-
-static FieldDesc 
-multicast_delegate_fields[] = {
-       {"prev", G_STRUCT_OFFSET (MonoMulticastDelegate, prev)},
-       {NULL, 0}
-};
-
-static FieldDesc 
-async_result_fields[] = {
-       {"async_state", G_STRUCT_OFFSET (MonoAsyncResult, async_state)},
-       {"handle", G_STRUCT_OFFSET (MonoAsyncResult, handle)},
-       {"async_delegate", G_STRUCT_OFFSET (MonoAsyncResult, async_delegate)},
-       {"data", G_STRUCT_OFFSET (MonoAsyncResult, data)},
-       {"sync_completed", G_STRUCT_OFFSET (MonoAsyncResult, sync_completed)},
-       {"completed", G_STRUCT_OFFSET (MonoAsyncResult, completed)},
-       {"endinvoke_called", G_STRUCT_OFFSET (MonoAsyncResult, endinvoke_called)},
-       {"async_callback", G_STRUCT_OFFSET (MonoAsyncResult, async_callback)},
-       {NULL, 0}
-};
-
-static FieldDesc 
-exception_fields[] = {
-       {"trace_ips", G_STRUCT_OFFSET (MonoException, trace_ips)},
-       {"inner_exception", G_STRUCT_OFFSET (MonoException, inner_ex)},
-       {"message", G_STRUCT_OFFSET (MonoException, message)},
-       {"help_link", G_STRUCT_OFFSET (MonoException, help_link)},
-       {"class_name", G_STRUCT_OFFSET (MonoException, class_name)},
-       {"stack_trace", G_STRUCT_OFFSET (MonoException, stack_trace)},
-       {"remote_stack_trace", G_STRUCT_OFFSET (MonoException, remote_stack_trace)},
-       {"remote_stack_index", G_STRUCT_OFFSET (MonoException, remote_stack_index)},
-       {"hresult", G_STRUCT_OFFSET (MonoException, hresult)},
-       {"source", G_STRUCT_OFFSET (MonoException, source)},
-       {NULL, 0}
-};
-
-static const ClassDesc
-system_classes_to_check [] = {
-       {"Exception", exception_fields},
-       {"MonoEnumInfo", enuminfo_fields},
-       {"Delegate", delegate_fields},
-       {"MulticastDelegate", multicast_delegate_fields},
-       {NULL, NULL}
-};
-
-static FieldDesc 
-stack_frame_fields [] = {
-       {"ilOffset", G_STRUCT_OFFSET (MonoStackFrame, il_offset)},
-       {"nativeOffset", G_STRUCT_OFFSET (MonoStackFrame, native_offset)},
-       {"methodBase", G_STRUCT_OFFSET (MonoStackFrame, method)},
-       {"fileName", G_STRUCT_OFFSET (MonoStackFrame, filename)},
-       {"lineNumber", G_STRUCT_OFFSET (MonoStackFrame, line)},
-       {"columnNumber", G_STRUCT_OFFSET (MonoStackFrame, column)},
-       {NULL, 0}
-};
-
-static const ClassDesc
-system_diagnostics_classes_to_check [] = {
-       {"StackFrame", stack_frame_fields},
-       {NULL, NULL}
-};
-
-static FieldDesc 
-mono_method_message_fields[] = {
-       {"method", G_STRUCT_OFFSET (MonoMethodMessage, method)},
-       {"args", G_STRUCT_OFFSET (MonoMethodMessage, args)},
-       {"names", G_STRUCT_OFFSET (MonoMethodMessage, names)},
-       {"arg_types", G_STRUCT_OFFSET (MonoMethodMessage, arg_types)},
-       {"ctx", G_STRUCT_OFFSET (MonoMethodMessage, ctx)},
-       {"rval", G_STRUCT_OFFSET (MonoMethodMessage, rval)},
-       {"exc", G_STRUCT_OFFSET (MonoMethodMessage, exc)},
-       {NULL, 0}
-};
-
-static const ClassDesc
-messaging_classes_to_check [] = {
-       {"AsyncResult", async_result_fields},
-       {"MonoMethodMessage", mono_method_message_fields},
-       {NULL, NULL}
-};
-
-static FieldDesc 
-transparent_proxy_fields[] = {
-       {"_rp", G_STRUCT_OFFSET (MonoTransparentProxy, rp)},
-       {"_class", G_STRUCT_OFFSET (MonoTransparentProxy, remote_class)},
-       {NULL, 0}
-};
-
-static FieldDesc 
-real_proxy_fields[] = {
-       {"class_to_proxy", G_STRUCT_OFFSET (MonoRealProxy, class_to_proxy)},
-       {NULL, 0}
-};
-
-static const ClassDesc
-proxy_classes_to_check [] = {
-       {"TransparentProxy", transparent_proxy_fields},
-       {"RealProxy", real_proxy_fields},
-       {NULL, NULL}
-};
-
-static FieldDesc 
-wait_handle_fields[] = {
-       {"os_handle", G_STRUCT_OFFSET (MonoWaitHandle, handle)},
-       {"disposed", G_STRUCT_OFFSET (MonoWaitHandle, disposed)},
-       {NULL, 0}
-};
-
-static FieldDesc 
-thread_fields[] = {
-       {"system_thread_handle", G_STRUCT_OFFSET (MonoThread, handle)},
-       {"threadpool_thread", G_STRUCT_OFFSET (MonoThread, threadpool_thread)},
-       {"state", G_STRUCT_OFFSET (MonoThread, state)},
-       {"abort_exc", G_STRUCT_OFFSET (MonoThread, abort_exc)},
-       {"abort_state", G_STRUCT_OFFSET (MonoThread, abort_state)},
-       {"thread_id", G_STRUCT_OFFSET (MonoThread, tid)},
-       {NULL, 0}
-};
-
-static const ClassDesc
-threading_classes_to_check [] = {
-       {"Thread", thread_fields},
-       {"WaitHandle", wait_handle_fields},
-       {NULL, NULL}
-};
-
-static const FieldDesc
-cinfo_fields[] = {
-       {"datetime_format", G_STRUCT_OFFSET (MonoCultureInfo, datetime_format)},
-       {"number_format", G_STRUCT_OFFSET (MonoCultureInfo, number_format)},
-       {"textinfo", G_STRUCT_OFFSET (MonoCultureInfo, textinfo)},
-       {"name", G_STRUCT_OFFSET (MonoCultureInfo, name)},
-       {"displayname", G_STRUCT_OFFSET (MonoCultureInfo, displayname)},
-       {"englishname", G_STRUCT_OFFSET (MonoCultureInfo, englishname)},
-       {"nativename", G_STRUCT_OFFSET (MonoCultureInfo, nativename)},
-       {"iso3lang", G_STRUCT_OFFSET (MonoCultureInfo, iso3lang)},
-       {"iso2lang", G_STRUCT_OFFSET (MonoCultureInfo, iso2lang)},
-       {"icu_name", G_STRUCT_OFFSET (MonoCultureInfo, icu_name)},
-       {"win3lang", G_STRUCT_OFFSET (MonoCultureInfo, win3lang)},
-       {"compareinfo", G_STRUCT_OFFSET (MonoCultureInfo, compareinfo)},
-       {NULL, 0}
-};
-
-static const FieldDesc
-dtfinfo_fields[] = {
-       {"amDesignator", G_STRUCT_OFFSET (MonoDateTimeFormatInfo, AMDesignator)},
-       {"pmDesignator", G_STRUCT_OFFSET (MonoDateTimeFormatInfo, PMDesignator)},
-       {"dayNames", G_STRUCT_OFFSET (MonoDateTimeFormatInfo, DayNames)},
-       {"monthNames", G_STRUCT_OFFSET (MonoDateTimeFormatInfo, MonthNames)},
-       {NULL, 0}
-};
-
-static const FieldDesc
-nfinfo_fields[] = {
-       {"decimalFormats", G_STRUCT_OFFSET (MonoNumberFormatInfo, decimalFormats)},
-       {"currencySymbol", G_STRUCT_OFFSET (MonoNumberFormatInfo, currencySymbol)},
-       {"percentSymbol", G_STRUCT_OFFSET (MonoNumberFormatInfo, percentSymbol)},
-       {"positiveSign", G_STRUCT_OFFSET (MonoNumberFormatInfo, positiveSign)},
-       {NULL, 0}
-};
-
-static const FieldDesc
-compinfo_fields[] = {
-       {"lcid", G_STRUCT_OFFSET (MonoCompareInfo, lcid)},
-       {"ICU_collator", G_STRUCT_OFFSET (MonoCompareInfo, ICU_collator)},
-       {NULL, 0}
-};
-
-static const FieldDesc
-sortkey_fields[] = {
-       {"str", G_STRUCT_OFFSET (MonoSortKey, str)},
-       {"options", G_STRUCT_OFFSET (MonoSortKey, options)},
-       {"key", G_STRUCT_OFFSET (MonoSortKey, key)},
-       {"lcid", G_STRUCT_OFFSET (MonoSortKey, lcid)},
-       {NULL, 0}
-};
-
-static const ClassDesc
-globalization_classes_to_check [] = {
-       {"CultureInfo", cinfo_fields},
-       {"DateTimeFormatInfo", dtfinfo_fields},
-       {"NumberFormatInfo", nfinfo_fields},
-       {"CompareInfo", compinfo_fields},
-       {"SortKey", sortkey_fields},
-       {NULL, NULL}
-};
-
-static const FieldDesc
-safe_handle_fields[] ={
-       {"handle", G_STRUCT_OFFSET (MonoSafeHandle, handle)},
-       {NULL, 0}
-};
-
-static const ClassDesc interop_classes_to_check [] = {
-       {"SafeHandle", safe_handle_fields},
-       {NULL, NULL}
-};
-
-typedef struct {
-       const char *name;
-       const ClassDesc *types;
-} NameSpaceDesc;
-
-static const NameSpaceDesc
-namespaces_to_check[] = {
-       {"System.Runtime.Remoting.Proxies", proxy_classes_to_check},
-       {"System.Runtime.Remoting.Messaging", messaging_classes_to_check},
-       {"System.Reflection.Emit", emit_classes_to_check},
-       {"System.Reflection", reflection_classes_to_check},
-       {"System.Threading", threading_classes_to_check},
-       {"System.Diagnostics", system_diagnostics_classes_to_check},
-       {"System", system_classes_to_check},
-       {"System.Globalization", globalization_classes_to_check},
-       {"System.Runtime.InteropServices", interop_classes_to_check},
-       {NULL, NULL}
-};
-
-static char*
-check_corlib (MonoImage *corlib)
+char*
+mono_verify_corlib ()
 {
-       MonoClass *klass;
-       MonoClassField *field;
-       const FieldDesc *fdesc;
-       const ClassDesc *cdesc;
-       const NameSpaceDesc *ndesc;
-       gint struct_offset;
-       GString *result = NULL;
-
-       for (ndesc = namespaces_to_check; ndesc->name; ++ndesc) {
-               for (cdesc = ndesc->types; cdesc->name; ++cdesc) {
-                       klass = mono_class_from_name (corlib, ndesc->name, cdesc->name);
-                       if (!klass) {
-                               if (!result)
-                                       result = g_string_new ("");
-                               g_string_append_printf (result, "Cannot find class %s\n", cdesc->name);
-                               continue;
-                       }
-                       mono_class_init (klass);
-                       /*
-                        * FIXME: we should also check the size of valuetypes, or
-                        * we're going to have trouble when we access them in arrays.
-                        */
-                       if (klass->valuetype)
-                               struct_offset = sizeof (MonoObject);
-                       else
-                               struct_offset = 0;
-                       for (fdesc = cdesc->fields; fdesc->name; ++fdesc) {
-                               field = mono_class_get_field_from_name (klass, fdesc->name);
-                               if (!field || (field->offset != (fdesc->offset + struct_offset))) {
-                                       if (!result)
-                                               result = g_string_new ("");
-                                       g_string_append_printf (result, "field `%s' mismatch in class %s (%ld + %ld != %ld)\n", fdesc->name, cdesc->name, (long) fdesc->offset, (long)struct_offset, (long) (field?field->offset:-1));
-                               }
-                       }
-               }
-       }
-       if (result)
-               return g_string_free (result, FALSE);
+       /* This is a public API function so cannot be removed */
        return NULL;
 }
 
-char*
-mono_verify_corlib () {
-       return check_corlib (mono_defaults.corlib);
-}
-