2008-10-19 Zoltan Varga <vargaz@gmail.com>
[mono.git] / mono / metadata / verify.c
index 87e7a04abe4ebb395a027389a1972cbbb7c1afb7..96771dbd47b72356b4ab56273d4d80fb178acef3 100644 (file)
@@ -1,6 +1,7 @@
 
 #include <mono/metadata/object-internals.h>
 #include <mono/metadata/verify.h>
+#include <mono/metadata/verify-internals.h>
 #include <mono/metadata/opcodes.h>
 #include <mono/metadata/tabledefs.h>
 #include <mono/metadata/reflection.h>
@@ -36,31 +37,50 @@ enum {
 //////////////////////////////////////////////////////////////////
 #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 ADD_VERIFY_INFO(__ctx, __msg, __status)        \
+#define IS_SKIP_VISIBILITY(ctx) (((ctx)->level & MONO_VERIFY_SKIP_VISIBILITY) == MONO_VERIFY_SKIP_VISIBILITY)
+#define IS_REPORT_ALL_ERRORS(ctx) (((ctx)->level & MONO_VERIFY_REPORT_ALL_ERRORS) == MONO_VERIFY_REPORT_ALL_ERRORS)
+#define CLEAR_PREFIX(ctx, prefix) do { (ctx)->prefix_set &= ~(prefix); } while (0)
+#define ADD_VERIFY_INFO(__ctx, __msg, __status, __exception)   \
        do {    \
                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)
 
+//TODO support MONO_VERIFY_REPORT_ALL_ERRORS
 #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); \
+               if ((__ctx)->verifiable || IS_REPORT_ALL_ERRORS (__ctx)) { \
+                       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 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 || IS_REPORT_ALL_ERRORS (__ctx)) { \
+                       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.*/
@@ -81,6 +101,12 @@ enum {
        IL_CODE_CALL_NONFINAL_VIRTUAL = 0x40,
 };
 
+typedef enum {
+       RESULT_VALID,
+       RESULT_UNVERIFIABLE,
+       RESULT_INVALID
+} verify_result_t;
+
 typedef struct {
        MonoType *type;
        int stype;
@@ -109,6 +135,8 @@ typedef struct {
        GSList *list;
        /*Allocated fnptr MonoType that should be freed by us.*/
        GSList *funptrs;
+       /*Type dup'ed exception types from catch blocks.*/
+       GSList *exception_types;
 
        int num_locals;
        MonoType **locals;
@@ -127,14 +155,35 @@ typedef struct {
        /*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;
+
+       /*This flag is used to control if the contructor of the parent class has been called.
+        *If the this pointer is pushed on the eval stack and it's a reference type constructor and
+        * super_ctor_called is false, the uninitialized flag is set on the pushed value.
+        * 
+        * Poping an uninitialized this ptr from the eval stack is an unverifiable operation unless
+        * the safe variant is used. Only a few opcodes can use it : dup, pop, ldfld, stfld and call to a constructor.
+        */
+       gboolean super_ctor_called;
+
+       guint32 prefix_set;
+       gboolean has_flags;
+       MonoType *constrained_type;
 } VerifyContext;
 
 static void
-merge_stacks (VerifyContext *ctx, ILCodeDesc *from, ILCodeDesc *to, int start, gboolean external);
+merge_stacks (VerifyContext *ctx, ILCodeDesc *from, ILCodeDesc *to, gboolean start, gboolean external);
 
 static int
 get_stack_type (MonoType *type);
 
+static gboolean
+mono_delegate_signature_equal (MonoMethodSignature *sig1, MonoMethodSignature *sig2);
+
+static gboolean
+mono_class_is_valid_generic_instantiation (VerifyContext *ctx, MonoClass *klass);
+
+static gboolean
+mono_method_is_valid_generic_instantiation (VerifyContext *ctx, MonoMethod *method);
 //////////////////////////////////////////////////////////////////
 
 
@@ -176,6 +225,8 @@ enum {
        /**Signals that this is a boxed value type*/
        BOXED_MASK = 0x1000,
 
+       /*This is an unitialized this ref*/
+       UNINIT_THIS_MASK = 0x2000,
 };
 
 static const char* const
@@ -193,8 +244,8 @@ enum {
        PREFIX_UNALIGNED = 1,
        PREFIX_VOLATILE  = 2,
        PREFIX_TAIL      = 4,
-       PREFIX_ADDR_MASK = 3,
-       PREFIX_FUNC_MASK = 4
+       PREFIX_CONSTRAINED = 8,
+       PREFIX_READONLY = 16
 };
 //////////////////////////////////////////////////////////////////
 
@@ -203,12 +254,14 @@ enum {
 #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.
@@ -216,6 +269,8 @@ enum {
 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);
 }
 
@@ -223,6 +278,7 @@ 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);
@@ -244,6 +300,29 @@ mono_type_is_enum_type (MonoType *type)
        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);
+}
+
+/*
+ * Returns TURE if @type is VAR or MVAR
+ */
+static gboolean
+mono_type_is_generic_argument (MonoType *type)
+{
+       return type->type == MONO_TYPE_VAR || type->type == MONO_TYPE_MVAR;
+}
+
 /*
  * mono_type_get_underlying_type_any:
  * 
@@ -278,6 +357,436 @@ mono_method_is_constructor (MonoMethod *method)
                        !strcmp (".ctor", method->name));
 }
 
+static gboolean
+mono_class_has_default_constructor (MonoClass *klass)
+{
+       MonoMethod *method;
+       int i;
+
+       mono_class_setup_methods (klass);
+
+       for (i = 0; i < klass->method.count; ++i) {
+               method = klass->methods [i];
+               if (mono_method_is_constructor (method) &&
+                       mono_method_signature (method)->param_count == 0 &&
+                       (method->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK) == METHOD_ATTRIBUTE_PUBLIC)
+                       return TRUE;
+       }
+       return FALSE;
+}
+
+static gboolean
+mono_class_interface_implements_interface (MonoClass *candidate, MonoClass *iface)
+{
+       int i;
+       if (candidate == iface)
+               return TRUE;
+       for (i = 0; i < candidate->interface_count; ++i) {
+               if (candidate->interfaces [i] == iface || mono_class_interface_implements_interface (candidate->interfaces [i], iface))
+                       return TRUE;
+       }
+       return FALSE;
+}
+
+/*
+ * Test if @candidate is a subtype of @target using the minimal possible information
+ * TODO move the code for non finished TypeBuilders to here.
+ */
+static gboolean
+mono_class_is_constraint_compatible (MonoClass *candidate, MonoClass *target)
+{
+       if (candidate == target)
+               return TRUE;
+       if (target == mono_defaults.object_class)
+                       return TRUE;
+
+       //setup_supertypes don't mono_class_init anything
+       mono_class_setup_supertypes (candidate);
+       mono_class_setup_supertypes (target);
+
+       if (mono_class_has_parent (candidate, target))
+               return TRUE;
+
+       //if target is not a supertype it must be an interface
+       if (!MONO_CLASS_IS_INTERFACE (target))
+                       return FALSE;
+
+       if (candidate->image->dynamic && !candidate->wastypebuilder) {
+               MonoReflectionTypeBuilder *tb = candidate->reflection_info;
+               int j;
+               if (tb->interfaces) {
+                       for (j = mono_array_length (tb->interfaces) - 1; j >= 0; --j) {
+                               MonoReflectionType *iface = mono_array_get (tb->interfaces, MonoReflectionType*, j);
+                               MonoClass *ifaceClass = mono_class_from_mono_type (iface->type);
+                               if (mono_class_is_constraint_compatible (ifaceClass, target)) {
+                                       return TRUE;
+                               }
+                       }
+               }
+               return FALSE;
+       }
+       return mono_class_interface_implements_interface (candidate, target);
+}
+
+static gboolean
+is_valid_generic_instantiation (MonoGenericContainer *gc, MonoGenericContext *context, MonoGenericInst *ginst)
+{
+       int i;
+
+       if (ginst->type_argc != gc->type_argc)
+               return FALSE;
+
+       for (i = 0; i < gc->type_argc; ++i) {
+               MonoGenericParam *param = &gc->type_params [i];
+               MonoClass *paramClass;
+               MonoClass **constraints;
+
+               if (!param->constraints && !(param->flags & GENERIC_PARAMETER_ATTRIBUTE_SPECIAL_CONSTRAINTS_MASK))
+                       continue;
+               if (mono_type_is_generic_argument (ginst->type_argv [i]))
+                       continue; //it's not our job to validate type variables
+
+               paramClass = mono_class_from_mono_type (ginst->type_argv [i]);
+
+               if (paramClass->exception_type != MONO_EXCEPTION_NONE)
+                       return FALSE;
+
+               /*it's not safe to call mono_class_init from here*/
+               if (paramClass->generic_class && !paramClass->inited) {
+                       if (!mono_class_is_valid_generic_instantiation (NULL, paramClass))
+                               return FALSE;
+               }
+
+               if ((param->flags & GENERIC_PARAMETER_ATTRIBUTE_VALUE_TYPE_CONSTRAINT) && (!paramClass->valuetype || mono_class_is_nullable (paramClass)))
+                       return FALSE;
+
+               if ((param->flags & GENERIC_PARAMETER_ATTRIBUTE_REFERENCE_TYPE_CONSTRAINT) && paramClass->valuetype)
+                       return FALSE;
+
+               if ((param->flags & GENERIC_PARAMETER_ATTRIBUTE_CONSTRUCTOR_CONSTRAINT) && !paramClass->valuetype && !mono_class_has_default_constructor (paramClass))
+                       return FALSE;
+
+               if (!param->constraints)
+                       continue;
+
+               for (constraints = param->constraints; *constraints; ++constraints) {
+                       MonoClass *ctr = *constraints;
+                       MonoType *inflated;
+
+                       inflated = mono_class_inflate_generic_type (&ctr->byval_arg, context);
+                       ctr = mono_class_from_mono_type (inflated);
+                       mono_metadata_free_type (inflated);
+
+                       if (!mono_class_is_constraint_compatible (paramClass, ctr))
+                               return FALSE;
+               }
+       }
+       return TRUE;
+}
+
+/*
+ * Return true if @candidate is constraint compatible with @target.
+ * 
+ * This means that @candidate constraints are a super set of @target constaints
+ */
+static gboolean
+mono_generic_param_is_constraint_compatible (MonoGenericParam *target, MonoGenericParam *candidate, MonoGenericContext *context)
+{
+       int tmask = target->flags & GENERIC_PARAMETER_ATTRIBUTE_SPECIAL_CONSTRAINTS_MASK;
+       int cmask = candidate->flags & GENERIC_PARAMETER_ATTRIBUTE_SPECIAL_CONSTRAINTS_MASK;    
+       if ((tmask & cmask) != tmask)
+               return FALSE;
+
+       if (target->constraints) {
+               MonoClass **target_class, **candidate_class;
+               if (!candidate->constraints)
+                       return FALSE;
+               for (target_class = target->constraints; *target_class; ++target_class) {
+                       MonoType *inflated = mono_class_inflate_generic_type (&(*target_class)->byval_arg, context);
+                       MonoClass *tc = mono_class_from_mono_type (inflated);
+                       mono_metadata_free_type (inflated);
+
+                       for (candidate_class = candidate->constraints; *candidate_class; ++candidate_class) {
+                               MonoClass *cc;
+
+                               inflated = mono_class_inflate_generic_type (&(*candidate_class)->byval_arg, context);
+                               cc = mono_class_from_mono_type (inflated);
+                               mono_metadata_free_type (inflated);
+
+                               if (mono_class_is_assignable_from (tc, cc))
+                                       break;
+                       }
+                       if (!*candidate_class)
+                               return FALSE;
+               }
+       }
+       return TRUE;
+}
+
+static MonoGenericParam*
+verifier_get_generic_param_from_type (VerifyContext *ctx, MonoType *type)
+{
+       MonoGenericContainer *gc;
+       MonoMethod *method = ctx->method;
+       int num;
+
+       num = type->data.generic_param->num;
+
+       if (type->type == MONO_TYPE_VAR) {
+               MonoClass *gtd = method->klass;
+               if (gtd->generic_class)
+                       gtd = gtd->generic_class->container_class;
+               gc = gtd->generic_container;
+       } else { //MVAR
+               MonoMethod *gmd = method;
+               if (method->is_inflated)
+                       gmd = ((MonoMethodInflated*)method)->declaring;
+               gc = mono_method_get_generic_container (gmd);
+       }
+       if (!gc)
+               return FALSE;
+       return &gc->type_params [num];
+}
+
+
+
+/*
+ * Verify if @type is valid for the given @ctx verification context.
+ * this function checks for VAR and MVAR types that are invalid under the current verifier,
+ * This means that it either 
+ */
+static gboolean
+is_valid_type_in_context (VerifyContext *ctx, MonoType *type)
+{
+       if (mono_type_is_generic_argument (type) && !ctx->generic_context)
+               return FALSE;
+       if (type->type == MONO_TYPE_VAR) {
+               if (!ctx->generic_context->class_inst)
+                       return FALSE;
+               if (type->data.generic_param->num >= ctx->generic_context->class_inst->type_argc)
+                       return FALSE;
+       } else if (type->type == MONO_TYPE_MVAR) {
+               if (!ctx->generic_context->method_inst)
+                       return FALSE;
+               if (type->data.generic_param->num >= ctx->generic_context->method_inst->type_argc)
+                       return FALSE;
+       }
+       return TRUE;
+}
+
+static gboolean
+is_valid_generic_instantiation_in_context (VerifyContext *ctx, MonoGenericInst *ginst)
+{
+       int i;
+       for (i = 0; i < ginst->type_argc; ++i) {
+               MonoType *type = ginst->type_argv [i];
+               if (!is_valid_type_in_context (ctx, type))
+                       return FALSE;
+       }
+       return TRUE;
+}
+
+static gboolean
+generic_arguments_respect_constraints (VerifyContext *ctx, MonoGenericContainer *gc, MonoGenericContext *context, MonoGenericInst *ginst)
+{
+       int i;
+       for (i = 0; i < ginst->type_argc; ++i) {
+               MonoType *type = ginst->type_argv [i];
+               MonoGenericParam *target = &gc->type_params [i];
+               MonoGenericParam *candidate;
+
+               if (!mono_type_is_generic_argument (type))
+                       continue;
+
+               if (!is_valid_type_in_context (ctx, type))
+                       return FALSE;
+
+               candidate = verifier_get_generic_param_from_type (ctx, type);
+
+               if (!mono_generic_param_is_constraint_compatible (target, candidate, context))
+                       return FALSE;
+       }
+       return TRUE;
+}
+
+static gboolean
+mono_method_repect_method_constraints (VerifyContext *ctx, MonoMethod *method)
+{
+       MonoMethodInflated *gmethod = (MonoMethodInflated *)method;
+       MonoGenericInst *ginst = gmethod->context.method_inst;
+       MonoGenericContainer *gc = mono_method_get_generic_container (gmethod->declaring);
+       return !gc || generic_arguments_respect_constraints (ctx, gc, &gmethod->context, ginst);
+}
+
+static gboolean
+mono_class_repect_method_constraints (VerifyContext *ctx, MonoClass *klass)
+{
+       MonoGenericClass *gklass = klass->generic_class;
+       MonoGenericInst *ginst = gklass->context.class_inst;
+       MonoGenericContainer *gc = gklass->container_class->generic_container;
+       return !gc || generic_arguments_respect_constraints (ctx, gc, &gklass->context, ginst);
+}
+
+static gboolean
+mono_method_is_valid_generic_instantiation (VerifyContext *ctx, MonoMethod *method)
+{
+       MonoMethodInflated *gmethod = (MonoMethodInflated *)method;
+       MonoGenericInst *ginst = gmethod->context.method_inst;
+       MonoGenericContainer *gc = mono_method_get_generic_container (gmethod->declaring);
+       if (!gc) /*non-generic inflated method - it's part of a generic type  */
+               return TRUE;
+       if (ctx && !is_valid_generic_instantiation_in_context (ctx, ginst))
+               return FALSE;
+       return is_valid_generic_instantiation (gc, &gmethod->context, ginst);
+
+}
+
+static gboolean
+mono_class_is_valid_generic_instantiation (VerifyContext *ctx, MonoClass *klass)
+{
+       MonoGenericClass *gklass = klass->generic_class;
+       MonoGenericInst *ginst = gklass->context.class_inst;
+       MonoGenericContainer *gc = gklass->container_class->generic_container;
+       if (ctx && !is_valid_generic_instantiation_in_context (ctx, ginst))
+               return FALSE;
+       return is_valid_generic_instantiation (gc, &gklass->context, ginst);
+}
+
+static gboolean
+mono_type_is_valid_in_context (VerifyContext *ctx, MonoType *type)
+{
+       MonoClass *klass;
+
+       if (!is_valid_type_in_context (ctx, type)) {
+               char *str = mono_type_full_name (type);
+               ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid generic type (%s%s) (argument out of range or %s is not generic) at 0x%04x",
+                       type->type == MONO_TYPE_VAR ? "!" : "!!",
+                       str,
+                       type->type == MONO_TYPE_VAR ? "class" : "method",
+                       ctx->ip_offset),
+                       MONO_EXCEPTION_BAD_IMAGE);              
+               g_free (str);
+               return FALSE;
+       }
+
+       klass = mono_class_from_mono_type (type);
+       mono_class_init (klass);
+       if (mono_loader_get_last_error () || klass->exception_type != MONO_EXCEPTION_NONE) {
+               if (klass->generic_class && !mono_class_is_valid_generic_instantiation (NULL, klass))
+                       ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid generic instantiation of type %s.%s at 0x%04x", klass->name_space, klass->name, ctx->ip_offset), MONO_EXCEPTION_TYPE_LOAD);
+               else
+                       ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Could not load type %s.%s at 0x%04x", klass->name_space, klass->name, ctx->ip_offset), MONO_EXCEPTION_TYPE_LOAD);
+               return FALSE;
+       }
+
+       if (klass->exception_type != MONO_EXCEPTION_NONE || (klass->generic_class && klass->generic_class->container_class->exception_type != MONO_EXCEPTION_NONE)) {
+               ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Could not load type %s.%s at 0x%04x", klass->name_space, klass->name, ctx->ip_offset), MONO_EXCEPTION_TYPE_LOAD);
+               return FALSE;
+       }
+
+       if (!klass->generic_class)
+               return TRUE;
+
+       if (!mono_class_is_valid_generic_instantiation (ctx, klass)) {
+               ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid generic type instantiation of type %s.%s at 0x%04x", klass->name_space, klass->name, ctx->ip_offset), MONO_EXCEPTION_TYPE_LOAD);
+               return FALSE;
+       }
+
+       if (!mono_class_repect_method_constraints (ctx, klass)) {
+               ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid generic type instantiation of type %s.%s (generic args don't respect target's constraints) at 0x%04x", klass->name_space, klass->name, ctx->ip_offset), MONO_EXCEPTION_TYPE_LOAD);
+               return FALSE;
+       }
+
+       return TRUE;
+}
+
+static verify_result_t
+mono_method_is_valid_in_context (VerifyContext *ctx, MonoMethod *method)
+{
+       if (!mono_type_is_valid_in_context (ctx, &method->klass->byval_arg))
+               return RESULT_INVALID;
+
+       if (!method->is_inflated)
+               return RESULT_VALID;
+
+       if (!mono_method_is_valid_generic_instantiation (ctx, method)) {
+               ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid generic method instantiation of method %s.%s::%s at 0x%04x", method->klass->name_space, method->klass->name, method->name, ctx->ip_offset), MONO_EXCEPTION_UNVERIFIABLE_IL);
+               return RESULT_INVALID;
+       }
+
+       if (!mono_method_repect_method_constraints (ctx, method)) {
+               CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid generic method instantiation of method %s.%s::%s (generic args don't respect target's constraints) at 0x%04x", method->klass->name_space, method->klass->name, method->name, ctx->ip_offset));
+               return RESULT_UNVERIFIABLE;
+       }
+       return RESULT_VALID;
+}
+
+       
+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;
+       }
+
+       if (!mono_type_is_valid_in_context (ctx, &field->parent->byval_arg))
+               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;
+       }
+       
+       if (mono_method_is_valid_in_context (ctx, method) == RESULT_INVALID)
+               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;
+       }
+
+       if (!mono_type_is_valid_in_context (ctx, type))
+               return NULL;
+
+       return type;
+}
+
 
 /* stack_slot_get_type:
  * 
@@ -318,7 +827,7 @@ stack_slot_is_managed_pointer (ILStackDesc *value)
  * 
  * Returns TRUE is @value is a managed mutability pointer.
  */
-static gboolean
+static G_GNUC_UNUSED gboolean
 stack_slot_is_managed_mutability_pointer (ILStackDesc *value)
 {
        return (value->stype & CMMP_MASK) == CMMP_MASK;
@@ -1349,6 +1858,7 @@ check_overflow (VerifyContext *ctx)
        return 1;
 }
 
+/*This reject out PTR, FNPTR and TYPEDBYREF*/
 static gboolean
 check_unmanaged_pointer (VerifyContext *ctx, ILStackDesc *value)
 {
@@ -1359,6 +1869,7 @@ check_unmanaged_pointer (VerifyContext *ctx, ILStackDesc *value)
        return 1;
 }
 
+/*TODO verify if MONO_TYPE_TYPEDBYREF is not allowed here as well.*/
 static gboolean
 check_unverifiable_type (VerifyContext *ctx, MonoType *type)
 {
@@ -1388,19 +1899,27 @@ stack_push_val (VerifyContext *ctx, int stype, MonoType *type)
 static ILStackDesc *
 stack_pop (VerifyContext *ctx)
 {
-       return ctx->eval.stack + --ctx->eval.size;
+       ILStackDesc *ret = ctx->eval.stack + --ctx->eval.size;
+       if ((ret->stype & UNINIT_THIS_MASK) == UNINIT_THIS_MASK)
+               CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Found use of uninitialized 'this ptr' ref at 0x%04x", ctx->ip_offset));
+       return ret;
 }
 
-static inline ILStackDesc *
-stack_top (VerifyContext *ctx)
+/* This function allows to safely pop an unititialized this ptr from
+ * the eval stack without marking the method as unverifiable. 
+ */
+static ILStackDesc *
+stack_pop_safe (VerifyContext *ctx)
 {
-       return ctx->eval.stack + (ctx->eval.size - 1);
+       return ctx->eval.stack + --ctx->eval.size;
 }
 
-static inline ILStackDesc *
-stack_get (VerifyContext *ctx, int distance)
+static ILStackDesc *
+stack_push_stack_val (VerifyContext *ctx, ILStackDesc *value)
 {
-       return ctx->eval.stack + (ctx->eval.size - distance - 1);
+       ILStackDesc *top = stack_push (ctx);
+       copy_stack_value (top, value);
+       return top;
 }
 
 /* Returns the MonoType associated with the token, or NULL if it is invalid.
@@ -1408,33 +1927,26 @@ 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;
-       if (!IS_TYPE_DEF_OR_REF_OR_SPEC (token) || !token_bounds_check (ctx->image, token)) {
-               ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid type token %x at 0x%04x", token, ctx->ip_offset));
-               return NULL;
-       }
-       
-       type = mono_type_get_full (ctx->image, token, ctx->generic_context);
 
-       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 at 0x%04x", ctx->ip_offset));
+               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 at 0x%04x", ctx->ip_offset));
+               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;
@@ -1828,174 +2340,14 @@ handle_enum:
 static void
 init_stack_with_value_at_exception_boundary (VerifyContext *ctx, ILCodeDesc *code, MonoClass *klass)
 {
+       MonoType *type = mono_class_inflate_generic_type (&klass->byval_arg, ctx->generic_context);
        stack_init (ctx, code);
-       set_stack_value (ctx, code->stack, &klass->byval_arg, FALSE);
+       set_stack_value (ctx, code->stack, type, FALSE);
+       ctx->exception_types = g_slist_prepend (ctx->exception_types, type);
        code->size = 1;
        code->flags |= IL_CODE_FLAG_WAS_TARGET;
 }
 
-/* Generics validation stuff, should be moved to another metadata/? file */
-static gboolean
-mono_is_generic_type_compatible (MonoType *target, MonoType *candidate)
-{
-       if (target->byref != candidate->byref)
-               return FALSE;
-
-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 (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 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 different 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
@@ -2081,25 +2433,33 @@ handle_enum:
        }
 
        case MONO_TYPE_GENERICINST: {
-               MonoGenericClass *left;
-               MonoGenericClass *right;
+               MonoClass *target_klass;
+               MonoClass *candidate_klass;
                if (mono_type_is_enum_type (target)) {
                        target = mono_type_get_underlying_type_any (target);
                        goto handle_enum;
                }
-
-               if (candidate->type != MONO_TYPE_GENERICINST)
-                       return mono_class_is_assignable_from (mono_class_from_mono_type (target), mono_class_from_mono_type (candidate));
-               left = target->data.generic_class;
-               right = candidate->data.generic_class;
-
-               return mono_is_generic_instance_compatible (left, right, right);
+               target_klass = mono_class_from_mono_type (target);
+               candidate_klass = mono_class_from_mono_type (candidate);
+               if (mono_class_is_nullable (target_klass)) {
+                       if (!mono_class_is_nullable (candidate_klass))
+                               return FALSE;
+                       return target_klass == candidate_klass;
+               }
+               
+               return mono_class_is_assignable_from (target_klass, candidate_klass);
        }
 
        case MONO_TYPE_STRING:
                return candidate->type == MONO_TYPE_STRING;
 
        case MONO_TYPE_CLASS:
+               /*
+                * VAR / MVAR compatibility must be checked by verify_stack_type_compatibility
+                * to take boxing status into account.
+                */
+               if (mono_type_is_generic_argument (original_candidate))
+                       return FALSE;
                /* 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.
                 */ 
@@ -2114,8 +2474,8 @@ handle_enum:
                if (candidate->type != MONO_TYPE_SZARRAY)
                        return FALSE;
 
-               left = target->data.klass;
-               right = candidate->data.klass;
+               left = target->data.array->eklass;
+               right = candidate->data.array->eklass;
                return mono_class_is_assignable_from(left, right);
        }
 
@@ -2162,6 +2522,30 @@ verify_type_compatibility (VerifyContext *ctx, MonoType *target, MonoType *candi
        return verify_type_compatibility_full (ctx, target, candidate, FALSE);
 }
 
+/*
+ * Returns the generic param bound to the context been verified.
+ * 
+ */
+static MonoGenericParam*
+get_generic_param (VerifyContext *ctx, MonoType *param) 
+{
+       guint16 param_num = param->data.generic_param->num;
+       if (param->type == MONO_TYPE_VAR) {
+               if (!ctx->generic_context->class_inst || ctx->generic_context->class_inst->type_argc <= param_num) {
+                       ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid generic type argument %d", param_num));
+                       return NULL;
+               }
+               return ctx->generic_context->class_inst->type_argv [param_num]->data.generic_param;
+       }
+       
+       /*param must be a MVAR */
+       if (!ctx->generic_context->method_inst || ctx->generic_context->method_inst->type_argc <= param_num) {
+               ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid generic method argument %d", param_num));
+               return NULL;
+       }
+       return ctx->generic_context->method_inst->type_argv [param_num]->data.generic_param;
+       
+}
 /*
  * is_compatible_boxed_valuetype:
  * 
@@ -2174,26 +2558,139 @@ verify_type_compatibility (VerifyContext *ctx, MonoType *target, MonoType *candi
  * 
  */
 static gboolean
-is_compatible_boxed_valuetype (MonoType *type, MonoType *candidate, ILStackDesc *stack, gboolean type_must_be_object)
+is_compatible_boxed_valuetype (VerifyContext *ctx, MonoType *type, MonoType *candidate, ILStackDesc *stack, gboolean type_must_be_object)
 {
-       if (type_must_be_object && type->type != MONO_TYPE_OBJECT)
-               return FALSE;
+       if (mono_type_is_generic_argument (candidate) && stack_slot_is_boxed_value (stack) && !type->byref) {
+               MonoGenericParam *param = get_generic_param (ctx, candidate);
+               MonoClass **class;
+               for (class = param->constraints; class && *class; ++class) {
+                       if (verify_type_compatibility_full (ctx, type, mono_type_get_type_byval (& (*class)->byval_arg), FALSE))
+                               return TRUE;
+               }
+       }
+       
        if (!type_must_be_object && !MONO_TYPE_IS_REFERENCE (type))
                return FALSE;
-       return !type->byref && mono_class_from_mono_type (candidate)->valuetype && !candidate->byref && stack_slot_is_boxed_value (stack);
+       return !type->byref && !candidate->byref && stack_slot_is_boxed_value (stack);
 }
 
 static int
-verify_stack_type_compatibility (VerifyContext *ctx, MonoType *type, ILStackDesc *stack)
+verify_stack_type_compatibility_full (VerifyContext *ctx, MonoType *type, ILStackDesc *stack, gboolean strict, gboolean drop_byref)
 {
        MonoType *candidate = mono_type_from_stack_slot (stack);
        if (MONO_TYPE_IS_REFERENCE (type) && !type->byref && stack_slot_is_null_literal (stack))
                return TRUE;
 
-       if (is_compatible_boxed_valuetype (type, candidate, stack, TRUE))
+       if (is_compatible_boxed_valuetype (ctx, type, candidate, stack, TRUE))
+               return TRUE;
+
+       if (drop_byref)
+               return verify_type_compatibility_full (ctx, type, mono_type_get_type_byval (candidate), strict);
+
+       return verify_type_compatibility_full (ctx, type, candidate, strict);
+}
+
+static int
+verify_stack_type_compatibility (VerifyContext *ctx, MonoType *type, ILStackDesc *stack)
+{
+       return verify_stack_type_compatibility_full (ctx, type, stack, FALSE, FALSE);
+}
+
+static gboolean
+mono_delegate_type_equal (MonoType *target, MonoType *candidate)
+{
+       if (candidate->byref ^ target->byref)
+               return FALSE;
+
+       switch (target->type) {
+       case MONO_TYPE_VOID:
+       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:
+       case MONO_TYPE_I8:
+       case MONO_TYPE_U8:
+       case MONO_TYPE_R4:
+       case MONO_TYPE_R8:
+       case MONO_TYPE_I:
+       case MONO_TYPE_U:
+       case MONO_TYPE_STRING:
+       case MONO_TYPE_TYPEDBYREF:
+               return candidate->type == target->type;
+
+       case MONO_TYPE_PTR:
+               return mono_delegate_type_equal (target->data.type, candidate->data.type);
+
+       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));
+
+       case MONO_TYPE_GENERICINST: {
+               MonoClass *target_klass;
+               MonoClass *candidate_klass;
+               target_klass = mono_class_from_mono_type (target);
+               candidate_klass = mono_class_from_mono_type (candidate);
+               /*FIXME handle nullables and enum*/
+               return mono_class_is_assignable_from (target_klass, candidate_klass);
+       }
+       case MONO_TYPE_OBJECT:
+               return MONO_TYPE_IS_REFERENCE (candidate);
+
+       case MONO_TYPE_CLASS:
+               if (candidate->type != MONO_TYPE_CLASS)
+                       return FALSE;
+               return mono_class_is_assignable_from(target->data.klass, candidate->data.klass);
+
+       case MONO_TYPE_SZARRAY:
+               if (candidate->type != MONO_TYPE_SZARRAY)
+                       return FALSE;
+               return mono_class_is_assignable_from (target->data.array->eklass, candidate->data.array->eklass);
+
+       case MONO_TYPE_ARRAY:
+               if (candidate->type != MONO_TYPE_ARRAY)
+                       return FALSE;
+               return is_array_type_compatible (target, candidate);
+
+       case MONO_TYPE_VALUETYPE:
+               /*FIXME handle nullables and enum*/
+               return candidate->type == MONO_TYPE_VALUETYPE && target->data.klass == candidate->data.klass;
+
+       case MONO_TYPE_VAR:
+               return candidate->type == MONO_TYPE_VAR && target->data.generic_param->num == candidate->data.generic_param->num; 
+               return FALSE;
+
+       case MONO_TYPE_MVAR:
+               return candidate->type == MONO_TYPE_MVAR && target->data.generic_param->num == candidate->data.generic_param->num;
+               return FALSE;
+
+       default:
+               VERIFIER_DEBUG ( printf ("Unknown type %d. Implement me!\n", target->type); );
+               g_assert_not_reached ();
+               return FALSE;
+       }
+}
+
+static gboolean
+mono_delegate_param_equal (MonoType *delegate, MonoType *method)
+{
+       if (mono_metadata_type_equal_full (delegate, method, TRUE))
+               return TRUE;
+
+       return mono_delegate_type_equal (method, delegate);
+}
+
+static gboolean
+mono_delegate_ret_equal (MonoType *delegate, MonoType *method)
+{
+       if (mono_metadata_type_equal_full (delegate, method, TRUE))
                return TRUE;
 
-       return verify_type_compatibility_full (ctx, type, candidate, FALSE);
+       return mono_delegate_type_equal (delegate, method);
 }
 
 /*
@@ -2209,24 +2706,21 @@ static gboolean
 mono_delegate_signature_equal (MonoMethodSignature *sig1, MonoMethodSignature *sig2)
 {
        int i;
-
-       //FIXME do we need to check for explicit_this?
-       //We don't check for has_this since this is irrelevant for delegate signatures
        if (sig1->param_count != sig2->param_count) 
                return FALSE;
 
-       if (sig1->generic_param_count != sig2->generic_param_count)
+       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_metadata_type_equal_full (p1, p2, TRUE))
+               if (!mono_delegate_param_equal (p1, p2))
                        return FALSE;
        }
 
-       if (!mono_metadata_type_equal_full (sig1->ret, sig2->ret, TRUE))
+       if (!mono_delegate_ret_equal (sig1->ret, sig2->ret))
                return FALSE;
 
        return TRUE;
@@ -2246,7 +2740,7 @@ verify_ldftn_delegate (VerifyContext *ctx, MonoClass *delegate, ILStackDesc *val
         * 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) && !stack_slot_is_boxed_value (value)) {
+       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));
@@ -2280,7 +2774,7 @@ verify_delegate_compatibility (VerifyContext *ctx, MonoClass *delegate, ILStackD
        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 %d", ctx->ip_offset));
+               CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid function pointer parameter for delegate constructor at 0x%04x", ctx->ip_offset));
                return;
        }
        
@@ -2288,7 +2782,7 @@ verify_delegate_compatibility (VerifyContext *ctx, MonoClass *delegate, ILStackD
        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 %d", ctx->ip_offset));
+               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:
@@ -2311,7 +2805,7 @@ verify_delegate_compatibility (VerifyContext *ctx, MonoClass *delegate, ILStackD
        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))
+       if (!verify_stack_type_compatibility (ctx, &method->klass->byval_arg, value) && !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)
@@ -2325,6 +2819,8 @@ verify_delegate_compatibility (VerifyContext *ctx, MonoClass *delegate, ILStackD
 static void
 push_arg (VerifyContext *ctx, unsigned int arg, int take_addr) 
 {
+       ILStackDesc *top;
+
        if (arg >= ctx->max_args) {
                if (take_addr) 
                        ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Method doesn't have argument %d", arg + 1));
@@ -2338,14 +2834,17 @@ push_arg (VerifyContext *ctx, unsigned int arg, int take_addr)
                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))
+               top = stack_push (ctx);
+               if (!set_stack_value (ctx, top, 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;
+                               top->stype |= THIS_POINTER_MASK;
+                       if (mono_method_is_constructor (ctx->method) && !ctx->super_ctor_called && !ctx->method->klass->valuetype)
+                               top->stype |= UNINIT_THIS_MASK;
                }
        } 
 }
@@ -2372,8 +2871,8 @@ store_arg (VerifyContext *ctx, guint32 arg)
 
        if (arg >= ctx->max_args) {
                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);
+               if (check_underflow (ctx, 1))
+                       stack_pop (ctx);
                return;
        }
 
@@ -2412,14 +2911,14 @@ store_local (VerifyContext *ctx, guint32 arg)
 static void
 do_binop (VerifyContext *ctx, unsigned int opcode, const unsigned char table [TYPE_MAX][TYPE_MAX])
 {
-       ILStackDesc *a, *b;
+       ILStackDesc *a, *b, *top;
        int idxa, idxb, complexMerge = 0;
        unsigned char res;
 
        if (!check_underflow (ctx, 2))
                return;
-       a = stack_get (ctx, 1);
-       b = stack_top (ctx);
+       b = stack_pop (ctx);
+       a = stack_pop (ctx);
 
        idxa = stack_slot_get_underlying_type (a);
        if (stack_slot_is_managed_pointer (a)) {
@@ -2440,23 +2939,24 @@ do_binop (VerifyContext *ctx, unsigned int opcode, const unsigned char table [TY
        VERIFIER_DEBUG ( printf ("binop res %d\n", res); );
        VERIFIER_DEBUG ( printf ("idxa %d idxb %d\n", idxa, idxb); );
 
-       ctx->eval.size--;
+       top = stack_push (ctx);
        if (res == TYPE_INV) {
                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)));
+               copy_stack_value (top, a);
                return;
        }
 
        if (res & NON_VERIFIABLE_RESULT) {
                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;
+               res = res & ~NON_VERIFIABLE_RESULT;
        }
 
        if (complexMerge && res == TYPE_PTR) {
                if (complexMerge == 1) 
-                       copy_stack_value (stack_top (ctx), a);
+                       copy_stack_value (top, a);
                else if (complexMerge == 2)
-                       copy_stack_value (stack_top (ctx), b);
+                       copy_stack_value (top, b);
                /*
                 * There is no need to merge the type of two pointers.
                 * The only valid operation is subtraction, that returns a native
@@ -2464,7 +2964,7 @@ do_binop (VerifyContext *ctx, unsigned int opcode, const unsigned char table [TY
                 * This is valid acording to Patition III 1.1.4
                 */
        } else
-               stack_top (ctx)->stype = res;
+               top->stype = res;
        
 }
 
@@ -2498,11 +2998,16 @@ 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", stack_slot_get_name (stack_get (ctx, -1)), 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 (top), ctx->ip_offset));
 
        check_unmanaged_pointer (ctx, top);
 }
 
+static gboolean
+stack_slot_is_complex_type_not_reference_type (ILStackDesc *slot)
+{
+       return stack_slot_get_type (slot) == TYPE_COMPLEX && !MONO_TYPE_IS_REFERENCE (slot->type);
+}
 
 static void
 do_branch_op (VerifyContext *ctx, signed int delta, const unsigned char table [TYPE_MAX][TYPE_MAX])
@@ -2520,7 +3025,7 @@ do_branch_op (VerifyContext *ctx, signed int delta, const unsigned char table [T
        }
 
        switch (is_valid_cmp_branch_instruction (ctx->header, ctx->ip_offset, target)) {
-       case 1:
+       case 1: /*FIXME use constants and not magic numbers.*/
                CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Branch target escapes out of exception block at 0x%04x", ctx->ip_offset));
                break;
        case 2:
@@ -2544,9 +3049,13 @@ do_branch_op (VerifyContext *ctx, signed int delta, const unsigned char table [T
        if (stack_slot_is_managed_pointer (b))
                idxb = TYPE_PTR;
 
-       --idxa;
-       --idxb;
-       res = table [idxa][idxb];
+       if (stack_slot_is_complex_type_not_reference_type (a) || stack_slot_is_complex_type_not_reference_type (b)) {
+               res = TYPE_INV;
+       } else {
+               --idxa;
+               --idxb;
+               res = table [idxa][idxb];
+       }
 
        VERIFIER_DEBUG ( printf ("branch res %d\n", res); );
        VERIFIER_DEBUG ( printf ("idxa %d idxb %d\n", idxa, idxb); );
@@ -2587,9 +3096,13 @@ do_cmp_op (VerifyContext *ctx, const unsigned char table [TYPE_MAX][TYPE_MAX], g
        if (stack_slot_is_managed_pointer (b)) 
                idxb = TYPE_PTR;
 
-       --idxa;
-       --idxb;
-       res = table [idxa][idxb];
+       if (stack_slot_is_complex_type_not_reference_type (a) || stack_slot_is_complex_type_not_reference_type (b)) {
+               res = TYPE_INV;
+       } else {
+               --idxa;
+               --idxb;
+               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", stack_slot_get_name (a), stack_slot_get_name (b), ctx->ip_offset));
@@ -2603,8 +3116,9 @@ do_cmp_op (VerifyContext *ctx, const unsigned char table [TYPE_MAX][TYPE_MAX], g
 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;
@@ -2615,6 +3129,9 @@ do_ret (VerifyContext *ctx)
                        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) {
@@ -2627,8 +3144,6 @@ do_ret (VerifyContext *ctx)
 /*
  * 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 vararg calls
  * TODO handle calling .ctor outside one or calling the .ctor for other class but super  
  */
 static void
@@ -2637,26 +3152,33 @@ 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 && (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 (virtual) {
+               CLEAR_PREFIX (ctx, 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 (virtual && method->klass->valuetype)
-               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));
 
-       if (!virtual && (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;
+       } 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;
@@ -2668,12 +3190,34 @@ do_invoke_method (VerifyContext *ctx, int method_token, gboolean virtual)
                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 %s at 0x%04x", virtual ? "callvirt" : "call",  ctx->ip_offset));
+
+               if ((ctx->prefix_set & PREFIX_TAIL) && stack_slot_is_managed_pointer (value)) {
+                       ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Cannot  pass a byref argument to a tail %s at 0x%04x", virtual ? "callvirt" : "call",  ctx->ip_offset));
+                       return;
+               }
        }
 
        if (sig->hasthis) {
                MonoType *type = &method->klass->byval_arg;
                ILStackDesc copy;
-               value = stack_pop (ctx);
+
+               if (mono_method_is_constructor (method) && !method->klass->valuetype) {
+                       if (!mono_method_is_constructor (ctx->method))
+                               CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot call a constructor outside one at 0x%04x", ctx->ip_offset));
+                       if (method->klass != ctx->method->klass->parent && method->klass != ctx->method->klass)
+                               CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot call a constructor to a type diferent that this or super at 0x%04x", ctx->ip_offset));
+
+                       ctx->super_ctor_called = TRUE;
+                       value = stack_pop_safe (ctx);
+                       if ((value->stype & THIS_POINTER_MASK) != THIS_POINTER_MASK)
+                               CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid 'this ptr' argument for constructor at 0x%04x", ctx->ip_offset));
+               } else {
+                       value = stack_pop (ctx);
+               }
+                       
                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 
@@ -2682,35 +3226,53 @@ do_invoke_method (VerifyContext *ctx, int method_token, gboolean virtual)
 
                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 (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 (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 (!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 (!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 (!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 (ctx, stack_push (ctx), sig->ret, 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;
+                       }
+               }
+       }
+
+       if ((ctx->prefix_set & PREFIX_TAIL)) {
+               if (!mono_delegate_ret_equal (mono_method_signature (ctx->method)->ret, sig->ret))
+                       CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Tail call with incompatible return type at 0x%04x", ctx->ip_offset));
+               if (ctx->header->code [ctx->ip_offset + 5] != CEE_RET)
+                       CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Tail call not followed by ret at 0x%04x", ctx->ip_offset));
        }
 
-       if (sig->ret->type == MONO_TYPE_TYPEDBYREF
-               || sig->ret->byref
-               || (sig->ret->type == MONO_TYPE_VALUETYPE && !strcmp ("System", sig->ret->data.klass->name_space) && !strcmp ("ArgIterator", sig->ret->data.klass->name)))
-               CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Method returns typedbyref, byref or ArgIterator at 0x%04x", ctx->ip_offset));
 }
 
 static void
@@ -2718,12 +3280,11 @@ do_push_static_field (VerifyContext *ctx, int token, gboolean take_addr)
 {
        MonoClassField *field;
        MonoClass *klass;
+       if (!take_addr)
+               CLEAR_PREFIX (ctx, PREFIX_VOLATILE);
 
-       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));
@@ -2734,8 +3295,8 @@ 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 (ctx, stack_push (ctx), field->type, take_addr);
 }
@@ -2745,17 +3306,15 @@ do_store_static_field (VerifyContext *ctx, int token) {
        MonoClassField *field;
        MonoClass *klass;
        ILStackDesc *value;
+       CLEAR_PREFIX (ctx, PREFIX_VOLATILE);
 
        if (!check_underflow (ctx, 1))
                return;
 
        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));
@@ -2767,33 +3326,27 @@ 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_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;
+       gboolean is_pointer;
 
-       /*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));
+       /*must be a reference type, a managed pointer, an unamanaged pointer, or a valuetype*/
+       if (!(field = verifier_load_field (ctx, token, &klass, opcode)))
                return FALSE;
-       }
 
        *ret_field = field;
+       //the value on stack is going to be used as a pointer
+       is_pointer = stack_slot_get_type (obj) == TYPE_PTR || (stack_slot_get_type (obj) == TYPE_NATIVE_INT && !get_stack_type (&field->parent->byval_arg));
 
        if (field->type->type == MONO_TYPE_TYPEDBYREF) {
                ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Typedbyref field is an unverfiable type at 0x%04x", ctx->ip_offset));
@@ -2803,7 +3356,13 @@ 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 (stack_slot_get_underlying_type (obj) == TYPE_COMPLEX) {
+       if (is_pointer) {
+               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));
+
+               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);
+       } else {
                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));
 
@@ -2811,18 +3370,12 @@ check_is_valid_type_for_field_ops (VerifyContext *ctx, int token, ILStackDesc *o
                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)))
+               if (!stack_slot_is_null_literal (obj) && !verify_stack_type_compatibility_full (ctx, &field->parent->byval_arg, obj, FALSE, TRUE))
                        CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Type at stack is not compatible to reference the 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 (!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 (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));
+               if (!IS_SKIP_VISIBILITY (ctx) && !mono_method_can_access_field_full (ctx->method, field, mono_class_from_mono_type (obj->type)))
+                       CODE_NOT_VERIFIABLE2 (ctx, g_strdup_printf ("Type at stack is not accessible at 0x%04x", ctx->ip_offset), MONO_EXCEPTION_FIELD_ACCESS);
+       } 
 
        check_unmanaged_pointer (ctx, obj);
        return TRUE;
@@ -2834,11 +3387,14 @@ do_push_field (VerifyContext *ctx, int token, gboolean take_addr)
        ILStackDesc *obj;
        MonoClassField *field;
 
+       if (!take_addr)
+               CLEAR_PREFIX (ctx, PREFIX_UNALIGNED | PREFIX_VOLATILE);
+
        if (!check_underflow (ctx, 1))
                return;
-       obj = stack_pop (ctx);
+       obj = stack_pop_safe (ctx);
 
-       if (!check_is_valid_type_for_field_ops (ctx, token, obj, &field))
+       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))
@@ -2856,14 +3412,15 @@ do_store_field (VerifyContext *ctx, int token)
 {
        ILStackDesc *value, *obj;
        MonoClassField *field;
+       CLEAR_PREFIX (ctx, PREFIX_UNALIGNED | PREFIX_VOLATILE);
 
        if (!check_underflow (ctx, 2))
                return;
 
        value = stack_pop (ctx);
-       obj = stack_pop (ctx);
+       obj = stack_pop_safe (ctx);
 
-       if (!check_is_valid_type_for_field_ops (ctx, token, obj, &field))
+       if (!check_is_valid_type_for_field_ops (ctx, token, obj, &field, "stfld"))
                return;
 
        if (!verify_stack_type_compatibility (ctx, field->type, value))
@@ -2875,7 +3432,7 @@ static void
 do_box_value (VerifyContext *ctx, int klass_token)
 {
        ILStackDesc *value;
-       MonoType *type = get_boxable_mono_type (ctx, klass_token);
+       MonoType *type = get_boxable_mono_type (ctx, klass_token, "box");
 
        if (!type)
                return;
@@ -2883,15 +3440,14 @@ do_box_value (VerifyContext *ctx, int klass_token)
        if (!check_underflow (ctx, 1))
                return;
 
-       value = stack_top (ctx);
+       value = stack_pop (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;
+               stack_push_stack_val (ctx, 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));
@@ -2903,7 +3459,7 @@ static void
 do_unbox_value (VerifyContext *ctx, int klass_token)
 {
        ILStackDesc *value;
-       MonoType *type = get_boxable_mono_type (ctx, klass_token);
+       MonoType *type = get_boxable_mono_type (ctx, klass_token, "unbox");
 
        if (!type)
                return;
@@ -2929,7 +3485,7 @@ static void
 do_unbox_any (VerifyContext *ctx, int klass_token)
 {
        ILStackDesc *value;
-       MonoType *type = get_boxable_mono_type (ctx, klass_token);
+       MonoType *type = get_boxable_mono_type (ctx, klass_token, "unbox.any");
 
        if (!type)
                return;
@@ -2953,7 +3509,7 @@ do_unary_math_op (VerifyContext *ctx, int op)
        ILStackDesc *value;
        if (!check_underflow (ctx, 1))
                return;
-       value = stack_top (ctx);
+       value = stack_pop (ctx);
        switch (stack_slot_get_type (value)) {
        case TYPE_I4:
        case TYPE_I8:
@@ -2968,6 +3524,7 @@ do_unary_math_op (VerifyContext *ctx, int op)
        default:
                CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid type at stack for unary not at 0x%04x", ctx->ip_offset));
        }
+       stack_push_stack_val (ctx, value);
 }
 
 static void
@@ -2985,7 +3542,7 @@ do_conversion (VerifyContext *ctx, int kind)
        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));
+               CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid type (%s) at stack for conversion operation. Numeric type expected at 0x%04x", stack_slot_get_name (value), ctx->ip_offset));
        }
 
        switch (kind) {
@@ -3019,6 +3576,15 @@ do_load_token (VerifyContext *ctx, int token)
                ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid token 0x%x for ldtoken at 0x%04x", token, ctx->ip_offset));
                return;
        }
+       if (handle_class == mono_defaults.typehandle_class) {
+               mono_type_is_valid_in_context (ctx, (MonoType*)handle);
+       } else if (handle_class == mono_defaults.methodhandle_class) {
+               mono_method_is_valid_in_context (ctx, (MonoMethod*)handle);             
+       } else if (handle_class == mono_defaults.fieldhandle_class) {
+               mono_type_is_valid_in_context (ctx, &((MonoClassField*)handle)->parent->byval_arg);                             
+       } else {
+               ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid ldtoken type %x at 0x%04x", token, ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE);
+       }
        stack_push_val (ctx, TYPE_COMPLEX, mono_class_get_type (handle_class));
 }
 
@@ -3026,7 +3592,8 @@ static void
 do_ldobj_value (VerifyContext *ctx, int token) 
 {
        ILStackDesc *value;
-       MonoType *type = get_boxable_mono_type (ctx, token);
+       MonoType *type = get_boxable_mono_type (ctx, token, "ldobj");
+       CLEAR_PREFIX (ctx, PREFIX_UNALIGNED | PREFIX_VOLATILE);
 
        if (!type)
                return;
@@ -3056,7 +3623,9 @@ static void
 do_stobj (VerifyContext *ctx, int token) 
 {
        ILStackDesc *dest, *src;
-       MonoType *type = get_boxable_mono_type (ctx, token);
+       MonoType *type = get_boxable_mono_type (ctx, token, "stobj");
+       CLEAR_PREFIX (ctx, PREFIX_UNALIGNED | PREFIX_VOLATILE);
+
        if (!type)
                return;
 
@@ -3066,9 +3635,15 @@ do_stobj (VerifyContext *ctx, int token)
        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 (stack_slot_is_boxed_value (src) && !MONO_TYPE_IS_REFERENCE (src->type) && !MONO_TYPE_IS_REFERENCE (type))
+               CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use stobj with a boxed source value that is not a reference type 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));
 
@@ -3080,7 +3655,7 @@ static void
 do_cpobj (VerifyContext *ctx, int token)
 {
        ILStackDesc *dest, *src;
-       MonoType *type = get_boxable_mono_type (ctx, token);
+       MonoType *type = get_boxable_mono_type (ctx, token, "cpobj");
        if (!type)
                return;
 
@@ -3096,6 +3671,9 @@ do_cpobj (VerifyContext *ctx, int token)
        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));
 
@@ -3107,7 +3685,7 @@ static void
 do_initobj (VerifyContext *ctx, int token)
 {
        ILStackDesc *obj;
-       MonoType *stack, *type = get_boxable_mono_type (ctx, token);
+       MonoType *stack, *type = get_boxable_mono_type (ctx, token, "initobj");
        if (!type)
                return;
 
@@ -3119,6 +3697,9 @@ do_initobj (VerifyContext *ctx, int token)
        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)) 
@@ -3136,13 +3717,11 @@ do_newobj (VerifyContext *ctx, int token)
        ILStackDesc *value;
        int i;
        MonoMethodSignature *sig;
-       MonoMethod *method = mono_get_method_full (ctx->image, token, NULL, ctx->generic_context);
+       MonoMethod *method;
        gboolean is_delegate = FALSE;
 
-       if (!method) {
-               ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Constructor 0x%08x not found at 0x%04x", token, ctx->ip_offset));
+       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));
@@ -3152,9 +3731,10 @@ do_newobj (VerifyContext *ctx, int token)
        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 (ctx->method, method))
-               CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Constructor not visible 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;
@@ -3177,6 +3757,9 @@ do_newobj (VerifyContext *ctx, int token)
                        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));
                }
        }
 
@@ -3185,23 +3768,20 @@ do_newobj (VerifyContext *ctx, int token)
 }
 
 static void
-do_cast (VerifyContext *ctx, int token) {
+do_cast (VerifyContext *ctx, int token, const char *opcode) {
        ILStackDesc *value;
        MonoType *type;
        gboolean is_boxed;
+       gboolean do_box;
 
        if (!check_underflow (ctx, 1))
                return;
 
-       type = mono_type_get_full (ctx->image, token, ctx->generic_context);
-
-       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;
-       }
 
        if (type->byref) {
-               ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid castclass type at 0x%04x",  ctx->ip_offset));
+               ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid %s type at 0x%04x", opcode, ctx->ip_offset));
                return;
        }
 
@@ -3209,18 +3789,19 @@ do_cast (VerifyContext *ctx, int token) {
        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 checkcast at 0x%04x", ctx->ip_offset));
+               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 checkast at 0x%04x", ctx->ip_offset));
+               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 checkast at 0x%04x", ctx->ip_offset));
+               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 ? BOXED_MASK : 0), type);
+       do_box = is_boxed || mono_type_is_generic_argument(type) || mono_class_from_mono_type (type)->valuetype;
+       stack_push_val (ctx, TYPE_COMPLEX | (do_box ? BOXED_MASK : 0), type);
 }
 
 static MonoType *
@@ -3290,6 +3871,8 @@ static void
 do_load_indirect (VerifyContext *ctx, int opcode)
 {
        ILStackDesc *value;
+       CLEAR_PREFIX (ctx, PREFIX_UNALIGNED | PREFIX_VOLATILE);
+
        if (!check_underflow (ctx, 1))
                return;
        
@@ -3315,6 +3898,8 @@ static void
 do_store_indirect (VerifyContext *ctx, int opcode)
 {
        ILStackDesc *addr, *val;
+       CLEAR_PREFIX (ctx, PREFIX_UNALIGNED | PREFIX_VOLATILE);
+
        if (!check_underflow (ctx, 2))
                return;
 
@@ -3328,6 +3913,11 @@ do_store_indirect (VerifyContext *ctx, int opcode)
                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));
 
@@ -3339,7 +3929,7 @@ static void
 do_newarr (VerifyContext *ctx, int token) 
 {
        ILStackDesc *value;
-       MonoType *type = get_boxable_mono_type (ctx, token);
+       MonoType *type = get_boxable_mono_type (ctx, token, "newarr");
 
        if (!type)
                return;
@@ -3376,8 +3966,8 @@ do_ldlen (VerifyContext *ctx)
 static void
 do_ldelema (VerifyContext *ctx, int klass_token)
 {
-       ILStackDesc *index, *array;
-       MonoType *type = get_boxable_mono_type (ctx, klass_token);
+       ILStackDesc *index, *array, *res;
+       MonoType *type = get_boxable_mono_type (ctx, klass_token, "ldelema");
        gboolean valid; 
 
        if (!type)
@@ -3406,11 +3996,18 @@ do_ldelema (VerifyContext *ctx, int klass_token)
                }
        }
 
-       set_stack_value (ctx, stack_push (ctx), type, TRUE);    
+       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*/
+/*
+ * FIXME handle arrays that are not 0-indexed
+ * FIXME handle readonly prefix and CMMP
+ */
 static void
 do_ldelem (VerifyContext *ctx, int opcode, int token)
 {
@@ -3421,8 +4018,7 @@ do_ldelem (VerifyContext *ctx, int opcode, int token)
                return;
 
        if (opcode == CEE_LDELEM_ANY) {
-               type = mono_type_get_full (ctx->image, token, ctx->generic_context);
-               if (!type) {
+               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;
                }
@@ -3463,7 +4059,9 @@ do_ldelem (VerifyContext *ctx, int opcode, int token)
 #undef IS_ONE_OF2
 }
 
-/*FIXME handle arrays that are not 0-indexed*/
+/*
+ * FIXME handle arrays that are not 0-indexed
+ */
 static void
 do_stelem (VerifyContext *ctx, int opcode, int token)
 {
@@ -3473,8 +4071,7 @@ do_stelem (VerifyContext *ctx, int opcode, int token)
                return;
 
        if (opcode == CEE_STELEM_ANY) {
-               type = mono_type_get_full (ctx->image, token, ctx->generic_context);
-               if (!type) {
+               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;
                }
@@ -3501,12 +4098,16 @@ do_stelem (VerifyContext *ctx, int opcode, int token)
                        }
                }
        }
-
        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));
+       } else if (opcode != CEE_STELEM_REF) {
+               if (!verify_stack_type_compatibility (ctx, type, value))
+                       CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid value on stack for stdelem.X at 0x%04x", ctx->ip_offset));
+
+               if (stack_slot_is_boxed_value (value) && !MONO_TYPE_IS_REFERENCE (value->type) && !MONO_TYPE_IS_REFERENCE (type))
+                       CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use stobj with a boxed source value that is not a reference type at 0x%04x", ctx->ip_offset));
+
        }
 }
 
@@ -3566,6 +4167,7 @@ do_leave (VerifyContext *ctx, int delta)
 
        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));
+       ctx->eval.size = 0;
 }
 
 /* 
@@ -3611,8 +4213,10 @@ do_switch (VerifyContext *ctx, int count, const unsigned char *data)
        for (i = 0; i < count; ++i) {
                int target = base + read32 (data + i * 4);
 
-               if (target < 0 || target >= ctx->code_size)
+               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));
+                       return;
+               }
 
                switch (is_valid_branch_instruction (ctx->header, ctx->ip_offset, target)) {
                case 1:
@@ -3620,7 +4224,7 @@ do_switch (VerifyContext *ctx, int count, const unsigned char *data)
                        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;
+                       return;
                }
                merge_stacks (ctx, &ctx->eval, &ctx->code [target], FALSE, TRUE);
        }
@@ -3639,16 +4243,12 @@ do_load_function_ptr (VerifyContext *ctx, guint32 token, gboolean virtual)
                return;
 
        if (!IS_METHOD_DEF_OR_REF_OR_SPEC (token) || !token_bounds_check (ctx->image, token)) {
-               ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid token %x for ldftn  at 0x%04x", token, ctx->ip_offset));
+               ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid token %x for ldftn  at 0x%04x", token, ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE);
                return;
        }
 
-       method = mono_get_method_full (ctx->image, token, NULL, ctx->generic_context);
-
-       if (!method) {
-               ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Could not resolve ldftn token %x at 0x%04x", token, ctx->ip_offset));
+       if (!(method = verifier_load_method (ctx, token, virtual ? "ldvirtfrn" : "ldftn")))
                return;
-       }
 
        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));
@@ -3661,13 +4261,13 @@ do_load_function_ptr (VerifyContext *ctx, guint32 token, gboolean virtual)
        
                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))
+
+               if (!verify_stack_type_compatibility (ctx, &method->klass->byval_arg, top))
                        CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Unexpected object for ldvirtftn at 0x%04x", ctx->ip_offset));
        }
        
-       if (!mono_method_can_access_method (ctx->method, method))
-               CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Loaded method is not visible for ldftn/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);
 
        top = stack_push_val(ctx, TYPE_PTR, mono_type_create_fnptr_from_mono_method (ctx, method));
        top->method = method;
@@ -3679,16 +4279,12 @@ do_sizeof (VerifyContext *ctx, int token)
        MonoType *type;
 
        if (!IS_TYPE_DEF_OR_REF_OR_SPEC (token) || !token_bounds_check (ctx->image, token)) {
-               ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid type token %x at 0x%04x", token, ctx->ip_offset));
+               ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid type token %x at 0x%04x", token, ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE);
                return;
        }
        
-       type = mono_type_get_full (ctx->image, token, ctx->generic_context);
-
-       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, "sizeof")))
                return;
-       }
 
        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));
@@ -3708,6 +4304,8 @@ do_sizeof (VerifyContext *ctx, int token)
 static void
 do_localloc (VerifyContext *ctx)
 {
+       ILStackDesc *top;
+       
        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;         
@@ -3718,7 +4316,10 @@ do_localloc (VerifyContext *ctx)
                return;
        }
 
-       set_stack_value (ctx, stack_top (ctx), &mono_defaults.int_class->byval_arg, FALSE);
+       /*TODO verify top type*/
+       top = stack_pop (ctx);
+
+       set_stack_value (ctx, stack_push (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));
 }
 
@@ -3726,12 +4327,12 @@ static void
 do_ldstr (VerifyContext *ctx, guint32 token)
 {
        if (mono_metadata_token_code (token) != MONO_TOKEN_STRING) {
-               ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid string token %x at 0x%04x", token, ctx->ip_offset));
+               ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid string token %x at 0x%04x", token, ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE);
                return;
        }
 
        if (mono_metadata_token_index (token) >= ctx->image->heap_us.size) {
-               ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid string index %x at 0x%04x", token, ctx->ip_offset));
+               ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid string index %x at 0x%04x", token, ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE);
                return;
        }
 
@@ -3739,6 +4340,85 @@ do_ldstr (VerifyContext *ctx, guint32 token)
                stack_push_val (ctx, TYPE_COMPLEX,  &mono_defaults.string_class->byval_arg);
 }
 
+static void
+do_refanyval (VerifyContext *ctx, int token)
+{
+       ILStackDesc *top;
+       MonoType *type;
+       if (!check_underflow (ctx, 1))
+               return;
+
+       if (!(type = get_boxable_mono_type (ctx, token, "refanyval")))
+               return;
+
+       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_refanytype (VerifyContext *ctx)
+{
+       ILStackDesc *top;
+
+       if (!check_underflow (ctx, 1))
+               return;
+
+       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 refanytype, but found %s at 0x%04x", stack_slot_get_name (top), ctx->ip_offset));
+
+       set_stack_value (ctx, stack_push (ctx), &mono_defaults.typehandle_class->byval_arg, FALSE);
+
+}
+
+static void
+do_mkrefany (VerifyContext *ctx, int token)
+{
+       ILStackDesc *top;
+       MonoType *type;
+       if (!check_underflow (ctx, 1))
+               return;
+
+       if (!(type = get_boxable_mono_type (ctx, token, "refanyval")))
+               return;
+
+       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 (ctx, stack_push (ctx), &mono_defaults.typed_reference_class->byval_arg, FALSE);
+}
+
+static void
+do_ckfinite (VerifyContext *ctx)
+{
+       ILStackDesc *top;
+       if (!check_underflow (ctx, 1))
+               return;
+
+       top = stack_pop (ctx);
+
+       if (stack_slot_get_underlying_type (top) != TYPE_R8)
+               ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Expected float32 or float64 on stack for ckfinit but found %s at 0x%04x", stack_slot_get_name (top), ctx->ip_offset)); 
+       stack_push_stack_val (ctx, top);
+}
 /*
  * merge_stacks:
  * Merge the stacks and perform compat checks. The merge check if types of @from are mergeable with type of @to 
@@ -3749,7 +4429,7 @@ do_ldstr (VerifyContext *ctx, guint32 token)
  * 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, gboolean external) 
+merge_stacks (VerifyContext *ctx, ILCodeDesc *from, ILCodeDesc *to, gboolean start, gboolean external) 
 {
        int i, j, k;
        stack_init (ctx, to);
@@ -3784,17 +4464,22 @@ merge_stacks (VerifyContext *ctx, ILCodeDesc *from, ILCodeDesc *to, int start, g
                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)) {
+               if (verify_stack_type_compatibility (ctx, old_type, new_slot)) {
                        copy_stack_value (new_slot, old_slot);
                        continue;
                }
 
                // T := S then U = T (old value is compatible with current value, use new)
-               if (verify_type_compatibility (ctx, new_type, old_type)) {
+               if (verify_stack_type_compatibility (ctx, new_type, old_slot)) {
                        copy_stack_value (old_slot, new_slot);
                        continue;
                }
 
+               if (mono_type_is_generic_argument (old_type) || mono_type_is_generic_argument (new_type)) {
+                       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;                        
+               } 
+
                //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
@@ -3820,12 +4505,13 @@ merge_stacks (VerifyContext *ctx, ILCodeDesc *from, ILCodeDesc *to, int start, g
                        //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)) {
+               } else if (is_compatible_boxed_valuetype (ctx,old_type, new_type, new_slot, FALSE) || is_compatible_boxed_valuetype (ctx, new_type, old_type, old_slot, FALSE)) {
                        match_class = mono_defaults.object_class;
                        goto match_found;
                } 
 
                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)); 
+               set_stack_value (ctx, old_slot, &new_class->byval_arg, stack_slot_is_managed_pointer (old_slot));
                goto end_verify;
 
 match_found:
@@ -3933,6 +4619,12 @@ verify_clause_relationship (VerifyContext *ctx, MonoExceptionClause *clause, Mon
                ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Exception clauses overlap"));
 }
 
+#define code_bounds_check(size) \
+       if (ip + size > end) {\
+               ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Code overrun starting with 0x%x at 0x%04x", *ip, ctx.ip_offset)); \
+               break; \
+       } \
+
 /*
  * FIXME: need to distinguish between valid and verifiable.
  * Need to keep track of types on the stack.
@@ -3944,13 +4636,12 @@ mono_method_verify (MonoMethod *method, int level)
        const unsigned char *ip;
        const unsigned char *end;
        int i, n, need_merge = 0, start = 0;
-       guint token, ip_offset = 0, prefix = 0, prefix_list = 0;
+       guint token, ip_offset = 0, prefix = 0;
        MonoGenericContext *generic_context = NULL;
        MonoImage *image;
        VerifyContext ctx;
        GSList *tmp;
-
-       VERIFIER_DEBUG ( printf ("Verify IL for method %s %s %s\n",  method->klass->name,  method->klass->name, method->name); );
+       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))) {
@@ -3959,6 +4650,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"));
@@ -3980,31 +4672,58 @@ mono_method_verify (MonoMethod *method, int level)
        ctx.verifiable = ctx.valid = 1;
        ctx.level = level;
 
-       ctx.code = g_new0 (ILCodeDesc, ctx.header->code_size);
+       ctx.code = g_new (ILCodeDesc, ctx.header->code_size);
        ctx.code_size = ctx.header->code_size;
 
        memset(ctx.code, 0, sizeof (ILCodeDesc) * ctx.header->code_size);
 
 
        ctx.num_locals = ctx.header->num_locals;
-       ctx.locals = ctx.header->locals;
+       ctx.locals = g_memdup (ctx.header->locals, sizeof (MonoType*) * ctx.header->num_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 = g_new (MonoType*, ctx.max_args);
+       if (ctx.signature->hasthis)
                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;
-       }
+       memcpy (ctx.params + ctx.signature->hasthis, ctx.signature->params, sizeof (MonoType *) * ctx.signature->param_count);
 
        if (ctx.signature->is_inflated)
                ctx.generic_context = generic_context = mono_method_get_context (method);
 
+       if (!generic_context && (method->klass->generic_container || method->is_generic)) {
+               if (method->is_generic)
+                       ctx.generic_context = generic_context = &(mono_method_get_generic_container (method)->context);
+               else
+                       ctx.generic_context = generic_context = &method->klass->generic_container->context;
+       }
+
+       for (i = 0; i < ctx.num_locals; ++i)
+               ctx.locals [i] = mono_class_inflate_generic_type (ctx.locals [i], ctx.generic_context);
+       for (i = 0; i < ctx.max_args; ++i)
+               ctx.params [i] = mono_class_inflate_generic_type (ctx.params [i], ctx.generic_context);
        stack_init (&ctx, &ctx.eval);
 
+       for (i = 0; i < ctx.num_locals; ++i) {
+               if (!mono_type_is_valid_in_context (&ctx, ctx.locals [i])) {
+                       /*TODO use the last error message to provide better feedback. */
+                       ADD_VERIFY_ERROR2 (&ctx, g_strdup_printf ("Invalid local variable %d", i), MONO_EXCEPTION_BAD_IMAGE);
+                       break;
+               }
+       }
+
+       for (i = 0; i < ctx.max_args; ++i) {
+               if (!mono_type_is_valid_in_context (&ctx, ctx.params [i])) {
+                       /*TODO use the last error message to provide better feedback. */
+                       ADD_VERIFY_ERROR2 (&ctx, g_strdup_printf ("Invalid parameter %d", i), MONO_EXCEPTION_BAD_IMAGE);
+                       break;
+               }
+       }
+
+       if (!ctx.valid)
+               goto cleanup;
+
        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); );
@@ -4095,14 +4814,6 @@ mono_method_verify (MonoMethod *method, int level)
                start = 0;
 
                /*TODO we can fast detect a forward branch or exception block targeting code after prefix, we should fail fast*/
-               if (prefix) {
-                       prefix_list |= prefix;
-               } else {
-                       prefix_list = 0;
-                       ctx.code [ip_offset].flags |= IL_CODE_FLAG_SEEN;
-               }
-               prefix = 0;
-
 #ifdef MONO_VERIFIER_DEBUG
                {
                        char *discode;
@@ -4131,6 +4842,7 @@ mono_method_verify (MonoMethod *method, int level)
 
                case CEE_LDARG_S:
                case CEE_LDARGA_S:
+                       code_bounds_check (2);
                        push_arg (&ctx, ip [1],  *ip == CEE_LDARGA_S);
                        ip += 2;
                        break;
@@ -4189,7 +4901,7 @@ mono_method_verify (MonoMethod *method, int level)
                case CEE_POP:
                        if (!check_underflow (&ctx, 1))
                                break;
-                       stack_pop (&ctx);
+                       stack_pop_safe (&ctx);
                        ++ip;
                        break;
 
@@ -4217,11 +4929,13 @@ mono_method_verify (MonoMethod *method, int level)
                        break;
 
                case CEE_STLOC_S:
+                       code_bounds_check (2);
                        store_local (&ctx, ip [1]);
                        ip += 2;
                        break;
 
                case CEE_STARG_S:
+                       code_bounds_check (2);
                        store_arg (&ctx, ip [1]);
                        ip += 2;
                        break;
@@ -4242,30 +4956,35 @@ mono_method_verify (MonoMethod *method, int level)
                        break;
 
                case CEE_LDC_I4_S:
+                       code_bounds_check (2);
                        if (check_overflow (&ctx))
                                stack_push_val (&ctx, TYPE_I4, &mono_defaults.int32_class->byval_arg);
                        ip += 2;
                        break;
 
                case CEE_LDC_I4:
+                       code_bounds_check (5);
                        if (check_overflow (&ctx))
                                stack_push_val (&ctx,TYPE_I4, &mono_defaults.int32_class->byval_arg);
                        ip += 5;
                        break;
 
                case CEE_LDC_I8:
+                       code_bounds_check (9);
                        if (check_overflow (&ctx))
                                stack_push_val (&ctx,TYPE_I8, &mono_defaults.int64_class->byval_arg);
                        ip += 9;
                        break;
 
                case CEE_LDC_R4:
+                       code_bounds_check (5);
                        if (check_overflow (&ctx))
                                stack_push_val (&ctx, TYPE_R8, &mono_defaults.double_class->byval_arg);
                        ip += 5;
                        break;
 
                case CEE_LDC_R8:
+                       code_bounds_check (9);
                        if (check_overflow (&ctx))
                                stack_push_val (&ctx, TYPE_R8, &mono_defaults.double_class->byval_arg);
                        ip += 9;
@@ -4279,6 +4998,7 @@ mono_method_verify (MonoMethod *method, int level)
 
                case CEE_BEQ_S:
                case CEE_BNE_UN_S:
+                       code_bounds_check (2);
                        do_branch_op (&ctx, (signed char)ip [1] + 2, cmp_br_eq_op);
                        ip += 2;
                        need_merge = 1;
@@ -4292,6 +5012,7 @@ mono_method_verify (MonoMethod *method, int level)
                case CEE_BGT_UN_S:
                case CEE_BLE_UN_S:
                case CEE_BLT_UN_S:
+                       code_bounds_check (2);
                        do_branch_op (&ctx, (signed char)ip [1] + 2, cmp_br_op);
                        ip += 2;
                        need_merge = 1;
@@ -4299,6 +5020,7 @@ mono_method_verify (MonoMethod *method, int level)
 
                case CEE_BEQ:
                case CEE_BNE_UN:
+                       code_bounds_check (5);
                        do_branch_op (&ctx, (gint32)read32 (ip + 1) + 5, cmp_br_eq_op);
                        ip += 5;
                        need_merge = 1;
@@ -4312,6 +5034,7 @@ mono_method_verify (MonoMethod *method, int level)
                case CEE_BGT_UN:
                case CEE_BLE_UN:
                case CEE_BLT_UN:
+                       code_bounds_check (5);
                        do_branch_op (&ctx, (gint32)read32 (ip + 1) + 5, cmp_br_op);
                        ip += 5;
                        need_merge = 1;
@@ -4319,6 +5042,7 @@ mono_method_verify (MonoMethod *method, int level)
 
                case CEE_LDLOC_S:
                case CEE_LDLOCA_S:
+                       code_bounds_check (2);
                        push_local (&ctx, ip[1], *ip == CEE_LDLOCA_S);
                        ip += 2;
                        break;
@@ -4334,18 +5058,22 @@ mono_method_verify (MonoMethod *method, int level)
                                break;
                        if (!check_overflow (&ctx))
                                break;
-                       top = stack_push (&ctx);
-                       copy_stack_value (top, stack_get (&ctx, 1)); 
+                       top = stack_pop_safe (&ctx);
+                       copy_stack_value (stack_push (&ctx), top); 
+                       copy_stack_value (stack_push (&ctx), top);
                        ++ip;
                        break;
                }
 
                case CEE_JMP:
+                       code_bounds_check (5);
                        if (ctx.eval.size)
                                ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Eval stack must be empty in jmp at 0x%04x", ip_offset));
                        token = read32 (ip + 1);
                        if (in_any_block (ctx.header, ip_offset))
                                ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("jmp cannot escape exception blocks at 0x%04x", ip_offset));
+
+                       CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Intruction jmp is not verifiable at 0x%04x", ctx.ip_offset));
                        /*
                         * FIXME: check signature, retval, arguments etc.
                         */
@@ -4353,18 +5081,23 @@ mono_method_verify (MonoMethod *method, int level)
                        break;
                case CEE_CALL:
                case CEE_CALLVIRT:
+                       code_bounds_check (5);
                        do_invoke_method (&ctx, read32 (ip + 1), *ip == CEE_CALLVIRT);
                        ip += 5;
                        break;
 
                case CEE_CALLI:
+                       code_bounds_check (5);
                        token = read32 (ip + 1);
                        /*
                         * FIXME: check signature, retval, arguments etc.
+                        * FIXME: check requirements for tail call
                         */
+                       CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Intruction calli is not verifiable at 0x%04x", ctx.ip_offset));
                        ip += 5;
                        break;
                case CEE_BR_S:
+                       code_bounds_check (2);
                        do_static_branch (&ctx, (signed char)ip [1] + 2);
                        need_merge = 1;
                        ip += 2;
@@ -4373,12 +5106,14 @@ mono_method_verify (MonoMethod *method, int level)
 
                case CEE_BRFALSE_S:
                case CEE_BRTRUE_S:
+                       code_bounds_check (2);
                        do_boolean_branch_op (&ctx, (signed char)ip [1] + 2);
                        ip += 2;
                        need_merge = 1;
                        break;
 
                case CEE_BR:
+                       code_bounds_check (5);
                        do_static_branch (&ctx, (gint32)read32 (ip + 1) + 5);
                        need_merge = 1;
                        ip += 5;
@@ -4387,13 +5122,17 @@ mono_method_verify (MonoMethod *method, int level)
 
                case CEE_BRFALSE:
                case CEE_BRTRUE:
+                       code_bounds_check (5);
                        do_boolean_branch_op (&ctx, (gint32)read32 (ip + 1) + 5);
                        ip += 5;
                        need_merge = 1;
                        break;
 
                case CEE_SWITCH:
+                       code_bounds_check (5);
                        n = read32 (ip + 1);
+                       code_bounds_check (5 + sizeof (guint32) * n);
+                       
                        do_switch (&ctx, n, (ip + 5));
                        start = 1;
                        ip += 5 + sizeof (guint32) * n;
@@ -4462,28 +5201,33 @@ mono_method_verify (MonoMethod *method, int level)
                        break;
 
                case CEE_CPOBJ:
+                       code_bounds_check (5);
                        do_cpobj (&ctx, read32 (ip + 1));
                        ip += 5;
                        break;
 
                case CEE_LDOBJ:
+                       code_bounds_check (5);
                        do_ldobj_value (&ctx, read32 (ip + 1));
                        ip += 5;
                        break;
 
                case CEE_LDSTR:
+                       code_bounds_check (5);
                        do_ldstr (&ctx, read32 (ip + 1));
                        ip += 5;
                        break;
 
                case CEE_NEWOBJ:
+                       code_bounds_check (5);
                        do_newobj (&ctx, read32 (ip + 1));
                        ip += 5;
                        break;
 
                case CEE_CASTCLASS:
                case CEE_ISINST:
-                       do_cast (&ctx, read32 (ip + 1));
+                       code_bounds_check (5);
+                       do_cast (&ctx, read32 (ip + 1), *ip == CEE_CASTCLASS ? "castclass" : "isinst");
                        ip += 5;
                        break;
 
@@ -4491,7 +5235,9 @@ mono_method_verify (MonoMethod *method, int level)
                case CEE_UNUSED1:
                        ++ip; /* warn, error ? */
                        break;
+
                case CEE_UNBOX:
+                       code_bounds_check (5);
                        do_unbox_value (&ctx, read32 (ip + 1));
                        ip += 5;
                        break;
@@ -4504,27 +5250,32 @@ mono_method_verify (MonoMethod *method, int level)
 
                case CEE_LDFLD:
                case CEE_LDFLDA:
+                       code_bounds_check (5);
                        do_push_field (&ctx, read32 (ip + 1), *ip == CEE_LDFLDA);
                        ip += 5;
                        break;
 
                case CEE_LDSFLD:
                case CEE_LDSFLDA:
+                       code_bounds_check (5);
                        do_push_static_field (&ctx, read32 (ip + 1), *ip == CEE_LDSFLDA);
                        ip += 5;
                        break;
 
                case CEE_STFLD:
+                       code_bounds_check (5);
                        do_store_field (&ctx, read32 (ip + 1));
                        ip += 5;
                        break;
 
                case CEE_STSFLD:
+                       code_bounds_check (5);
                        do_store_static_field (&ctx, read32 (ip + 1));
                        ip += 5;
                        break;
 
                case CEE_STOBJ:
+                       code_bounds_check (5);
                        do_stobj (&ctx, read32 (ip + 1));
                        ip += 5;
                        break;
@@ -4552,11 +5303,13 @@ mono_method_verify (MonoMethod *method, int level)
                        break;
 
                case CEE_BOX:
+                       code_bounds_check (5);
                        do_box_value (&ctx, read32 (ip + 1));
                        ip += 5;
                        break;
 
                case CEE_NEWARR:
+                       code_bounds_check (5);
                        do_newarr (&ctx, read32 (ip + 1));
                        ip += 5;
                        break;
@@ -4567,6 +5320,7 @@ mono_method_verify (MonoMethod *method, int level)
                        break;
 
                case CEE_LDELEMA:
+                       code_bounds_check (5);
                        do_ldelema (&ctx, read32 (ip + 1));
                        ip += 5;
                        break;
@@ -4599,36 +5353,23 @@ mono_method_verify (MonoMethod *method, int level)
                        break;
 
                case CEE_LDELEM_ANY:
+                       code_bounds_check (5);
                        do_ldelem (&ctx, *ip, read32 (ip + 1));
                        ip += 5;
                        break;
 
                case CEE_STELEM_ANY:
+                       code_bounds_check (5);
                        do_stelem (&ctx, *ip, read32 (ip + 1));
                        ip += 5;
                        break;
                        
                case CEE_UNBOX_ANY:
+                       code_bounds_check (5);
                        do_unbox_any (&ctx, read32 (ip + 1));
                        ip += 5;
                        break;
 
-               case CEE_UNUSED5:
-               case CEE_UNUSED6:
-               case CEE_UNUSED7:
-               case CEE_UNUSED8:
-               case CEE_UNUSED9:
-               case CEE_UNUSED10:
-               case CEE_UNUSED11:
-               case CEE_UNUSED12:
-               case CEE_UNUSED13:
-               case CEE_UNUSED14:
-               case CEE_UNUSED15:
-               case CEE_UNUSED16:
-               case CEE_UNUSED17:
-                       ++ip; /* warn, error ? */
-                       break;
-
                case CEE_CONV_OVF_I1:
                case CEE_CONV_OVF_U1:
                case CEE_CONV_OVF_I2:
@@ -4651,47 +5392,25 @@ mono_method_verify (MonoMethod *method, int level)
                        ++ip;
                        break;
 
-               case CEE_UNUSED50:
-               case CEE_UNUSED18:
-               case CEE_UNUSED19:
-               case CEE_UNUSED20:
-               case CEE_UNUSED21:
-               case CEE_UNUSED22:
-               case CEE_UNUSED23:
-                       ++ip; /* warn, error ? */
-                       break;
                case CEE_REFANYVAL:
-                       if (!check_underflow (&ctx, 1))
-                               break;
-                       ++ip;
+                       code_bounds_check (5);
+                       do_refanyval (&ctx, read32 (ip + 1));
+                       ip += 5;
                        break;
+
                case CEE_CKFINITE:
-                       if (!check_underflow (&ctx, 1))
-                               break;
+                       do_ckfinite (&ctx);
                        ++ip;
                        break;
-               case CEE_UNUSED24:
-               case CEE_UNUSED25:
-                       ++ip; /* warn, error ? */
-                       break;
+
                case CEE_MKREFANY:
-                       if (!check_underflow (&ctx, 1))
-                               break;
-                       token = read32 (ip + 1);
+                       code_bounds_check (5);
+                       do_mkrefany (&ctx,  read32 (ip + 1));
                        ip += 5;
                        break;
-               case CEE_UNUSED59:
-               case CEE_UNUSED60:
-               case CEE_UNUSED61:
-               case CEE_UNUSED62:
-               case CEE_UNUSED63:
-               case CEE_UNUSED64:
-               case CEE_UNUSED65:
-               case CEE_UNUSED66:
-               case CEE_UNUSED67:
-                       ++ip; /* warn, error ? */
-                       break;
+
                case CEE_LDTOKEN:
+                       code_bounds_check (5);
                        do_load_token (&ctx, read32 (ip + 1));
                        ip += 5;
                        break;
@@ -4705,55 +5424,25 @@ mono_method_verify (MonoMethod *method, int level)
                        break;
 
                case CEE_LEAVE:
+                       code_bounds_check (5);
                        do_leave (&ctx, read32 (ip + 1) + 5);
                        ip += 5;
                        start = 1;
                        break;
 
                case CEE_LEAVE_S:
+                       code_bounds_check (2);
                        do_leave (&ctx, (signed char)ip [1] + 2);
                        ip += 2;
                        start = 1;
                        break;
-                       
-               case CEE_UNUSED26:
-               case CEE_UNUSED27:
-               case CEE_UNUSED28:
-               case CEE_UNUSED29:
-               case CEE_UNUSED30:
-               case CEE_UNUSED31:
-               case CEE_UNUSED32:
-               case CEE_UNUSED33:
-               case CEE_UNUSED34:
-               case CEE_UNUSED35:
-               case CEE_UNUSED36:
-               case CEE_UNUSED37:
-               case CEE_UNUSED38:
-               case CEE_UNUSED39:
-               case CEE_UNUSED40:
-               case CEE_UNUSED41:
-               case CEE_UNUSED42:
-               case CEE_UNUSED43:
-               case CEE_UNUSED44:
-               case CEE_UNUSED45:
-               case CEE_UNUSED46:
-               case CEE_UNUSED47:
-               case CEE_UNUSED48:
-                       ++ip;
-                       break;
-               case CEE_PREFIX7:
-               case CEE_PREFIX6:
-               case CEE_PREFIX5:
-               case CEE_PREFIX4:
-               case CEE_PREFIX3:
-               case CEE_PREFIX2:
-               case CEE_PREFIXREF:
-                       ++ip;
-                       break;
+
                case CEE_PREFIX1:
+                       code_bounds_check (2);
                        ++ip;
                        switch (*ip) {
                        case CEE_STLOC:
+                               code_bounds_check (3);
                                store_local (&ctx, read16 (ip + 1));
                                ip += 3;
                                break;
@@ -4772,6 +5461,7 @@ mono_method_verify (MonoMethod *method, int level)
                                break;
 
                        case CEE_STARG:
+                               code_bounds_check (3);
                                store_arg (&ctx, read16 (ip + 1) );
                                ip += 3;
                                break;
@@ -4779,14 +5469,20 @@ 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:
+                               code_bounds_check (5);
                                do_load_function_ptr (&ctx, read32 (ip + 1), FALSE);
                                ip += 5;
                                break;
 
                        case CEE_LDVIRTFTN:
+                               code_bounds_check (5);
                                do_load_function_ptr (&ctx, read32 (ip + 1), TRUE);
                                ip += 5;
                                break;
@@ -4797,12 +5493,14 @@ mono_method_verify (MonoMethod *method, int level)
 
                        case CEE_LDARG:
                        case CEE_LDARGA:
+                               code_bounds_check (3);
                                push_arg (&ctx, read16 (ip + 1),  *ip == CEE_LDARGA);
                                ip += 3;
                                break;
 
                        case CEE_LDLOC:
                        case CEE_LDLOCA:
+                               code_bounds_check (3);
                                push_local (&ctx, read16 (ip + 1), *ip == CEE_LDLOCA);
                                ip += 3;
                                break;
@@ -4821,6 +5519,7 @@ mono_method_verify (MonoMethod *method, int level)
                                ++ip;
                                break;
                        case CEE_UNALIGNED_:
+                               code_bounds_check (2);
                                prefix |= PREFIX_UNALIGNED;
                                ip += 2;
                                break;
@@ -4836,24 +5535,39 @@ mono_method_verify (MonoMethod *method, int level)
                                break;
 
                        case CEE_INITOBJ:
+                               code_bounds_check (5);
                                do_initobj (&ctx, read32 (ip + 1));
                                ip += 5;
                                break;
 
                        case CEE_CONSTRAINED_:
-                               token = read32 (ip + 1);
+                               code_bounds_check (5);
+                               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:
+                               CLEAR_PREFIX (&ctx, PREFIX_UNALIGNED | PREFIX_VOLATILE);
                                if (!check_underflow (&ctx, 3))
                                        break;
+                               CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Instruction cpblk is not verifiable at 0x%04x", ctx.ip_offset));
                                ip++;
                                break;
+                               
                        case CEE_INITBLK:
+                               CLEAR_PREFIX (&ctx, PREFIX_UNALIGNED | PREFIX_VOLATILE);
                                if (!check_underflow (&ctx, 3))
                                        break;
+                               CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Instruction initblk is not verifiable at 0x%04x", ctx.ip_offset));
                                ip++;
                                break;
+                               
                        case CEE_NO_:
                                ip += 2;
                                break;
@@ -4868,22 +5582,48 @@ mono_method_verify (MonoMethod *method, int level)
                                break;
 
                        case CEE_SIZEOF:
+                               code_bounds_check (5);
                                do_sizeof (&ctx, read32 (ip + 1));
                                ip += 5;
                                break;
 
                        case CEE_REFANYTYPE:
-                               if (!check_underflow (&ctx, 1))
-                                       break;
+                               do_refanytype (&ctx);
                                ++ip;
                                break;
-                       case CEE_UNUSED53:
-                       case CEE_UNUSED54:
-                       case CEE_UNUSED55:
-                       case CEE_UNUSED70:
+
+                       default:
+                               ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid instruction FE %x at 0x%04x", *ip, ctx.ip_offset));
                                ++ip;
-                               break;
                        }
+                       break;
+
+               default:
+                       ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid instruction %x at 0x%04x", *ip, ctx.ip_offset));
+                       ++ip;
+               }
+
+               /*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;
+                       ctx.has_flags = TRUE;
+                       prefix = 0;
+               } else {
+                       if (!ctx.has_flags)
+                               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));
+                       if (ctx.prefix_set & PREFIX_VOLATILE)
+                               ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid instruction after volatile prefix at 0x%04x", ctx.ip_offset));
+                       if (ctx.prefix_set & PREFIX_UNALIGNED)
+                               ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid instruction after unaligned prefix at 0x%04x", ctx.ip_offset));
+                       ctx.prefix_set = prefix = 0;
+                       ctx.has_flags = FALSE;
                }
        }
        /*
@@ -4909,6 +5649,10 @@ mono_method_verify (MonoMethod *method, int level)
                        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 (mono_method_is_constructor (ctx.method) && !ctx.super_ctor_called && !ctx.method->klass->valuetype && ctx.method->klass != mono_defaults.object_class)
+               CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Constructor not calling super\n"));
+
+cleanup:
        if (ctx.code) {
                for (i = 0; i < ctx.header->code_size; ++i) {
                        if (ctx.code [i].stack)
@@ -4920,12 +5664,21 @@ mono_method_verify (MonoMethod *method, int level)
                g_free (tmp->data);
        g_slist_free (ctx.funptrs);
 
+       for (tmp = ctx.exception_types; tmp; tmp = tmp->next)
+               mono_metadata_free_type (tmp->data);
+       g_slist_free (ctx.exception_types);
+
+       for (i = 0; i < ctx.num_locals; ++i)
+               mono_metadata_free_type (ctx.locals [i]);
+       for (i = 0; i < ctx.max_args; ++i)
+               mono_metadata_free_type (ctx.params [i]);
+
        if (ctx.eval.stack)
                g_free (ctx.eval.stack);
        if (ctx.code)
                g_free (ctx.code);
-       if (ctx.signature->hasthis)
-               g_free (ctx.params);
+       g_free (ctx.locals);
+       g_free (ctx.params);
 
        return ctx.list;
 }
@@ -4937,4 +5690,139 @@ mono_verify_corlib ()
        return NULL;
 }
 
+static MiniVerifierMode verifier_mode = MONO_VERIFIER_MODE_OFF;
+static gboolean verify_all = FALSE;
+
+/*
+ * Set the desired level of checks for the verfier.
+ * 
+ */
+void
+mono_verifier_set_mode (MiniVerifierMode mode)
+{
+       verifier_mode = mode;
+}
+
+void
+mono_verifier_enable_verify_all ()
+{
+       verify_all = TRUE;
+}
+
+/*
+ * Returns true if @method needs to be verified.
+ * 
+ */
+gboolean
+mono_verifier_is_enabled_for_method (MonoMethod *method)
+{
+       return mono_verifier_is_enabled_for_class (method->klass) && method->wrapper_type == MONO_WRAPPER_NONE;
+}
+
+/*
+ * Returns true if @klass need to be verified.
+ * 
+ */
+gboolean
+mono_verifier_is_enabled_for_class (MonoClass *klass)
+{
+       return verify_all || (verifier_mode > MONO_VERIFIER_MODE_OFF && !klass->image->assembly->in_gac && klass->image != mono_defaults.corlib);
+}
+
+gboolean
+mono_verifier_is_method_full_trust (MonoMethod *method)
+{
+       return mono_verifier_is_class_full_trust (method->klass);
+}
+
+/*
+ * Returns if @klass is under full trust or not.
+ * 
+ * TODO This code doesn't take CAS into account.
+ * 
+ * This value is only pertinent to assembly verification and has
+ * nothing to do with CoreClr security. 
+ * 
+ * Under verify_all all user code must be verifiable if no security option was set 
+ * 
+ */
+gboolean
+mono_verifier_is_class_full_trust (MonoClass *klass)
+{
+       if (verify_all && verifier_mode == MONO_VERIFIER_MODE_OFF)
+               return klass->image->assembly->in_gac || klass->image == mono_defaults.corlib;
+       return verifier_mode < MONO_VERIFIER_MODE_VERIFIABLE || klass->image->assembly->in_gac || klass->image == mono_defaults.corlib;
+}
+
+GSList*
+mono_method_verify_with_current_settings (MonoMethod *method, gboolean skip_visibility)
+{
+       return mono_method_verify (method, 
+                       (verifier_mode != MONO_VERIFIER_MODE_STRICT ? MONO_VERIFY_NON_STRICT: 0)
+                       | (!mono_verifier_is_method_full_trust (method) ? MONO_VERIFY_FAIL_FAST : 0)
+                       | (skip_visibility ? MONO_VERIFY_SKIP_VISIBILITY : 0));
+}
+
+static int
+get_field_end (MonoClassField *field)
+{
+       int align;
+       int size = mono_type_size (field->type, &align);
+       if (size == 0)
+               size = 4; /*FIXME Is this a safe bet?*/
+       return size + field->offset;
+}
+
+static gboolean
+verify_class_for_overlapping_reference_fields (MonoClass *class)
+{
+       int i, j;
+       gboolean is_fulltrust = mono_verifier_is_class_full_trust (class);
+       if (!((class->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_EXPLICIT_LAYOUT) || !class->has_references)
+               return TRUE;
+               
+               //we must check for stuff overlapping reference fields
+       for (i = 0; i < class->field.count; ++i) {
+               MonoClassField *field = &class->fields [i];
+               int fieldEnd = get_field_end (field);
+               gboolean is_valuetype = !MONO_TYPE_IS_REFERENCE (field->type);
+               if (mono_field_is_deleted (field) || (field->type->attrs & FIELD_ATTRIBUTE_STATIC))
+                       continue;
+
+               for (j = i + 1; j < class->field.count; ++j) {
+                       MonoClassField *other = &class->fields [j];
+                       int otherEnd = get_field_end (other);
+                       if (mono_field_is_deleted (other) || (is_valuetype && !MONO_TYPE_IS_REFERENCE (other->type)) || (other->type->attrs & FIELD_ATTRIBUTE_STATIC))
+                               continue;
+
+                       if (!is_valuetype && MONO_TYPE_IS_REFERENCE (other->type) && field->offset == other->offset && is_fulltrust)
+                               continue;
+
+                       if ((otherEnd > field->offset && otherEnd <= fieldEnd) || (other->offset >= field->offset && other->offset < fieldEnd))
+                               return FALSE;
+               }
+       }
+       return TRUE;
+}
 
+/*
+ * Check if the class is verifiable.
+ * 
+ * Right now there are no conditions that make a class a valid but not verifiable. Both overlapping reference
+ * field and invalid generic instantiation are fatal errors.
+ * 
+ * This method must be safe to be called from mono_class_init and all code must be carefull about that.
+ * 
+ */
+gboolean
+mono_verifier_verify_class (MonoClass *class)
+{
+       if (class->generic_container && (class->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_EXPLICIT_LAYOUT)
+               return FALSE;
+       if (!verify_class_for_overlapping_reference_fields (class))
+               return FALSE;
+       
+       if (class->generic_class && !mono_class_is_valid_generic_instantiation (NULL, class))
+               return FALSE;
+       return TRUE;
+}