5 * Mono Project (http://www.mono-project.com)
7 * Copyright 2001-2003 Ximian, Inc (http://www.ximian.com)
8 * Copyright 2004-2009 Novell, Inc (http://www.novell.com)
12 #include <mono/metadata/object-internals.h>
13 #include <mono/metadata/verify.h>
14 #include <mono/metadata/verify-internals.h>
15 #include <mono/metadata/opcodes.h>
16 #include <mono/metadata/tabledefs.h>
17 #include <mono/metadata/reflection.h>
18 #include <mono/metadata/debug-helpers.h>
19 #include <mono/metadata/mono-endian.h>
20 #include <mono/metadata/metadata.h>
21 #include <mono/metadata/metadata-internals.h>
22 #include <mono/metadata/class-internals.h>
23 #include <mono/metadata/security-manager.h>
24 #include <mono/metadata/security-core-clr.h>
25 #include <mono/metadata/tokentype.h>
26 #include <mono/metadata/mono-basic-block.h>
27 #include <mono/utils/mono-counters.h>
28 #include <mono/utils/monobitset.h>
33 static MiniVerifierMode verifier_mode = MONO_VERIFIER_MODE_OFF;
34 static gboolean verify_all = FALSE;
37 * Set the desired level of checks for the verfier.
41 mono_verifier_set_mode (MiniVerifierMode mode)
47 mono_verifier_enable_verify_all ()
52 #ifndef DISABLE_VERIFIER
54 * Pull the list of opcodes
56 #define OPDEF(a,b,c,d,e,f,g,h,i,j) \
60 #include "mono/cil/opcode.def"
65 #ifdef MONO_VERIFIER_DEBUG
66 #define VERIFIER_DEBUG(code) do { code } while (0)
68 #define VERIFIER_DEBUG(code)
71 //////////////////////////////////////////////////////////////////
72 #define IS_STRICT_MODE(ctx) (((ctx)->level & MONO_VERIFY_NON_STRICT) == 0)
73 #define IS_FAIL_FAST_MODE(ctx) (((ctx)->level & MONO_VERIFY_FAIL_FAST) == MONO_VERIFY_FAIL_FAST)
74 #define IS_SKIP_VISIBILITY(ctx) (((ctx)->level & MONO_VERIFY_SKIP_VISIBILITY) == MONO_VERIFY_SKIP_VISIBILITY)
75 #define IS_REPORT_ALL_ERRORS(ctx) (((ctx)->level & MONO_VERIFY_REPORT_ALL_ERRORS) == MONO_VERIFY_REPORT_ALL_ERRORS)
76 #define CLEAR_PREFIX(ctx, prefix) do { (ctx)->prefix_set &= ~(prefix); } while (0)
77 #define ADD_VERIFY_INFO(__ctx, __msg, __status, __exception) \
79 MonoVerifyInfoExtended *vinfo = g_new (MonoVerifyInfoExtended, 1); \
80 vinfo->info.status = __status; \
81 vinfo->info.message = ( __msg ); \
82 vinfo->exception_type = (__exception); \
83 (__ctx)->list = g_slist_prepend ((__ctx)->list, vinfo); \
86 //TODO support MONO_VERIFY_REPORT_ALL_ERRORS
87 #define ADD_VERIFY_ERROR(__ctx, __msg) \
89 ADD_VERIFY_INFO(__ctx, __msg, MONO_VERIFY_ERROR, MONO_EXCEPTION_INVALID_PROGRAM); \
93 #define CODE_NOT_VERIFIABLE(__ctx, __msg) \
95 if ((__ctx)->verifiable || IS_REPORT_ALL_ERRORS (__ctx)) { \
96 ADD_VERIFY_INFO(__ctx, __msg, MONO_VERIFY_NOT_VERIFIABLE, MONO_EXCEPTION_UNVERIFIABLE_IL); \
97 (__ctx)->verifiable = 0; \
98 if (IS_FAIL_FAST_MODE (__ctx)) \
103 #define ADD_VERIFY_ERROR2(__ctx, __msg, __exception) \
105 ADD_VERIFY_INFO(__ctx, __msg, MONO_VERIFY_ERROR, __exception); \
106 (__ctx)->valid = 0; \
109 #define CODE_NOT_VERIFIABLE2(__ctx, __msg, __exception) \
111 if ((__ctx)->verifiable || IS_REPORT_ALL_ERRORS (__ctx)) { \
112 ADD_VERIFY_INFO(__ctx, __msg, MONO_VERIFY_NOT_VERIFIABLE, __exception); \
113 (__ctx)->verifiable = 0; \
114 if (IS_FAIL_FAST_MODE (__ctx)) \
115 (__ctx)->valid = 0; \
119 #define CHECK_ADD4_OVERFLOW_UN(a, b) ((guint32)(0xFFFFFFFFU) - (guint32)(b) < (guint32)(a))
120 #define CHECK_ADD8_OVERFLOW_UN(a, b) ((guint64)(0xFFFFFFFFFFFFFFFFUL) - (guint64)(b) < (guint64)(a))
122 #if SIZEOF_VOID_P == 4
123 #define CHECK_ADDP_OVERFLOW_UN(a,b) CHECK_ADD4_OVERFLOW_UN(a, b)
125 #define CHECK_ADDP_OVERFLOW_UN(a,b) CHECK_ADD8_OVERFLOW_UN(a, b)
128 #define ADDP_IS_GREATER_OR_OVF(a, b, c) (((a) + (b) > (c)) || CHECK_ADDP_OVERFLOW_UN (a, b))
129 #define ADD_IS_GREATER_OR_OVF(a, b, c) (((a) + (b) > (c)) || CHECK_ADD4_OVERFLOW_UN (a, b))
131 /*Flags to be used with ILCodeDesc::flags */
133 /*Instruction has not been processed.*/
134 IL_CODE_FLAG_NOT_PROCESSED = 0,
135 /*Instruction was decoded by mono_method_verify loop.*/
136 IL_CODE_FLAG_SEEN = 1,
137 /*Instruction was target of a branch or is at a protected block boundary.*/
138 IL_CODE_FLAG_WAS_TARGET = 2,
139 /*Used by stack_init to avoid double initialize each entry.*/
140 IL_CODE_FLAG_STACK_INITED = 4,
141 /*Used by merge_stacks to decide if it should just copy the eval stack.*/
142 IL_CODE_STACK_MERGED = 8,
143 /*This instruction is part of the delegate construction sequence, it cannot be target of a branch.*/
144 IL_CODE_DELEGATE_SEQUENCE = 0x10,
145 /*This is a delegate created from a ldftn to a non final virtual method*/
146 IL_CODE_LDFTN_DELEGATE_NONFINAL_VIRTUAL = 0x20,
147 /*This is a call to a non final virtual method*/
148 IL_CODE_CALL_NONFINAL_VIRTUAL = 0x40,
166 guint16 size, max_size;
183 /*Allocated fnptr MonoType that should be freed by us.*/
185 /*Type dup'ed exception types from catch blocks.*/
186 GSList *exception_types;
191 /*TODO get rid of target here, need_merge in mono_method_verify and hoist the merging code in the branching code*/
195 MonoMethodSignature *signature;
196 MonoMethodHeader *header;
198 MonoGenericContext *generic_context;
202 /*This flag helps solving a corner case of delegate verification in that you cannot have a "starg 0"
203 *on a method that creates a delegate for a non-final virtual method using ldftn*/
204 gboolean has_this_store;
206 /*This flag is used to control if the contructor of the parent class has been called.
207 *If the this pointer is pushed on the eval stack and it's a reference type constructor and
208 * super_ctor_called is false, the uninitialized flag is set on the pushed value.
210 * Poping an uninitialized this ptr from the eval stack is an unverifiable operation unless
211 * the safe variant is used. Only a few opcodes can use it : dup, pop, ldfld, stfld and call to a constructor.
213 gboolean super_ctor_called;
217 MonoType *constrained_type;
221 merge_stacks (VerifyContext *ctx, ILCodeDesc *from, ILCodeDesc *to, gboolean start, gboolean external);
224 get_stack_type (MonoType *type);
227 mono_delegate_signature_equal (MonoMethodSignature *delegate_sig, MonoMethodSignature *method_sig, gboolean is_static_ldftn);
230 mono_class_is_valid_generic_instantiation (VerifyContext *ctx, MonoClass *klass);
233 mono_method_is_valid_generic_instantiation (VerifyContext *ctx, MonoMethod *method);
235 static MonoGenericParam*
236 verifier_get_generic_param_from_type (VerifyContext *ctx, MonoType *type);
237 //////////////////////////////////////////////////////////////////
242 TYPE_INV = 0, /* leave at 0. */
247 /* Used by operator tables to resolve pointer types (managed & unmanaged) and by unmanaged pointer types*/
249 /* value types and classes */
251 /* Number of types, used to define the size of the tables*/
254 /* Used by tables to signal that a result is not verifiable*/
255 NON_VERIFIABLE_RESULT = 0x80,
257 /*Mask used to extract just the type, excluding flags */
260 /* The stack type is a managed pointer, unmask the value to res */
261 POINTER_MASK = 0x100,
263 /*Stack type with the pointer mask*/
264 RAW_TYPE_MASK = 0x10F,
266 /* Controlled Mutability Manager Pointer */
269 /* The stack type is a null literal*/
270 NULL_LITERAL_MASK = 0x400,
272 /**Used by ldarg.0 and family to let delegate verification happens.*/
273 THIS_POINTER_MASK = 0x800,
275 /**Signals that this is a boxed value type*/
278 /*This is an unitialized this ref*/
279 UNINIT_THIS_MASK = 0x2000,
282 static const char* const
283 type_names [TYPE_MAX + 1] = {
294 PREFIX_UNALIGNED = 1,
297 PREFIX_CONSTRAINED = 8,
300 //////////////////////////////////////////////////////////////////
302 #ifdef ENABLE_VERIFIER_STATS
304 #define MEM_ALLOC(amt) do { allocated_memory += (amt); working_set += (amt); } while (0)
305 #define MEM_FREE(amt) do { working_set -= (amt); } while (0)
307 static int allocated_memory;
308 static int working_set;
309 static int max_allocated_memory;
310 static int max_working_set;
311 static int total_allocated_memory;
314 finish_collect_stats (void)
316 max_allocated_memory = MAX (max_allocated_memory, allocated_memory);
317 max_working_set = MAX (max_working_set, working_set);
318 total_allocated_memory += allocated_memory;
319 allocated_memory = working_set = 0;
323 init_verifier_stats (void)
325 static gboolean inited;
328 mono_counters_register ("Maximum memory allocated during verification", MONO_COUNTER_METADATA | MONO_COUNTER_INT, &max_allocated_memory);
329 mono_counters_register ("Maximum memory used during verification", MONO_COUNTER_METADATA | MONO_COUNTER_INT, &max_working_set);
330 mono_counters_register ("Total memory allocated for verification", MONO_COUNTER_METADATA | MONO_COUNTER_INT, &total_allocated_memory);
336 #define MEM_ALLOC(amt) do {} while (0)
337 #define MEM_FREE(amt) do { } while (0)
339 #define finish_collect_stats()
340 #define init_verifier_stats()
345 //////////////////////////////////////////////////////////////////
348 /*Token validation macros and functions */
349 #define IS_MEMBER_REF(token) (mono_metadata_token_table (token) == MONO_TABLE_MEMBERREF)
350 #define IS_METHOD_DEF(token) (mono_metadata_token_table (token) == MONO_TABLE_METHOD)
351 #define IS_METHOD_SPEC(token) (mono_metadata_token_table (token) == MONO_TABLE_METHODSPEC)
352 #define IS_FIELD_DEF(token) (mono_metadata_token_table (token) == MONO_TABLE_FIELD)
354 #define IS_TYPE_REF(token) (mono_metadata_token_table (token) == MONO_TABLE_TYPEREF)
355 #define IS_TYPE_DEF(token) (mono_metadata_token_table (token) == MONO_TABLE_TYPEDEF)
356 #define IS_TYPE_SPEC(token) (mono_metadata_token_table (token) == MONO_TABLE_TYPESPEC)
357 #define IS_METHOD_DEF_OR_REF_OR_SPEC(token) (IS_METHOD_DEF (token) || IS_MEMBER_REF (token) || IS_METHOD_SPEC (token))
358 #define IS_TYPE_DEF_OR_REF_OR_SPEC(token) (IS_TYPE_DEF (token) || IS_TYPE_REF (token) || IS_TYPE_SPEC (token))
359 #define IS_FIELD_DEF_OR_REF(token) (IS_FIELD_DEF (token) || IS_MEMBER_REF (token))
362 * Verify if @token refers to a valid row on int's table.
365 token_bounds_check (MonoImage *image, guint32 token)
368 return mono_reflection_is_valid_dynamic_token ((MonoDynamicImage*)image, token);
369 return image->tables [mono_metadata_token_table (token)].rows >= mono_metadata_token_index (token);
373 mono_type_create_fnptr_from_mono_method (VerifyContext *ctx, MonoMethod *method)
375 MonoType *res = g_new0 (MonoType, 1);
376 MEM_ALLOC (sizeof (MonoType));
378 //FIXME use mono_method_get_signature_full
379 res->data.method = mono_method_signature (method);
380 res->type = MONO_TYPE_FNPTR;
381 ctx->funptrs = g_slist_prepend (ctx->funptrs, res);
386 * mono_type_is_enum_type:
388 * Returns TRUE if @type is an enum type.
391 mono_type_is_enum_type (MonoType *type)
393 if (type->type == MONO_TYPE_VALUETYPE && type->data.klass->enumtype)
395 if (type->type == MONO_TYPE_GENERICINST && type->data.generic_class->container_class->enumtype)
401 * mono_type_is_value_type:
403 * Returns TRUE if @type is named after @namespace.@name.
407 mono_type_is_value_type (MonoType *type, const char *namespace, const char *name)
409 return type->type == MONO_TYPE_VALUETYPE &&
410 !strcmp (namespace, type->data.klass->name_space) &&
411 !strcmp (name, type->data.klass->name);
415 * Returns TURE if @type is VAR or MVAR
418 mono_type_is_generic_argument (MonoType *type)
420 return type->type == MONO_TYPE_VAR || type->type == MONO_TYPE_MVAR;
424 * mono_type_get_underlying_type_any:
426 * This functions is just like mono_type_get_underlying_type but it doesn't care if the type is byref.
428 * Returns the underlying type of @type regardless if it is byref or not.
431 mono_type_get_underlying_type_any (MonoType *type)
433 if (type->type == MONO_TYPE_VALUETYPE && type->data.klass->enumtype)
434 return mono_class_enum_basetype (type->data.klass);
435 if (type->type == MONO_TYPE_GENERICINST && type->data.generic_class->container_class->enumtype)
436 return mono_class_enum_basetype (type->data.generic_class->container_class);
440 static G_GNUC_UNUSED const char*
441 mono_type_get_stack_name (MonoType *type)
443 return type_names [get_stack_type (type) & TYPE_MASK];
446 #define CTOR_REQUIRED_FLAGS (METHOD_ATTRIBUTE_SPECIAL_NAME | METHOD_ATTRIBUTE_RT_SPECIAL_NAME)
447 #define CTOR_INVALID_FLAGS (METHOD_ATTRIBUTE_STATIC)
450 mono_method_is_constructor (MonoMethod *method)
452 return ((method->flags & CTOR_REQUIRED_FLAGS) == CTOR_REQUIRED_FLAGS &&
453 !(method->flags & CTOR_INVALID_FLAGS) &&
454 !strcmp (".ctor", method->name));
458 mono_class_has_default_constructor (MonoClass *klass)
463 mono_class_setup_methods (klass);
464 if (klass->exception_type)
467 for (i = 0; i < klass->method.count; ++i) {
468 method = klass->methods [i];
469 if (mono_method_is_constructor (method) &&
470 mono_method_signature (method) &&
471 mono_method_signature (method)->param_count == 0 &&
472 (method->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK) == METHOD_ATTRIBUTE_PUBLIC)
479 * Verify if @type is valid for the given @ctx verification context.
480 * this function checks for VAR and MVAR types that are invalid under the current verifier,
483 mono_type_is_valid_type_in_context (MonoType *type, MonoGenericContext *context)
486 MonoGenericInst *inst;
488 switch (type->type) {
493 inst = type->type == MONO_TYPE_VAR ? context->class_inst : context->method_inst;
494 if (!inst || mono_type_get_generic_param_num (type) >= inst->type_argc)
497 case MONO_TYPE_SZARRAY:
498 return mono_type_is_valid_type_in_context (&type->data.klass->byval_arg, context);
499 case MONO_TYPE_ARRAY:
500 return mono_type_is_valid_type_in_context (&type->data.array->eklass->byval_arg, context);
502 return mono_type_is_valid_type_in_context (type->data.type, context);
503 case MONO_TYPE_GENERICINST:
504 inst = type->data.generic_class->context.class_inst;
507 for (i = 0; i < inst->type_argc; ++i)
508 if (!mono_type_is_valid_type_in_context (inst->type_argv [i], context))
511 case MONO_TYPE_CLASS:
512 case MONO_TYPE_VALUETYPE: {
513 MonoClass *klass = type->data.klass;
515 * It's possible to encode generic'sh types in such a way that they disguise themselves as class or valuetype.
516 * Fixing the type decoding is really tricky since under some cases this behavior is needed, for example, to
517 * have a 'class' type pointing to a 'genericinst' class.
519 * For the runtime these non canonical (weird) encodings work fine, they worst they can cause is some
520 * reflection oddities which are harmless - to security at least.
522 if (klass->byval_arg.type != type->type)
523 return mono_type_is_valid_type_in_context (&klass->byval_arg, context);
530 /*This function returns NULL if the type is not instantiatable*/
532 verifier_inflate_type (VerifyContext *ctx, MonoType *type, MonoGenericContext *context)
537 result = mono_class_inflate_generic_type_checked (type, context, &error);
538 if (!mono_error_ok (&error)) {
539 mono_error_cleanup (&error);
547 is_valid_generic_instantiation (MonoGenericContainer *gc, MonoGenericContext *context, MonoGenericInst *ginst)
552 if (ginst->type_argc != gc->type_argc)
555 for (i = 0; i < gc->type_argc; ++i) {
556 MonoGenericParamInfo *param_info = mono_generic_container_get_param_info (gc, i);
557 MonoClass *paramClass;
558 MonoClass **constraints;
559 MonoType *param_type = ginst->type_argv [i];
561 /*it's not our job to validate type variables*/
562 if (mono_type_is_generic_argument (param_type))
565 paramClass = mono_class_from_mono_type (param_type);
567 if (paramClass->exception_type != MONO_EXCEPTION_NONE)
570 /* A GTD can't be a generic argument.
572 * Due to how types are encoded we must check for the case of a genericinst MonoType and GTD MonoClass.
573 * This happens in cases such as: class Foo<T> { void X() { new Bar<T> (); } }
575 * Open instantiations can have GTDs as this happens when one type is instantiated with others params
576 * and the former has an expansion into the later. For example:
578 * class A<T>: B<K> {}
579 * The type A <K> has a parent B<K>, that is inflated into the GTD B<>.
580 * Since A<K> is open, thus not instantiatable, this is valid.
582 if (paramClass->generic_container && param_type->type != MONO_TYPE_GENERICINST && !ginst->is_open)
585 /*it's not safe to call mono_class_init from here*/
586 if (paramClass->generic_class && !paramClass->inited) {
587 if (!mono_class_is_valid_generic_instantiation (NULL, paramClass))
591 if (!param_info->constraints && !(param_info->flags & GENERIC_PARAMETER_ATTRIBUTE_SPECIAL_CONSTRAINTS_MASK))
594 if ((param_info->flags & GENERIC_PARAMETER_ATTRIBUTE_VALUE_TYPE_CONSTRAINT) && (!paramClass->valuetype || mono_class_is_nullable (paramClass)))
597 if ((param_info->flags & GENERIC_PARAMETER_ATTRIBUTE_REFERENCE_TYPE_CONSTRAINT) && paramClass->valuetype)
600 if ((param_info->flags & GENERIC_PARAMETER_ATTRIBUTE_CONSTRUCTOR_CONSTRAINT) && !paramClass->valuetype && !mono_class_has_default_constructor (paramClass))
603 if (!param_info->constraints)
606 for (constraints = param_info->constraints; *constraints; ++constraints) {
607 MonoClass *ctr = *constraints;
610 inflated = mono_class_inflate_generic_type_checked (&ctr->byval_arg, context, &error);
611 if (!mono_error_ok (&error)) {
612 mono_error_cleanup (&error);
615 ctr = mono_class_from_mono_type (inflated);
616 mono_metadata_free_type (inflated);
618 if (!mono_class_is_assignable_from_slow (ctr, paramClass))
626 * Return true if @candidate is constraint compatible with @target.
628 * This means that @candidate constraints are a super set of @target constaints
631 mono_generic_param_is_constraint_compatible (VerifyContext *ctx, MonoGenericParam *target, MonoGenericParam *candidate, MonoClass *candidate_param_class, MonoGenericContext *context)
633 MonoGenericParamInfo *tinfo = mono_generic_param_info (target);
634 MonoGenericParamInfo *cinfo = mono_generic_param_info (candidate);
636 int tmask = tinfo->flags & GENERIC_PARAMETER_ATTRIBUTE_SPECIAL_CONSTRAINTS_MASK;
637 int cmask = cinfo->flags & GENERIC_PARAMETER_ATTRIBUTE_SPECIAL_CONSTRAINTS_MASK;
638 if ((tmask & cmask) != tmask)
641 if (tinfo->constraints) {
642 MonoClass **target_class, **candidate_class;
643 for (target_class = tinfo->constraints; *target_class; ++target_class) {
645 MonoType *inflated = verifier_inflate_type (ctx, &(*target_class)->byval_arg, context);
648 tc = mono_class_from_mono_type (inflated);
649 mono_metadata_free_type (inflated);
652 * A constraint from @target might inflate into @candidate itself and in that case we don't need
653 * check it's constraints since it satisfy the constraint by itself.
655 if (mono_metadata_type_equal (&tc->byval_arg, &candidate_param_class->byval_arg))
658 if (!cinfo->constraints)
661 for (candidate_class = cinfo->constraints; *candidate_class; ++candidate_class) {
663 inflated = verifier_inflate_type (ctx, &(*candidate_class)->byval_arg, ctx->generic_context);
666 cc = mono_class_from_mono_type (inflated);
667 mono_metadata_free_type (inflated);
669 if (mono_class_is_assignable_from (tc, cc))
673 * This happens when we have the following:
675 * Bar<K> where K : IFace
676 * Foo<T, U> where T : U where U : IFace
678 * Bar<T> <- T here satisfy K constraint transitively through to U's constraint
681 if (mono_type_is_generic_argument (&cc->byval_arg)) {
682 MonoGenericParam *other_candidate = verifier_get_generic_param_from_type (ctx, &cc->byval_arg);
684 if (mono_generic_param_is_constraint_compatible (ctx, target, other_candidate, cc, context)) {
689 if (!*candidate_class)
696 static MonoGenericParam*
697 verifier_get_generic_param_from_type (VerifyContext *ctx, MonoType *type)
699 MonoGenericContainer *gc;
700 MonoMethod *method = ctx->method;
703 num = mono_type_get_generic_param_num (type);
705 if (type->type == MONO_TYPE_VAR) {
706 MonoClass *gtd = method->klass;
707 if (gtd->generic_class)
708 gtd = gtd->generic_class->container_class;
709 gc = gtd->generic_container;
711 MonoMethod *gmd = method;
712 if (method->is_inflated)
713 gmd = ((MonoMethodInflated*)method)->declaring;
714 gc = mono_method_get_generic_container (gmd);
718 return mono_generic_container_get_param (gc, num);
724 * Verify if @type is valid for the given @ctx verification context.
725 * this function checks for VAR and MVAR types that are invalid under the current verifier,
726 * This means that it either
729 is_valid_type_in_context (VerifyContext *ctx, MonoType *type)
731 return mono_type_is_valid_type_in_context (type, ctx->generic_context);
735 is_valid_generic_instantiation_in_context (VerifyContext *ctx, MonoGenericInst *ginst)
738 for (i = 0; i < ginst->type_argc; ++i) {
739 MonoType *type = ginst->type_argv [i];
740 if (!is_valid_type_in_context (ctx, type))
747 generic_arguments_respect_constraints (VerifyContext *ctx, MonoGenericContainer *gc, MonoGenericContext *context, MonoGenericInst *ginst)
750 for (i = 0; i < ginst->type_argc; ++i) {
751 MonoType *type = ginst->type_argv [i];
752 MonoGenericParam *target = mono_generic_container_get_param (gc, i);
753 MonoGenericParam *candidate;
754 MonoClass *candidate_class;
756 if (!mono_type_is_generic_argument (type))
759 if (!is_valid_type_in_context (ctx, type))
762 candidate = verifier_get_generic_param_from_type (ctx, type);
763 candidate_class = mono_class_from_mono_type (type);
765 if (!mono_generic_param_is_constraint_compatible (ctx, target, candidate, candidate_class, context))
772 mono_method_repect_method_constraints (VerifyContext *ctx, MonoMethod *method)
774 MonoMethodInflated *gmethod = (MonoMethodInflated *)method;
775 MonoGenericInst *ginst = gmethod->context.method_inst;
776 MonoGenericContainer *gc = mono_method_get_generic_container (gmethod->declaring);
777 return !gc || generic_arguments_respect_constraints (ctx, gc, &gmethod->context, ginst);
781 mono_class_repect_method_constraints (VerifyContext *ctx, MonoClass *klass)
783 MonoGenericClass *gklass = klass->generic_class;
784 MonoGenericInst *ginst = gklass->context.class_inst;
785 MonoGenericContainer *gc = gklass->container_class->generic_container;
786 return !gc || generic_arguments_respect_constraints (ctx, gc, &gklass->context, ginst);
790 mono_method_is_valid_generic_instantiation (VerifyContext *ctx, MonoMethod *method)
792 MonoMethodInflated *gmethod = (MonoMethodInflated *)method;
793 MonoGenericInst *ginst = gmethod->context.method_inst;
794 MonoGenericContainer *gc = mono_method_get_generic_container (gmethod->declaring);
795 if (!gc) /*non-generic inflated method - it's part of a generic type */
797 if (ctx && !is_valid_generic_instantiation_in_context (ctx, ginst))
799 return is_valid_generic_instantiation (gc, &gmethod->context, ginst);
804 mono_class_is_valid_generic_instantiation (VerifyContext *ctx, MonoClass *klass)
806 MonoGenericClass *gklass = klass->generic_class;
807 MonoGenericInst *ginst = gklass->context.class_inst;
808 MonoGenericContainer *gc = gklass->container_class->generic_container;
809 if (ctx && !is_valid_generic_instantiation_in_context (ctx, ginst))
811 return is_valid_generic_instantiation (gc, &gklass->context, ginst);
815 mono_type_is_valid_in_context (VerifyContext *ctx, MonoType *type)
820 ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid null type at 0x%04x", ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE);
824 if (!is_valid_type_in_context (ctx, type)) {
825 char *str = mono_type_full_name (type);
826 ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid generic type (%s%s) (argument out of range or %s is not generic) at 0x%04x",
827 type->type == MONO_TYPE_VAR ? "!" : "!!",
829 type->type == MONO_TYPE_VAR ? "class" : "method",
831 MONO_EXCEPTION_BAD_IMAGE);
836 klass = mono_class_from_mono_type (type);
837 mono_class_init (klass);
838 if (mono_loader_get_last_error () || klass->exception_type != MONO_EXCEPTION_NONE) {
839 if (klass->generic_class && !mono_class_is_valid_generic_instantiation (NULL, klass))
840 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);
842 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);
843 mono_loader_clear_error ();
847 if (klass->generic_class && klass->generic_class->container_class->exception_type != MONO_EXCEPTION_NONE) {
848 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);
852 if (!klass->generic_class)
855 if (!mono_class_is_valid_generic_instantiation (ctx, klass)) {
856 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);
860 if (!mono_class_repect_method_constraints (ctx, klass)) {
861 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);
868 static verify_result_t
869 mono_method_is_valid_in_context (VerifyContext *ctx, MonoMethod *method)
871 if (!mono_type_is_valid_in_context (ctx, &method->klass->byval_arg))
872 return RESULT_INVALID;
874 if (!method->is_inflated)
877 if (!mono_method_is_valid_generic_instantiation (ctx, method)) {
878 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);
879 return RESULT_INVALID;
882 if (!mono_method_repect_method_constraints (ctx, method)) {
883 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));
884 return RESULT_UNVERIFIABLE;
890 static MonoClassField*
891 verifier_load_field (VerifyContext *ctx, int token, MonoClass **out_klass, const char *opcode) {
892 MonoClassField *field;
893 MonoClass *klass = NULL;
895 if (!IS_FIELD_DEF_OR_REF (token) || !token_bounds_check (ctx->image, token)) {
896 ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid field token 0x%08x for %s at 0x%04x", token, opcode, ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE);
900 field = mono_field_from_token (ctx->image, token, &klass, ctx->generic_context);
901 if (!field || !field->parent || !klass || mono_loader_get_last_error ()) {
902 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);
903 mono_loader_clear_error ();
907 if (!mono_type_is_valid_in_context (ctx, &klass->byval_arg))
910 if (mono_field_get_flags (field) & FIELD_ATTRIBUTE_LITERAL) {
911 char *type_name = mono_type_get_full_name (field->parent);
912 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Cannot reference literal field %s::%s at 0x%04x", type_name, field->name, ctx->ip_offset));
922 verifier_load_method (VerifyContext *ctx, int token, const char *opcode) {
925 if (!IS_METHOD_DEF_OR_REF_OR_SPEC (token) || !token_bounds_check (ctx->image, token)) {
926 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);
930 method = mono_get_method_full (ctx->image, token, NULL, ctx->generic_context);
932 if (!method || mono_loader_get_last_error ()) {
933 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);
934 mono_loader_clear_error ();
938 if (mono_method_is_valid_in_context (ctx, method) == RESULT_INVALID)
945 verifier_load_type (VerifyContext *ctx, int token, const char *opcode) {
948 if (!IS_TYPE_DEF_OR_REF_OR_SPEC (token) || !token_bounds_check (ctx->image, token)) {
949 ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid type token 0x%08x at 0x%04x", token, ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE);
953 type = mono_type_get_full (ctx->image, token, ctx->generic_context);
955 if (!type || mono_loader_get_last_error ()) {
956 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);
957 mono_loader_clear_error ();
961 if (!mono_type_is_valid_in_context (ctx, type))
968 /* stack_slot_get_type:
970 * Returns the stack type of @value. This value includes POINTER_MASK.
972 * Use this function to checks that account for a managed pointer.
975 stack_slot_get_type (ILStackDesc *value)
977 return value->stype & RAW_TYPE_MASK;
980 /* stack_slot_get_underlying_type:
982 * Returns the stack type of @value. This value does not include POINTER_MASK.
984 * Use this function is cases where the fact that the value could be a managed pointer is
985 * irrelevant. For example, field load doesn't care about this fact of type on stack.
988 stack_slot_get_underlying_type (ILStackDesc *value)
990 return value->stype & TYPE_MASK;
993 /* stack_slot_is_managed_pointer:
995 * Returns TRUE is @value is a managed pointer.
998 stack_slot_is_managed_pointer (ILStackDesc *value)
1000 return (value->stype & POINTER_MASK) == POINTER_MASK;
1003 /* stack_slot_is_managed_mutability_pointer:
1005 * Returns TRUE is @value is a managed mutability pointer.
1007 static G_GNUC_UNUSED gboolean
1008 stack_slot_is_managed_mutability_pointer (ILStackDesc *value)
1010 return (value->stype & CMMP_MASK) == CMMP_MASK;
1013 /* stack_slot_is_null_literal:
1015 * Returns TRUE is @value is the null literal.
1018 stack_slot_is_null_literal (ILStackDesc *value)
1020 return (value->stype & NULL_LITERAL_MASK) == NULL_LITERAL_MASK;
1024 /* stack_slot_is_this_pointer:
1026 * Returns TRUE is @value is the this literal
1029 stack_slot_is_this_pointer (ILStackDesc *value)
1031 return (value->stype & THIS_POINTER_MASK) == THIS_POINTER_MASK;
1034 /* stack_slot_is_boxed_value:
1036 * Returns TRUE is @value is a boxed value
1039 stack_slot_is_boxed_value (ILStackDesc *value)
1041 return (value->stype & BOXED_MASK) == BOXED_MASK;
1045 stack_slot_get_name (ILStackDesc *value)
1047 return type_names [value->stype & TYPE_MASK];
1050 #define APPEND_WITH_PREDICATE(PRED,NAME) do {\
1051 if (PRED (value)) { \
1053 g_string_append (str, ", "); \
1054 g_string_append (str, NAME); \
1059 stack_slot_stack_type_full_name (ILStackDesc *value)
1061 GString *str = g_string_new ("");
1063 gboolean has_pred = FALSE, first = TRUE;
1065 if ((value->stype & TYPE_MASK) != value->stype) {
1066 g_string_append(str, "[");
1067 APPEND_WITH_PREDICATE (stack_slot_is_this_pointer, "this");
1068 APPEND_WITH_PREDICATE (stack_slot_is_boxed_value, "boxed");
1069 APPEND_WITH_PREDICATE (stack_slot_is_null_literal, "null");
1070 APPEND_WITH_PREDICATE (stack_slot_is_managed_mutability_pointer, "cmmp");
1071 APPEND_WITH_PREDICATE (stack_slot_is_managed_pointer, "mp");
1075 if (mono_type_is_generic_argument (value->type) && !stack_slot_is_boxed_value (value)) {
1077 g_string_append(str, "[");
1079 g_string_append (str, ", ");
1080 g_string_append (str, "unboxed");
1085 g_string_append(str, "] ");
1087 g_string_append (str, stack_slot_get_name (value));
1089 g_string_free (str, FALSE);
1094 stack_slot_full_name (ILStackDesc *value)
1096 char *type_name = mono_type_full_name (value->type);
1097 char *stack_name = stack_slot_stack_type_full_name (value);
1098 char *res = g_strdup_printf ("%s (%s)", type_name, stack_name);
1100 g_free (stack_name);
1104 //////////////////////////////////////////////////////////////////
1106 mono_free_verify_list (GSList *list)
1108 MonoVerifyInfoExtended *info;
1111 for (tmp = list; tmp; tmp = tmp->next) {
1113 g_free (info->info.message);
1116 g_slist_free (list);
1119 #define ADD_ERROR(list,msg) \
1121 MonoVerifyInfoExtended *vinfo = g_new (MonoVerifyInfoExtended, 1); \
1122 vinfo->info.status = MONO_VERIFY_ERROR; \
1123 vinfo->info.message = (msg); \
1124 (list) = g_slist_prepend ((list), vinfo); \
1127 #define ADD_WARN(list,code,msg) \
1129 MonoVerifyInfoExtended *vinfo = g_new (MonoVerifyInfoExtended, 1); \
1130 vinfo->info.status = (code); \
1131 vinfo->info.message = (msg); \
1132 (list) = g_slist_prepend ((list), vinfo); \
1135 #define ADD_INVALID(list,msg) \
1137 MonoVerifyInfoExtended *vinfo = g_new (MonoVerifyInfoExtended, 1); \
1138 vinfo->status = MONO_VERIFY_ERROR; \
1139 vinfo->message = (msg); \
1140 (list) = g_slist_prepend ((list), vinfo); \
1141 /*G_BREAKPOINT ();*/ \
1145 #define CHECK_STACK_UNDERFLOW(num) \
1147 if (cur_stack < (num)) \
1148 ADD_INVALID (list, g_strdup_printf ("Stack underflow at 0x%04x (%d items instead of %d)", ip_offset, cur_stack, (num))); \
1151 #define CHECK_STACK_OVERFLOW() \
1153 if (cur_stack >= max_stack) \
1154 ADD_INVALID (list, g_strdup_printf ("Maxstack exceeded at 0x%04x", ip_offset)); \
1159 in_any_block (MonoMethodHeader *header, guint offset)
1162 MonoExceptionClause *clause;
1164 for (i = 0; i < header->num_clauses; ++i) {
1165 clause = &header->clauses [i];
1166 if (MONO_OFFSET_IN_CLAUSE (clause, offset))
1168 if (MONO_OFFSET_IN_HANDLER (clause, offset))
1170 if (MONO_OFFSET_IN_FILTER (clause, offset))
1177 * in_any_exception_block:
1179 * Returns TRUE is @offset is part of any exception clause (filter, handler, catch, finally or fault).
1182 in_any_exception_block (MonoMethodHeader *header, guint offset)
1185 MonoExceptionClause *clause;
1187 for (i = 0; i < header->num_clauses; ++i) {
1188 clause = &header->clauses [i];
1189 if (MONO_OFFSET_IN_HANDLER (clause, offset))
1191 if (MONO_OFFSET_IN_FILTER (clause, offset))
1198 * is_valid_branch_instruction:
1200 * Verify if it's valid to perform a branch from @offset to @target.
1201 * This should be used with br and brtrue/false.
1202 * It returns 0 if valid, 1 for unverifiable and 2 for invalid.
1203 * The major diferent from other similiar functions is that branching into a
1204 * finally/fault block is invalid instead of just unverifiable.
1207 is_valid_branch_instruction (MonoMethodHeader *header, guint offset, guint target)
1210 MonoExceptionClause *clause;
1212 for (i = 0; i < header->num_clauses; ++i) {
1213 clause = &header->clauses [i];
1214 /*branching into a finally block is invalid*/
1215 if ((clause->flags == MONO_EXCEPTION_CLAUSE_FINALLY || clause->flags == MONO_EXCEPTION_CLAUSE_FAULT) &&
1216 !MONO_OFFSET_IN_HANDLER (clause, offset) &&
1217 MONO_OFFSET_IN_HANDLER (clause, target))
1220 if (clause->try_offset != target && (MONO_OFFSET_IN_CLAUSE (clause, offset) ^ MONO_OFFSET_IN_CLAUSE (clause, target)))
1222 if (MONO_OFFSET_IN_HANDLER (clause, offset) ^ MONO_OFFSET_IN_HANDLER (clause, target))
1224 if (MONO_OFFSET_IN_FILTER (clause, offset) ^ MONO_OFFSET_IN_FILTER (clause, target))
1231 * is_valid_cmp_branch_instruction:
1233 * Verify if it's valid to perform a branch from @offset to @target.
1234 * This should be used with binary comparison branching instruction, like beq, bge and similars.
1235 * It returns 0 if valid, 1 for unverifiable and 2 for invalid.
1237 * The major diferences from other similar functions are that most errors lead to invalid
1238 * code and only branching out of finally, filter or fault clauses is unverifiable.
1241 is_valid_cmp_branch_instruction (MonoMethodHeader *header, guint offset, guint target)
1244 MonoExceptionClause *clause;
1246 for (i = 0; i < header->num_clauses; ++i) {
1247 clause = &header->clauses [i];
1248 /*branching out of a handler or finally*/
1249 if (clause->flags != MONO_EXCEPTION_CLAUSE_NONE &&
1250 MONO_OFFSET_IN_HANDLER (clause, offset) &&
1251 !MONO_OFFSET_IN_HANDLER (clause, target))
1254 if (clause->try_offset != target && (MONO_OFFSET_IN_CLAUSE (clause, offset) ^ MONO_OFFSET_IN_CLAUSE (clause, target)))
1256 if (MONO_OFFSET_IN_HANDLER (clause, offset) ^ MONO_OFFSET_IN_HANDLER (clause, target))
1258 if (MONO_OFFSET_IN_FILTER (clause, offset) ^ MONO_OFFSET_IN_FILTER (clause, target))
1265 * A leave can't escape a finally block
1268 is_correct_leave (MonoMethodHeader *header, guint offset, guint target)
1271 MonoExceptionClause *clause;
1273 for (i = 0; i < header->num_clauses; ++i) {
1274 clause = &header->clauses [i];
1275 if (clause->flags == MONO_EXCEPTION_CLAUSE_FINALLY && MONO_OFFSET_IN_HANDLER (clause, offset) && !MONO_OFFSET_IN_HANDLER (clause, target))
1277 if (MONO_OFFSET_IN_FILTER (clause, offset))
1284 * A rethrow can't happen outside of a catch handler.
1287 is_correct_rethrow (MonoMethodHeader *header, guint offset)
1290 MonoExceptionClause *clause;
1292 for (i = 0; i < header->num_clauses; ++i) {
1293 clause = &header->clauses [i];
1294 if (MONO_OFFSET_IN_HANDLER (clause, offset))
1296 if (MONO_OFFSET_IN_FILTER (clause, offset))
1303 * An endfinally can't happen outside of a finally/fault handler.
1306 is_correct_endfinally (MonoMethodHeader *header, guint offset)
1309 MonoExceptionClause *clause;
1311 for (i = 0; i < header->num_clauses; ++i) {
1312 clause = &header->clauses [i];
1313 if (MONO_OFFSET_IN_HANDLER (clause, offset) && (clause->flags == MONO_EXCEPTION_CLAUSE_FAULT || clause->flags == MONO_EXCEPTION_CLAUSE_FINALLY))
1321 * An endfilter can only happens inside a filter clause.
1322 * In non-strict mode filter is allowed inside the handler clause too
1324 static MonoExceptionClause *
1325 is_correct_endfilter (VerifyContext *ctx, guint offset)
1328 MonoExceptionClause *clause;
1330 for (i = 0; i < ctx->header->num_clauses; ++i) {
1331 clause = &ctx->header->clauses [i];
1332 if (clause->flags != MONO_EXCEPTION_CLAUSE_FILTER)
1334 if (MONO_OFFSET_IN_FILTER (clause, offset))
1336 if (!IS_STRICT_MODE (ctx) && MONO_OFFSET_IN_HANDLER (clause, offset))
1344 * Non-strict endfilter can happens inside a try block or any handler block
1347 is_unverifiable_endfilter (VerifyContext *ctx, guint offset)
1350 MonoExceptionClause *clause;
1352 for (i = 0; i < ctx->header->num_clauses; ++i) {
1353 clause = &ctx->header->clauses [i];
1354 if (MONO_OFFSET_IN_CLAUSE (clause, offset))
1361 is_valid_bool_arg (ILStackDesc *arg)
1363 if (stack_slot_is_managed_pointer (arg) || stack_slot_is_boxed_value (arg) || stack_slot_is_null_literal (arg))
1367 switch (stack_slot_get_underlying_type (arg)) {
1370 case TYPE_NATIVE_INT:
1374 g_assert (arg->type);
1375 switch (arg->type->type) {
1376 case MONO_TYPE_CLASS:
1377 case MONO_TYPE_STRING:
1378 case MONO_TYPE_OBJECT:
1379 case MONO_TYPE_SZARRAY:
1380 case MONO_TYPE_ARRAY:
1381 case MONO_TYPE_FNPTR:
1384 case MONO_TYPE_GENERICINST:
1385 /*We need to check if the container class
1386 * of the generic type is a valuetype, iow:
1387 * is it a "class Foo<T>" or a "struct Foo<T>"?
1389 return !arg->type->data.generic_class->container_class->valuetype;
1397 /*Type manipulation helper*/
1399 /*Returns the byref version of the supplied MonoType*/
1401 mono_type_get_type_byref (MonoType *type)
1405 return &mono_class_from_mono_type (type)->this_arg;
1409 /*Returns the byval version of the supplied MonoType*/
1411 mono_type_get_type_byval (MonoType *type)
1415 return &mono_class_from_mono_type (type)->byval_arg;
1419 mono_type_from_stack_slot (ILStackDesc *slot)
1421 if (stack_slot_is_managed_pointer (slot))
1422 return mono_type_get_type_byref (slot->type);
1426 /*Stack manipulation code*/
1429 ensure_stack_size (ILCodeDesc *stack, int required)
1434 if (required < stack->max_size)
1437 /* We don't have to worry about the exponential growth since stack_copy prune unused space */
1438 new_size = MAX (8, MAX (required, stack->max_size * 2));
1440 g_assert (new_size >= stack->size);
1441 g_assert (new_size >= required);
1443 tmp = g_new0 (ILStackDesc, new_size);
1444 MEM_ALLOC (sizeof (ILStackDesc) * new_size);
1448 memcpy (tmp, stack->stack, stack->size * sizeof (ILStackDesc));
1449 g_free (stack->stack);
1450 MEM_FREE (sizeof (ILStackDesc) * stack->max_size);
1454 stack->max_size = new_size;
1458 stack_init (VerifyContext *ctx, ILCodeDesc *state)
1460 if (state->flags & IL_CODE_FLAG_STACK_INITED)
1462 state->size = state->max_size = 0;
1463 state->flags |= IL_CODE_FLAG_STACK_INITED;
1467 stack_copy (ILCodeDesc *to, ILCodeDesc *from)
1469 ensure_stack_size (to, from->size);
1470 to->size = from->size;
1472 /*stack copy happens at merge points, which have small stacks*/
1474 memcpy (to->stack, from->stack, sizeof (ILStackDesc) * from->size);
1478 copy_stack_value (ILStackDesc *to, ILStackDesc *from)
1480 to->stype = from->stype;
1481 to->type = from->type;
1482 to->method = from->method;
1486 check_underflow (VerifyContext *ctx, int size)
1488 if (ctx->eval.size < size) {
1489 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Stack underflow, required %d, but have %d at 0x%04x", size, ctx->eval.size, ctx->ip_offset));
1496 check_overflow (VerifyContext *ctx)
1498 if (ctx->eval.size >= ctx->max_stack) {
1499 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Method doesn't have stack-depth %d at 0x%04x", ctx->eval.size + 1, ctx->ip_offset));
1505 /*This reject out PTR, FNPTR and TYPEDBYREF*/
1507 check_unmanaged_pointer (VerifyContext *ctx, ILStackDesc *value)
1509 if (stack_slot_get_type (value) == TYPE_PTR) {
1510 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Unmanaged pointer is not a verifiable type at 0x%04x", ctx->ip_offset));
1516 /*TODO verify if MONO_TYPE_TYPEDBYREF is not allowed here as well.*/
1518 check_unverifiable_type (VerifyContext *ctx, MonoType *type)
1520 if (type->type == MONO_TYPE_PTR || type->type == MONO_TYPE_FNPTR) {
1521 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Unmanaged pointer is not a verifiable type at 0x%04x", ctx->ip_offset));
1527 static ILStackDesc *
1528 stack_push (VerifyContext *ctx)
1530 g_assert (ctx->eval.size < ctx->max_stack);
1531 g_assert (ctx->eval.size <= ctx->eval.max_size);
1533 ensure_stack_size (&ctx->eval, ctx->eval.size + 1);
1535 return & ctx->eval.stack [ctx->eval.size++];
1538 static ILStackDesc *
1539 stack_push_val (VerifyContext *ctx, int stype, MonoType *type)
1541 ILStackDesc *top = stack_push (ctx);
1547 static ILStackDesc *
1548 stack_pop (VerifyContext *ctx)
1551 g_assert (ctx->eval.size > 0);
1552 ret = ctx->eval.stack + --ctx->eval.size;
1553 if ((ret->stype & UNINIT_THIS_MASK) == UNINIT_THIS_MASK)
1554 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Found use of uninitialized 'this ptr' ref at 0x%04x", ctx->ip_offset));
1558 /* This function allows to safely pop an unititialized this ptr from
1559 * the eval stack without marking the method as unverifiable.
1561 static ILStackDesc *
1562 stack_pop_safe (VerifyContext *ctx)
1564 g_assert (ctx->eval.size > 0);
1565 return ctx->eval.stack + --ctx->eval.size;
1568 /*Positive number distance from stack top. [0] is stack top, [1] is the one below*/
1570 stack_peek (VerifyContext *ctx, int distance)
1572 g_assert (ctx->eval.size - distance > 0);
1573 return ctx->eval.stack + (ctx->eval.size - 1 - distance);
1576 static ILStackDesc *
1577 stack_push_stack_val (VerifyContext *ctx, ILStackDesc *value)
1579 ILStackDesc *top = stack_push (ctx);
1580 copy_stack_value (top, value);
1584 /* Returns the MonoType associated with the token, or NULL if it is invalid.
1586 * A boxable type can be either a reference or value type, but cannot be a byref type or an unmanaged pointer
1589 get_boxable_mono_type (VerifyContext* ctx, int token, const char *opcode)
1594 if (!(type = verifier_load_type (ctx, token, opcode)))
1597 if (type->byref && type->type != MONO_TYPE_TYPEDBYREF) {
1598 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid use of byref type for %s at 0x%04x", opcode, ctx->ip_offset));
1602 if (type->type == MONO_TYPE_VOID) {
1603 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid use of void type for %s at 0x%04x", opcode, ctx->ip_offset));
1607 if (type->type == MONO_TYPE_TYPEDBYREF)
1608 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid use of typedbyref for %s at 0x%04x", opcode, ctx->ip_offset));
1610 if (!(class = mono_class_from_mono_type (type)))
1611 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Could not retrieve type token for %s at 0x%04x", opcode, ctx->ip_offset));
1613 if (class->generic_container && type->type != MONO_TYPE_GENERICINST)
1614 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use the generic type definition in a boxable type position for %s at 0x%04x", opcode, ctx->ip_offset));
1616 check_unverifiable_type (ctx, type);
1621 /*operation result tables */
1623 static const unsigned char bin_op_table [TYPE_MAX][TYPE_MAX] = {
1624 {TYPE_I4, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV},
1625 {TYPE_INV, TYPE_I8, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
1626 {TYPE_NATIVE_INT, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV},
1627 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_R8, TYPE_INV, TYPE_INV},
1628 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
1629 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
1632 static const unsigned char add_table [TYPE_MAX][TYPE_MAX] = {
1633 {TYPE_I4, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV},
1634 {TYPE_INV, TYPE_I8, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
1635 {TYPE_NATIVE_INT, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV},
1636 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_R8, TYPE_INV, TYPE_INV},
1637 {TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV, TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV, TYPE_INV, TYPE_INV},
1638 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
1641 static const unsigned char sub_table [TYPE_MAX][TYPE_MAX] = {
1642 {TYPE_I4, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV},
1643 {TYPE_INV, TYPE_I8, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
1644 {TYPE_NATIVE_INT, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV},
1645 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_R8, TYPE_INV, TYPE_INV},
1646 {TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV, TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV, TYPE_NATIVE_INT | NON_VERIFIABLE_RESULT, TYPE_INV},
1647 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
1650 static const unsigned char int_bin_op_table [TYPE_MAX][TYPE_MAX] = {
1651 {TYPE_I4, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV},
1652 {TYPE_INV, TYPE_I8, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
1653 {TYPE_NATIVE_INT, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV},
1654 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
1655 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
1656 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
1659 static const unsigned char shift_op_table [TYPE_MAX][TYPE_MAX] = {
1660 {TYPE_I4, TYPE_INV, TYPE_I4, TYPE_INV, TYPE_INV, TYPE_INV},
1661 {TYPE_I8, TYPE_INV, TYPE_I8, TYPE_INV, TYPE_INV, TYPE_INV},
1662 {TYPE_NATIVE_INT, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV},
1663 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
1664 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
1665 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
1668 static const unsigned char cmp_br_op [TYPE_MAX][TYPE_MAX] = {
1669 {TYPE_I4, TYPE_INV, TYPE_I4, TYPE_INV, TYPE_INV, TYPE_INV},
1670 {TYPE_INV, TYPE_I4, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
1671 {TYPE_I4, TYPE_INV, TYPE_I4, TYPE_INV, TYPE_INV, TYPE_INV},
1672 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_I4, TYPE_INV, TYPE_INV},
1673 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_I4, TYPE_INV},
1674 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
1677 static const unsigned char cmp_br_eq_op [TYPE_MAX][TYPE_MAX] = {
1678 {TYPE_I4, TYPE_INV, TYPE_I4, TYPE_INV, TYPE_INV, TYPE_INV},
1679 {TYPE_INV, TYPE_I4, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
1680 {TYPE_I4, TYPE_INV, TYPE_I4, TYPE_INV, TYPE_I4 | NON_VERIFIABLE_RESULT, TYPE_INV},
1681 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_I4, TYPE_INV, TYPE_INV},
1682 {TYPE_INV, TYPE_INV, TYPE_I4 | NON_VERIFIABLE_RESULT, TYPE_INV, TYPE_I4, TYPE_INV},
1683 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_I4},
1686 static const unsigned char add_ovf_un_table [TYPE_MAX][TYPE_MAX] = {
1687 {TYPE_I4, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV},
1688 {TYPE_INV, TYPE_I8, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
1689 {TYPE_NATIVE_INT, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV},
1690 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
1691 {TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV, TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV, TYPE_INV, TYPE_INV},
1692 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
1695 static const unsigned char sub_ovf_un_table [TYPE_MAX][TYPE_MAX] = {
1696 {TYPE_I4, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV},
1697 {TYPE_INV, TYPE_I8, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
1698 {TYPE_NATIVE_INT, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV},
1699 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
1700 {TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV, TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV, TYPE_NATIVE_INT | NON_VERIFIABLE_RESULT, TYPE_INV},
1701 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
1704 static const unsigned char bin_ovf_table [TYPE_MAX][TYPE_MAX] = {
1705 {TYPE_I4, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV},
1706 {TYPE_INV, TYPE_I8, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
1707 {TYPE_NATIVE_INT, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV},
1708 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
1709 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
1710 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
1713 #ifdef MONO_VERIFIER_DEBUG
1717 dump_stack_value (ILStackDesc *value)
1719 printf ("[(%x)(%x)", value->type->type, value->stype);
1721 if (stack_slot_is_this_pointer (value))
1724 if (stack_slot_is_boxed_value (value))
1725 printf ("[boxed] ");
1727 if (stack_slot_is_null_literal (value))
1730 if (stack_slot_is_managed_mutability_pointer (value))
1731 printf ("Controled Mutability MP: ");
1733 if (stack_slot_is_managed_pointer (value))
1734 printf ("Managed Pointer to: ");
1736 switch (stack_slot_get_underlying_type (value)) {
1738 printf ("invalid type]");
1746 case TYPE_NATIVE_INT:
1747 printf ("native int]");
1750 printf ("float64]");
1753 printf ("unmanaged pointer]");
1756 switch (value->type->type) {
1757 case MONO_TYPE_CLASS:
1758 case MONO_TYPE_VALUETYPE:
1759 printf ("complex] (%s)", value->type->data.klass->name);
1761 case MONO_TYPE_STRING:
1762 printf ("complex] (string)");
1764 case MONO_TYPE_OBJECT:
1765 printf ("complex] (object)");
1767 case MONO_TYPE_SZARRAY:
1768 printf ("complex] (%s [])", value->type->data.klass->name);
1770 case MONO_TYPE_ARRAY:
1771 printf ("complex] (%s [%d %d %d])",
1772 value->type->data.array->eklass->name,
1773 value->type->data.array->rank,
1774 value->type->data.array->numsizes,
1775 value->type->data.array->numlobounds);
1777 case MONO_TYPE_GENERICINST:
1778 printf ("complex] (inst of %s )", value->type->data.generic_class->container_class->name);
1781 printf ("complex] (type generic param !%d - %s) ", value->type->data.generic_param->num, mono_generic_param_info (value->type->data.generic_param)->name);
1783 case MONO_TYPE_MVAR:
1784 printf ("complex] (method generic param !!%d - %s) ", value->type->data.generic_param->num, mono_generic_param_info (value->type->data.generic_param)->name);
1787 //should be a boxed value
1788 char * name = mono_type_full_name (value->type);
1789 printf ("complex] %s", name);
1795 printf ("unknown stack %x type]\n", value->stype);
1796 g_assert_not_reached ();
1801 dump_stack_state (ILCodeDesc *state)
1805 printf ("(%d) ", state->size);
1806 for (i = 0; i < state->size; ++i)
1807 dump_stack_value (state->stack + i);
1812 /*Returns TRUE if candidate array type can be assigned to target.
1813 *Both parameters MUST be of type MONO_TYPE_ARRAY (target->type == MONO_TYPE_ARRAY)
1816 is_array_type_compatible (MonoType *target, MonoType *candidate)
1818 MonoArrayType *left = target->data.array;
1819 MonoArrayType *right = candidate->data.array;
1821 g_assert (target->type == MONO_TYPE_ARRAY);
1822 g_assert (candidate->type == MONO_TYPE_ARRAY);
1824 if (left->rank != right->rank)
1827 return mono_class_is_assignable_from (left->eklass, right->eklass);
1831 get_stack_type (MonoType *type)
1834 int type_kind = type->type;
1836 mask = POINTER_MASK;
1837 /*TODO handle CMMP_MASK */
1840 switch (type_kind) {
1843 case MONO_TYPE_BOOLEAN:
1846 case MONO_TYPE_CHAR:
1849 return TYPE_I4 | mask;
1853 return TYPE_NATIVE_INT | mask;
1855 /* FIXME: the spec says that you cannot have a pointer to method pointer, do we need to check this here? */
1856 case MONO_TYPE_FNPTR:
1858 case MONO_TYPE_TYPEDBYREF:
1859 return TYPE_PTR | mask;
1862 case MONO_TYPE_MVAR:
1864 case MONO_TYPE_CLASS:
1865 case MONO_TYPE_STRING:
1866 case MONO_TYPE_OBJECT:
1867 case MONO_TYPE_SZARRAY:
1868 case MONO_TYPE_ARRAY:
1869 return TYPE_COMPLEX | mask;
1873 return TYPE_I8 | mask;
1877 return TYPE_R8 | mask;
1879 case MONO_TYPE_GENERICINST:
1880 case MONO_TYPE_VALUETYPE:
1881 if (mono_type_is_enum_type (type)) {
1882 type = mono_type_get_underlying_type_any (type);
1885 type_kind = type->type;
1888 return TYPE_COMPLEX | mask;
1896 /* convert MonoType to ILStackDesc format (stype) */
1898 set_stack_value (VerifyContext *ctx, ILStackDesc *stack, MonoType *type, int take_addr)
1901 int type_kind = type->type;
1903 if (type->byref || take_addr)
1904 mask = POINTER_MASK;
1905 /* TODO handle CMMP_MASK */
1910 switch (type_kind) {
1913 case MONO_TYPE_BOOLEAN:
1916 case MONO_TYPE_CHAR:
1919 stack->stype = TYPE_I4 | mask;
1923 stack->stype = TYPE_NATIVE_INT | mask;
1926 /*FIXME: Do we need to check if it's a pointer to the method pointer? The spec says it' illegal to have that.*/
1927 case MONO_TYPE_FNPTR:
1929 case MONO_TYPE_TYPEDBYREF:
1930 stack->stype = TYPE_PTR | mask;
1933 case MONO_TYPE_CLASS:
1934 case MONO_TYPE_STRING:
1935 case MONO_TYPE_OBJECT:
1936 case MONO_TYPE_SZARRAY:
1937 case MONO_TYPE_ARRAY:
1940 case MONO_TYPE_MVAR:
1941 stack->stype = TYPE_COMPLEX | mask;
1946 stack->stype = TYPE_I8 | mask;
1950 stack->stype = TYPE_R8 | mask;
1952 case MONO_TYPE_GENERICINST:
1953 case MONO_TYPE_VALUETYPE:
1954 if (mono_type_is_enum_type (type)) {
1955 MonoType *utype = mono_type_get_underlying_type_any (type);
1957 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Could not resolve underlying type of %x at %d", type->type, ctx->ip_offset));
1961 type_kind = type->type;
1964 stack->stype = TYPE_COMPLEX | mask;
1968 VERIFIER_DEBUG ( printf ("unknown type 0x%02x in eval stack type\n", type->type); );
1969 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Illegal value set on stack 0x%02x at %d", type->type, ctx->ip_offset));
1976 * init_stack_with_value_at_exception_boundary:
1978 * Initialize the stack and push a given type.
1979 * The instruction is marked as been on the exception boundary.
1982 init_stack_with_value_at_exception_boundary (VerifyContext *ctx, ILCodeDesc *code, MonoClass *klass)
1985 MonoType *type = mono_class_inflate_generic_type_checked (&klass->byval_arg, ctx->generic_context, &error);
1987 if (!mono_error_ok (&error)) {
1988 char *name = mono_type_get_full_name (klass);
1989 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid class %s used for exception", name));
1991 mono_error_cleanup (&error);
1995 if (!ctx->max_stack) {
1996 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Stack overflow at 0x%04x", ctx->ip_offset));
2000 stack_init (ctx, code);
2001 ensure_stack_size (code, 1);
2002 set_stack_value (ctx, code->stack, type, FALSE);
2003 ctx->exception_types = g_slist_prepend (ctx->exception_types, type);
2005 code->flags |= IL_CODE_FLAG_WAS_TARGET;
2006 if (mono_type_is_generic_argument (type))
2007 code->stack->stype |= BOXED_MASK;
2010 /*Verify if type 'candidate' can be stored in type 'target'.
2012 * If strict, check for the underlying type and not the verification stack types
2015 verify_type_compatibility_full (VerifyContext *ctx, MonoType *target, MonoType *candidate, gboolean strict)
2017 #define IS_ONE_OF3(T, A, B, C) (T == A || T == B || T == C)
2018 #define IS_ONE_OF2(T, A, B) (T == A || T == B)
2020 MonoType *original_candidate = candidate;
2021 VERIFIER_DEBUG ( printf ("checking type compatibility %s x %s strict %d\n", mono_type_full_name (target), mono_type_full_name (candidate), strict); );
2023 /*only one is byref */
2024 if (candidate->byref ^ target->byref) {
2025 /* converting from native int to byref*/
2026 if (get_stack_type (candidate) == TYPE_NATIVE_INT && target->byref) {
2027 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("using byref native int at 0x%04x", ctx->ip_offset));
2032 strict |= target->byref;
2033 /*From now on we don't care about byref anymore, so it's ok to discard it here*/
2034 candidate = mono_type_get_underlying_type_any (candidate);
2037 switch (target->type) {
2038 case MONO_TYPE_VOID:
2039 return candidate->type == MONO_TYPE_VOID;
2042 case MONO_TYPE_BOOLEAN:
2044 return IS_ONE_OF3 (candidate->type, MONO_TYPE_I1, MONO_TYPE_U1, MONO_TYPE_BOOLEAN);
2047 case MONO_TYPE_CHAR:
2049 return IS_ONE_OF3 (candidate->type, MONO_TYPE_I2, MONO_TYPE_U2, MONO_TYPE_CHAR);
2051 case MONO_TYPE_U4: {
2052 gboolean is_native_int = IS_ONE_OF2 (candidate->type, MONO_TYPE_I, MONO_TYPE_U);
2053 gboolean is_int4 = IS_ONE_OF2 (candidate->type, MONO_TYPE_I4, MONO_TYPE_U4);
2055 return is_native_int || is_int4;
2056 return is_native_int || get_stack_type (candidate) == TYPE_I4;
2061 return IS_ONE_OF2 (candidate->type, MONO_TYPE_I8, MONO_TYPE_U8);
2066 return candidate->type == target->type;
2067 return IS_ONE_OF2 (candidate->type, MONO_TYPE_R4, MONO_TYPE_R8);
2071 gboolean is_native_int = IS_ONE_OF2 (candidate->type, MONO_TYPE_I, MONO_TYPE_U);
2072 gboolean is_int4 = IS_ONE_OF2 (candidate->type, MONO_TYPE_I4, MONO_TYPE_U4);
2074 return is_native_int || is_int4;
2075 return is_native_int || get_stack_type (candidate) == TYPE_I4;
2079 if (candidate->type != MONO_TYPE_PTR)
2081 /* check the underlying type */
2082 return verify_type_compatibility_full (ctx, target->data.type, candidate->data.type, TRUE);
2084 case MONO_TYPE_FNPTR: {
2085 MonoMethodSignature *left, *right;
2086 if (candidate->type != MONO_TYPE_FNPTR)
2089 left = mono_type_get_signature (target);
2090 right = mono_type_get_signature (candidate);
2091 return mono_metadata_signature_equal (left, right) && left->call_convention == right->call_convention;
2094 case MONO_TYPE_GENERICINST: {
2095 MonoClass *target_klass;
2096 MonoClass *candidate_klass;
2097 if (mono_type_is_enum_type (target)) {
2098 target = mono_type_get_underlying_type_any (target);
2104 * VAR / MVAR compatibility must be checked by verify_stack_type_compatibility
2105 * to take boxing status into account.
2107 if (mono_type_is_generic_argument (original_candidate))
2110 target_klass = mono_class_from_mono_type (target);
2111 candidate_klass = mono_class_from_mono_type (candidate);
2112 if (mono_class_is_nullable (target_klass)) {
2113 if (!mono_class_is_nullable (candidate_klass))
2115 return target_klass == candidate_klass;
2118 return mono_class_is_assignable_from (target_klass, candidate_klass);
2121 case MONO_TYPE_STRING:
2122 return candidate->type == MONO_TYPE_STRING;
2124 case MONO_TYPE_CLASS:
2126 * VAR / MVAR compatibility must be checked by verify_stack_type_compatibility
2127 * to take boxing status into account.
2129 if (mono_type_is_generic_argument (original_candidate))
2132 if (candidate->type == MONO_TYPE_VALUETYPE)
2135 /* If candidate is an enum it should return true for System.Enum and supertypes.
2136 * That's why here we use the original type and not the underlying type.
2138 return mono_class_is_assignable_from (target->data.klass, mono_class_from_mono_type (original_candidate));
2140 case MONO_TYPE_OBJECT:
2141 return MONO_TYPE_IS_REFERENCE (candidate);
2143 case MONO_TYPE_SZARRAY: {
2146 if (candidate->type != MONO_TYPE_SZARRAY)
2149 left = mono_class_from_mono_type (target);
2150 right = mono_class_from_mono_type (candidate);
2152 return mono_class_is_assignable_from (left, right);
2155 case MONO_TYPE_ARRAY:
2156 if (candidate->type != MONO_TYPE_ARRAY)
2158 return is_array_type_compatible (target, candidate);
2160 case MONO_TYPE_TYPEDBYREF:
2161 return candidate->type == MONO_TYPE_TYPEDBYREF;
2163 case MONO_TYPE_VALUETYPE: {
2164 MonoClass *target_klass;
2165 MonoClass *candidate_klass;
2167 if (candidate->type == MONO_TYPE_CLASS)
2170 target_klass = mono_class_from_mono_type (target);
2171 candidate_klass = mono_class_from_mono_type (candidate);
2172 if (target_klass == candidate_klass)
2174 if (mono_type_is_enum_type (target)) {
2175 target = mono_type_get_underlying_type_any (target);
2184 if (candidate->type != MONO_TYPE_VAR)
2186 return mono_type_get_generic_param_num (candidate) == mono_type_get_generic_param_num (target);
2188 case MONO_TYPE_MVAR:
2189 if (candidate->type != MONO_TYPE_MVAR)
2191 return mono_type_get_generic_param_num (candidate) == mono_type_get_generic_param_num (target);
2194 VERIFIER_DEBUG ( printf ("unknown store type %d\n", target->type); );
2195 g_assert_not_reached ();
2204 verify_type_compatibility (VerifyContext *ctx, MonoType *target, MonoType *candidate)
2206 return verify_type_compatibility_full (ctx, target, candidate, FALSE);
2210 * Returns the generic param bound to the context been verified.
2213 static MonoGenericParam*
2214 get_generic_param (VerifyContext *ctx, MonoType *param)
2216 guint16 param_num = mono_type_get_generic_param_num (param);
2217 if (param->type == MONO_TYPE_VAR) {
2218 if (!ctx->generic_context->class_inst || ctx->generic_context->class_inst->type_argc <= param_num) {
2219 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid generic type argument %d", param_num));
2222 return ctx->generic_context->class_inst->type_argv [param_num]->data.generic_param;
2225 /*param must be a MVAR */
2226 if (!ctx->generic_context->method_inst || ctx->generic_context->method_inst->type_argc <= param_num) {
2227 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid generic method argument %d", param_num));
2230 return ctx->generic_context->method_inst->type_argv [param_num]->data.generic_param;
2235 recursive_boxed_constraint_type_check (VerifyContext *ctx, MonoType *type, MonoClass *constraint_class, int recursion_level)
2237 MonoType *constraint_type = &constraint_class->byval_arg;
2238 if (recursion_level <= 0)
2241 if (verify_type_compatibility_full (ctx, type, mono_type_get_type_byval (constraint_type), FALSE))
2244 if (mono_type_is_generic_argument (constraint_type)) {
2245 MonoGenericParam *param = get_generic_param (ctx, constraint_type);
2249 for (class = mono_generic_param_info (param)->constraints; class && *class; ++class) {
2250 if (recursive_boxed_constraint_type_check (ctx, type, *class, recursion_level - 1))
2258 * is_compatible_boxed_valuetype:
2260 * Returns TRUE if @candidate / @stack is a valid boxed valuetype.
2262 * @type The source type. It it tested to be of the proper type.
2263 * @candidate type of the boxed valuetype.
2264 * @stack stack slot of the boxed valuetype, separate from @candidade since one could be changed before calling this function
2265 * @strict if TRUE candidate must be boxed compatible to the target type
2269 is_compatible_boxed_valuetype (VerifyContext *ctx, MonoType *type, MonoType *candidate, ILStackDesc *stack, gboolean strict)
2271 if (!stack_slot_is_boxed_value (stack))
2273 if (type->byref || candidate->byref)
2276 if (mono_type_is_generic_argument (candidate)) {
2277 MonoGenericParam *param = get_generic_param (ctx, candidate);
2282 for (class = mono_generic_param_info (param)->constraints; class && *class; ++class) {
2283 /*256 should be enough since there can't be more than 255 generic arguments.*/
2284 if (recursive_boxed_constraint_type_check (ctx, type, *class, 256))
2289 if (mono_type_is_generic_argument (type))
2295 return MONO_TYPE_IS_REFERENCE (type) && mono_class_is_assignable_from (mono_class_from_mono_type (type), mono_class_from_mono_type (candidate));
2299 verify_stack_type_compatibility_full (VerifyContext *ctx, MonoType *type, ILStackDesc *stack, gboolean drop_byref, gboolean valuetype_must_be_boxed)
2301 MonoType *candidate = mono_type_from_stack_slot (stack);
2302 if (MONO_TYPE_IS_REFERENCE (type) && !type->byref && stack_slot_is_null_literal (stack))
2305 if (is_compatible_boxed_valuetype (ctx, type, candidate, stack, TRUE))
2308 if (valuetype_must_be_boxed && !stack_slot_is_boxed_value (stack) && !MONO_TYPE_IS_REFERENCE (candidate))
2311 if (!valuetype_must_be_boxed && stack_slot_is_boxed_value (stack))
2315 return verify_type_compatibility_full (ctx, type, mono_type_get_type_byval (candidate), FALSE);
2317 return verify_type_compatibility_full (ctx, type, candidate, FALSE);
2321 verify_stack_type_compatibility (VerifyContext *ctx, MonoType *type, ILStackDesc *stack)
2323 return verify_stack_type_compatibility_full (ctx, type, stack, FALSE, FALSE);
2327 mono_delegate_type_equal (MonoType *target, MonoType *candidate)
2329 if (candidate->byref ^ target->byref)
2332 switch (target->type) {
2333 case MONO_TYPE_VOID:
2336 case MONO_TYPE_BOOLEAN:
2339 case MONO_TYPE_CHAR:
2348 case MONO_TYPE_STRING:
2349 case MONO_TYPE_TYPEDBYREF:
2350 return candidate->type == target->type;
2353 return mono_delegate_type_equal (target->data.type, candidate->data.type);
2355 case MONO_TYPE_FNPTR:
2356 if (candidate->type != MONO_TYPE_FNPTR)
2358 return mono_delegate_signature_equal (mono_type_get_signature (target), mono_type_get_signature (candidate), FALSE);
2360 case MONO_TYPE_GENERICINST: {
2361 MonoClass *target_klass;
2362 MonoClass *candidate_klass;
2363 target_klass = mono_class_from_mono_type (target);
2364 candidate_klass = mono_class_from_mono_type (candidate);
2365 /*FIXME handle nullables and enum*/
2366 return mono_class_is_assignable_from (target_klass, candidate_klass);
2368 case MONO_TYPE_OBJECT:
2369 return MONO_TYPE_IS_REFERENCE (candidate);
2371 case MONO_TYPE_CLASS:
2372 return mono_class_is_assignable_from(target->data.klass, mono_class_from_mono_type (candidate));
2374 case MONO_TYPE_SZARRAY:
2375 if (candidate->type != MONO_TYPE_SZARRAY)
2377 return mono_class_is_assignable_from (mono_class_from_mono_type (target)->element_class, mono_class_from_mono_type (candidate)->element_class);
2379 case MONO_TYPE_ARRAY:
2380 if (candidate->type != MONO_TYPE_ARRAY)
2382 return is_array_type_compatible (target, candidate);
2384 case MONO_TYPE_VALUETYPE:
2385 /*FIXME handle nullables and enum*/
2386 return mono_class_from_mono_type (candidate) == mono_class_from_mono_type (target);
2389 return candidate->type == MONO_TYPE_VAR && mono_type_get_generic_param_num (target) == mono_type_get_generic_param_num (candidate);
2392 case MONO_TYPE_MVAR:
2393 return candidate->type == MONO_TYPE_MVAR && mono_type_get_generic_param_num (target) == mono_type_get_generic_param_num (candidate);
2397 VERIFIER_DEBUG ( printf ("Unknown type %d. Implement me!\n", target->type); );
2398 g_assert_not_reached ();
2404 mono_delegate_param_equal (MonoType *delegate, MonoType *method)
2406 if (mono_metadata_type_equal_full (delegate, method, TRUE))
2409 return mono_delegate_type_equal (method, delegate);
2413 mono_delegate_ret_equal (MonoType *delegate, MonoType *method)
2415 if (mono_metadata_type_equal_full (delegate, method, TRUE))
2418 return mono_delegate_type_equal (delegate, method);
2422 * mono_delegate_signature_equal:
2424 * Compare two signatures in the way expected by delegates.
2426 * This function only exists due to the fact that it should ignore the 'has_this' part of the signature.
2428 * FIXME can this function be eliminated and proper metadata functionality be used?
2431 mono_delegate_signature_equal (MonoMethodSignature *delegate_sig, MonoMethodSignature *method_sig, gboolean is_static_ldftn)
2434 int method_offset = is_static_ldftn ? 1 : 0;
2436 if (delegate_sig->param_count + method_offset != method_sig->param_count)
2439 if (delegate_sig->call_convention != method_sig->call_convention)
2442 for (i = 0; i < delegate_sig->param_count; i++) {
2443 MonoType *p1 = delegate_sig->params [i];
2444 MonoType *p2 = method_sig->params [i + method_offset];
2446 if (!mono_delegate_param_equal (p1, p2))
2450 if (!mono_delegate_ret_equal (delegate_sig->ret, method_sig->ret))
2457 mono_verifier_is_signature_compatible (MonoMethodSignature *target, MonoMethodSignature *candidate)
2459 return mono_delegate_signature_equal (target, candidate, FALSE);
2463 * verify_ldftn_delegate:
2465 * Verify properties of ldftn based delegates.
2468 verify_ldftn_delegate (VerifyContext *ctx, MonoClass *delegate, ILStackDesc *value, ILStackDesc *funptr)
2470 MonoMethod *method = funptr->method;
2472 /*ldftn non-final virtuals only allowed if method is not static,
2473 * the object is a this arg (comes from a ldarg.0), and there is no starg.0.
2474 * This rules doesn't apply if the object on stack is a boxed valuetype.
2476 if ((method->flags & METHOD_ATTRIBUTE_VIRTUAL) && !(method->flags & METHOD_ATTRIBUTE_FINAL) && !(method->klass->flags & TYPE_ATTRIBUTE_SEALED) && !stack_slot_is_boxed_value (value)) {
2477 /*A stdarg 0 must not happen, we fail here only in fail fast mode to avoid double error reports*/
2478 if (IS_FAIL_FAST_MODE (ctx) && ctx->has_this_store)
2479 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid ldftn with virtual function in method with stdarg 0 at 0x%04x", ctx->ip_offset));
2481 /*current method must not be static*/
2482 if (ctx->method->flags & METHOD_ATTRIBUTE_STATIC)
2483 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid ldftn with virtual function at 0x%04x", ctx->ip_offset));
2485 /*value is the this pointer, loaded using ldarg.0 */
2486 if (!stack_slot_is_this_pointer (value))
2487 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid object argument, it is not the this pointer, to ldftn with virtual method at 0x%04x", ctx->ip_offset));
2489 ctx->code [ctx->ip_offset].flags |= IL_CODE_LDFTN_DELEGATE_NONFINAL_VIRTUAL;
2494 * verify_delegate_compatibility:
2496 * Verify delegate creation sequence.
2500 verify_delegate_compatibility (VerifyContext *ctx, MonoClass *delegate, ILStackDesc *value, ILStackDesc *funptr)
2502 #define IS_VALID_OPCODE(offset, opcode) (ip [ip_offset - offset] == opcode && (ctx->code [ip_offset - offset].flags & IL_CODE_FLAG_SEEN))
2503 #define IS_LOAD_FUN_PTR(kind) (IS_VALID_OPCODE (6, CEE_PREFIX1) && ip [ip_offset - 5] == kind)
2505 MonoMethod *invoke, *method;
2506 const guint8 *ip = ctx->header->code;
2507 guint32 ip_offset = ctx->ip_offset;
2508 gboolean is_static_ldftn = FALSE, is_first_arg_bound = FALSE;
2510 if (stack_slot_get_type (funptr) != TYPE_PTR || !funptr->method) {
2511 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid function pointer parameter for delegate constructor at 0x%04x", ctx->ip_offset));
2515 invoke = mono_get_delegate_invoke (delegate);
2516 method = funptr->method;
2518 if (!method || !mono_method_signature (method)) {
2519 char *name = mono_type_get_full_name (delegate);
2520 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid method on stack to create delegate %s construction at 0x%04x", name, ctx->ip_offset));
2525 if (!invoke || !mono_method_signature (invoke)) {
2526 char *name = mono_type_get_full_name (delegate);
2527 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Delegate type %s with bad Invoke method at 0x%04x", name, ctx->ip_offset));
2532 is_static_ldftn = (ip_offset > 5 && IS_LOAD_FUN_PTR (CEE_LDFTN)) && method->flags & METHOD_ATTRIBUTE_STATIC;
2534 if (is_static_ldftn)
2535 is_first_arg_bound = mono_method_signature (invoke)->param_count + 1 == mono_method_signature (method)->param_count;
2537 if (!mono_delegate_signature_equal (mono_method_signature (invoke), mono_method_signature (method), is_first_arg_bound)) {
2538 char *fun_sig = mono_signature_get_desc (mono_method_signature (method), FALSE);
2539 char *invoke_sig = mono_signature_get_desc (mono_method_signature (invoke), FALSE);
2540 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Function pointer signature '%s' doesn't match delegate's signature '%s' at 0x%04x", fun_sig, invoke_sig, ctx->ip_offset));
2542 g_free (invoke_sig);
2546 * Delegate code sequences:
2552 * [-6] ldvirtftn token
2556 if (ip_offset > 5 && IS_LOAD_FUN_PTR (CEE_LDFTN)) {
2557 verify_ldftn_delegate (ctx, delegate, value, funptr);
2558 } else if (ip_offset > 6 && IS_VALID_OPCODE (7, CEE_DUP) && IS_LOAD_FUN_PTR (CEE_LDVIRTFTN)) {
2559 ctx->code [ip_offset - 6].flags |= IL_CODE_DELEGATE_SEQUENCE;
2561 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid code sequence for delegate creation at 0x%04x", ctx->ip_offset));
2563 ctx->code [ip_offset].flags |= IL_CODE_DELEGATE_SEQUENCE;
2566 if (is_first_arg_bound) {
2567 if (mono_method_signature (method)->param_count == 0 || !verify_stack_type_compatibility_full (ctx, mono_method_signature (method)->params [0], value, FALSE, TRUE))
2568 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("This object not compatible with function pointer for delegate creation at 0x%04x", ctx->ip_offset));
2570 if (method->flags & METHOD_ATTRIBUTE_STATIC) {
2571 if (!stack_slot_is_null_literal (value) && !is_first_arg_bound)
2572 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Non-null this args used with static function for delegate creation at 0x%04x", ctx->ip_offset));
2574 if (!verify_stack_type_compatibility_full (ctx, &method->klass->byval_arg, value, FALSE, TRUE) && !stack_slot_is_null_literal (value))
2575 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("This object not compatible with function pointer for delegate creation at 0x%04x", ctx->ip_offset));
2579 if (stack_slot_get_type (value) != TYPE_COMPLEX)
2580 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid first parameter for delegate creation at 0x%04x", ctx->ip_offset));
2582 #undef IS_VALID_OPCODE
2583 #undef IS_LOAD_FUN_PTR
2586 /* implement the opcode checks*/
2588 push_arg (VerifyContext *ctx, unsigned int arg, int take_addr)
2592 if (arg >= ctx->max_args) {
2594 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Method doesn't have argument %d", arg + 1));
2596 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Method doesn't have argument %d", arg + 1));
2597 if (check_overflow (ctx)) //FIXME: what sane value could we ever push?
2598 stack_push_val (ctx, TYPE_I4, &mono_defaults.int32_class->byval_arg);
2600 } else if (check_overflow (ctx)) {
2601 /*We must let the value be pushed, otherwise we would get an underflow error*/
2602 check_unverifiable_type (ctx, ctx->params [arg]);
2603 if (ctx->params [arg]->byref && take_addr)
2604 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("ByRef of ByRef at 0x%04x", ctx->ip_offset));
2605 top = stack_push (ctx);
2606 if (!set_stack_value (ctx, top, ctx->params [arg], take_addr))
2609 if (arg == 0 && !(ctx->method->flags & METHOD_ATTRIBUTE_STATIC)) {
2611 ctx->has_this_store = TRUE;
2613 top->stype |= THIS_POINTER_MASK;
2614 if (mono_method_is_constructor (ctx->method) && !ctx->super_ctor_called && !ctx->method->klass->valuetype)
2615 top->stype |= UNINIT_THIS_MASK;
2621 push_local (VerifyContext *ctx, guint32 arg, int take_addr)
2623 if (arg >= ctx->num_locals) {
2624 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Method doesn't have local %d", arg + 1));
2625 } else if (check_overflow (ctx)) {
2626 /*We must let the value be pushed, otherwise we would get an underflow error*/
2627 check_unverifiable_type (ctx, ctx->locals [arg]);
2628 if (ctx->locals [arg]->byref && take_addr)
2629 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("ByRef of ByRef at 0x%04x", ctx->ip_offset));
2631 set_stack_value (ctx, stack_push (ctx), ctx->locals [arg], take_addr);
2636 store_arg (VerifyContext *ctx, guint32 arg)
2640 if (arg >= ctx->max_args) {
2641 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Method doesn't have argument %d at 0x%04x", arg + 1, ctx->ip_offset));
2642 if (check_underflow (ctx, 1))
2647 if (check_underflow (ctx, 1)) {
2648 value = stack_pop (ctx);
2649 if (!verify_stack_type_compatibility (ctx, ctx->params [arg], value)) {
2650 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Incompatible type %s in argument store at 0x%04x", stack_slot_get_name (value), ctx->ip_offset));
2653 if (arg == 0 && !(ctx->method->flags & METHOD_ATTRIBUTE_STATIC))
2654 ctx->has_this_store = 1;
2658 store_local (VerifyContext *ctx, guint32 arg)
2661 if (arg >= ctx->num_locals) {
2662 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Method doesn't have local var %d at 0x%04x", arg + 1, ctx->ip_offset));
2666 /*TODO verify definite assigment */
2667 if (check_underflow (ctx, 1)) {
2668 value = stack_pop(ctx);
2669 if (!verify_stack_type_compatibility (ctx, ctx->locals [arg], value)) {
2670 char *expected = mono_type_full_name (ctx->locals [arg]);
2671 char *found = stack_slot_full_name (value);
2672 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Incompatible type '%s' on stack cannot be stored to local %d with type '%s' at 0x%04x",
2683 /*FIXME add and sub needs special care here*/
2685 do_binop (VerifyContext *ctx, unsigned int opcode, const unsigned char table [TYPE_MAX][TYPE_MAX])
2687 ILStackDesc *a, *b, *top;
2688 int idxa, idxb, complexMerge = 0;
2691 if (!check_underflow (ctx, 2))
2693 b = stack_pop (ctx);
2694 a = stack_pop (ctx);
2696 idxa = stack_slot_get_underlying_type (a);
2697 if (stack_slot_is_managed_pointer (a)) {
2702 idxb = stack_slot_get_underlying_type (b);
2703 if (stack_slot_is_managed_pointer (b)) {
2710 res = table [idxa][idxb];
2712 VERIFIER_DEBUG ( printf ("binop res %d\n", res); );
2713 VERIFIER_DEBUG ( printf ("idxa %d idxb %d\n", idxa, idxb); );
2715 top = stack_push (ctx);
2716 if (res == TYPE_INV) {
2717 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)));
2718 copy_stack_value (top, a);
2722 if (res & NON_VERIFIABLE_RESULT) {
2723 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)));
2725 res = res & ~NON_VERIFIABLE_RESULT;
2728 if (complexMerge && res == TYPE_PTR) {
2729 if (complexMerge == 1)
2730 copy_stack_value (top, a);
2731 else if (complexMerge == 2)
2732 copy_stack_value (top, b);
2734 * There is no need to merge the type of two pointers.
2735 * The only valid operation is subtraction, that returns a native
2736 * int as result and can be used with any 2 pointer kinds.
2737 * This is valid acording to Patition III 1.1.4
2746 do_boolean_branch_op (VerifyContext *ctx, int delta)
2748 int target = ctx->ip_offset + delta;
2751 VERIFIER_DEBUG ( printf ("boolean branch offset %d delta %d target %d\n", ctx->ip_offset, delta, target); );
2753 if (target < 0 || target >= ctx->code_size) {
2754 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Boolean branch target out of code at 0x%04x", ctx->ip_offset));
2758 switch (is_valid_branch_instruction (ctx->header, ctx->ip_offset, target)) {
2760 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Branch target escapes out of exception block at 0x%04x", ctx->ip_offset));
2763 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Branch target escapes out of exception block at 0x%04x", ctx->ip_offset));
2767 ctx->target = target;
2769 if (!check_underflow (ctx, 1))
2772 top = stack_pop (ctx);
2773 if (!is_valid_bool_arg (top))
2774 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));
2776 check_unmanaged_pointer (ctx, top);
2780 stack_slot_is_complex_type_not_reference_type (ILStackDesc *slot)
2782 return stack_slot_get_type (slot) == TYPE_COMPLEX && !MONO_TYPE_IS_REFERENCE (slot->type) && !stack_slot_is_boxed_value (slot);
2786 do_branch_op (VerifyContext *ctx, signed int delta, const unsigned char table [TYPE_MAX][TYPE_MAX])
2791 int target = ctx->ip_offset + delta;
2793 VERIFIER_DEBUG ( printf ("branch offset %d delta %d target %d\n", ctx->ip_offset, delta, target); );
2795 if (target < 0 || target >= ctx->code_size) {
2796 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Branch target out of code at 0x%04x", ctx->ip_offset));
2800 switch (is_valid_cmp_branch_instruction (ctx->header, ctx->ip_offset, target)) {
2801 case 1: /*FIXME use constants and not magic numbers.*/
2802 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Branch target escapes out of exception block at 0x%04x", ctx->ip_offset));
2805 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Branch target escapes out of exception block at 0x%04x", ctx->ip_offset));
2809 ctx->target = target;
2811 if (!check_underflow (ctx, 2))
2814 b = stack_pop (ctx);
2815 a = stack_pop (ctx);
2817 idxa = stack_slot_get_underlying_type (a);
2818 if (stack_slot_is_managed_pointer (a))
2821 idxb = stack_slot_get_underlying_type (b);
2822 if (stack_slot_is_managed_pointer (b))
2825 if (stack_slot_is_complex_type_not_reference_type (a) || stack_slot_is_complex_type_not_reference_type (b)) {
2830 res = table [idxa][idxb];
2833 VERIFIER_DEBUG ( printf ("branch res %d\n", res); );
2834 VERIFIER_DEBUG ( printf ("idxa %d idxb %d\n", idxa, idxb); );
2836 if (res == TYPE_INV) {
2837 CODE_NOT_VERIFIABLE (ctx,
2838 g_strdup_printf ("Compare and Branch instruction applyed to ill formed stack (%s x %s) at 0x%04x", stack_slot_get_name (a), stack_slot_get_name (b), ctx->ip_offset));
2839 } else if (res & NON_VERIFIABLE_RESULT) {
2840 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Compare and Branch instruction is not verifiable (%s x %s) at 0x%04x", stack_slot_get_name (a), stack_slot_get_name (b), ctx->ip_offset));
2841 res = res & ~NON_VERIFIABLE_RESULT;
2846 do_cmp_op (VerifyContext *ctx, const unsigned char table [TYPE_MAX][TYPE_MAX], guint32 opcode)
2852 if (!check_underflow (ctx, 2))
2854 b = stack_pop (ctx);
2855 a = stack_pop (ctx);
2857 if (opcode == CEE_CGT_UN) {
2858 if (stack_slot_get_type (a) == TYPE_COMPLEX && stack_slot_get_type (b) == TYPE_COMPLEX) {
2859 stack_push_val (ctx, TYPE_I4, &mono_defaults.int32_class->byval_arg);
2864 idxa = stack_slot_get_underlying_type (a);
2865 if (stack_slot_is_managed_pointer (a))
2868 idxb = stack_slot_get_underlying_type (b);
2869 if (stack_slot_is_managed_pointer (b))
2872 if (stack_slot_is_complex_type_not_reference_type (a) || stack_slot_is_complex_type_not_reference_type (b)) {
2877 res = table [idxa][idxb];
2880 if(res == TYPE_INV) {
2881 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));
2882 } else if (res & NON_VERIFIABLE_RESULT) {
2883 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Compare instruction is not verifiable (%s x %s) at 0x%04x", stack_slot_get_name (a), stack_slot_get_name (b), ctx->ip_offset));
2884 res = res & ~NON_VERIFIABLE_RESULT;
2886 stack_push_val (ctx, TYPE_I4, &mono_defaults.int32_class->byval_arg);
2890 do_ret (VerifyContext *ctx)
2892 MonoType *ret = ctx->signature->ret;
2893 VERIFIER_DEBUG ( printf ("checking ret\n"); );
2894 if (ret->type != MONO_TYPE_VOID) {
2896 if (!check_underflow (ctx, 1))
2899 top = stack_pop(ctx);
2901 if (!verify_stack_type_compatibility (ctx, ctx->signature->ret, top)) {
2902 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Incompatible return value on stack with method signature ret at 0x%04x", ctx->ip_offset));
2906 if (ret->byref || ret->type == MONO_TYPE_TYPEDBYREF || mono_type_is_value_type (ret, "System", "ArgIterator") || mono_type_is_value_type (ret, "System", "RuntimeArgumentHandle"))
2907 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Method returns byref, TypedReference, ArgIterator or RuntimeArgumentHandle at 0x%04x", ctx->ip_offset));
2910 if (ctx->eval.size > 0) {
2911 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Stack not empty (%d) after ret at 0x%04x", ctx->eval.size, ctx->ip_offset));
2913 if (in_any_block (ctx->header, ctx->ip_offset))
2914 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("ret cannot escape exception blocks at 0x%04x", ctx->ip_offset));
2918 * 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.
2919 * This is illegal but mono_get_method_full decoded it.
2920 * TODO handle calling .ctor outside one or calling the .ctor for other class but super
2923 do_invoke_method (VerifyContext *ctx, int method_token, gboolean virtual)
2926 MonoMethodSignature *sig;
2929 gboolean virt_check_this = FALSE;
2930 gboolean constrained = ctx->prefix_set & PREFIX_CONSTRAINED;
2932 if (!(method = verifier_load_method (ctx, method_token, virtual ? "callvirt" : "call")))
2936 CLEAR_PREFIX (ctx, PREFIX_CONSTRAINED);
2938 if (method->klass->valuetype) // && !constrained ???
2939 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use callvirtual with valuetype method at 0x%04x", ctx->ip_offset));
2941 if ((method->flags & METHOD_ATTRIBUTE_STATIC))
2942 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use callvirtual with static method at 0x%04x", ctx->ip_offset));
2945 if (method->flags & METHOD_ATTRIBUTE_ABSTRACT)
2946 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use call with an abstract method at 0x%04x", ctx->ip_offset));
2948 if ((method->flags & METHOD_ATTRIBUTE_VIRTUAL) && !(method->flags & METHOD_ATTRIBUTE_FINAL) && !(method->klass->flags & TYPE_ATTRIBUTE_SEALED)) {
2949 virt_check_this = TRUE;
2950 ctx->code [ctx->ip_offset].flags |= IL_CODE_CALL_NONFINAL_VIRTUAL;
2954 if (!(sig = mono_method_get_signature_full (method, ctx->image, method_token, ctx->generic_context)))
2955 sig = mono_method_get_signature (method, ctx->image, method_token);
2958 char *name = mono_type_get_full_name (method->klass);
2959 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Could not resolve signature of %s:%s at 0x%04x", name, method->name, ctx->ip_offset));
2964 param_count = sig->param_count + sig->hasthis;
2965 if (!check_underflow (ctx, param_count))
2968 for (i = sig->param_count - 1; i >= 0; --i) {
2969 VERIFIER_DEBUG ( printf ("verifying argument %d\n", i); );
2970 value = stack_pop (ctx);
2971 if (!verify_stack_type_compatibility (ctx, sig->params[i], value)) {
2972 char *stack_name = stack_slot_full_name (value);
2973 char *sig_name = mono_type_full_name (sig->params [i]);
2974 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Incompatible parameter with function signature: Calling method with signature (%s) but for argument %d there is a (%s) on stack at 0x%04x", sig_name, i, stack_name, ctx->ip_offset));
2975 g_free (stack_name);
2979 if (stack_slot_is_managed_mutability_pointer (value))
2980 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));
2982 if ((ctx->prefix_set & PREFIX_TAIL) && stack_slot_is_managed_pointer (value)) {
2983 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));
2989 MonoType *type = &method->klass->byval_arg;
2992 if (mono_method_is_constructor (method) && !method->klass->valuetype) {
2993 if (!mono_method_is_constructor (ctx->method))
2994 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot call a constructor outside one at 0x%04x", ctx->ip_offset));
2995 if (method->klass != ctx->method->klass->parent && method->klass != ctx->method->klass)
2996 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));
2998 ctx->super_ctor_called = TRUE;
2999 value = stack_pop_safe (ctx);
3000 if ((value->stype & THIS_POINTER_MASK) != THIS_POINTER_MASK)
3001 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid 'this ptr' argument for constructor at 0x%04x", ctx->ip_offset));
3003 value = stack_pop (ctx);
3006 copy_stack_value (©, value);
3007 //TODO we should extract this to a 'drop_byref_argument' and use everywhere
3008 //Other parts of the code suffer from the same issue of
3009 copy.type = mono_type_get_type_byval (copy.type);
3010 copy.stype &= ~POINTER_MASK;
3012 if (virt_check_this && !stack_slot_is_this_pointer (value) && !(method->klass->valuetype || stack_slot_is_boxed_value (value)))
3013 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use the call opcode with a non-final virtual method on an object diferent thant the this pointer at 0x%04x", ctx->ip_offset));
3015 if (constrained && virtual) {
3016 if (!stack_slot_is_managed_pointer (value))
3017 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Object is not a managed pointer for a constrained call at 0x%04x", ctx->ip_offset));
3018 if (!mono_metadata_type_equal_full (mono_type_get_type_byval (value->type), ctx->constrained_type, TRUE))
3019 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Object not compatible with constrained type at 0x%04x", ctx->ip_offset));
3020 copy.stype |= BOXED_MASK;
3022 if (stack_slot_is_managed_pointer (value) && !mono_class_from_mono_type (value->type)->valuetype)
3023 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));
3025 if (!virtual && mono_class_from_mono_type (value->type)->valuetype && !method->klass->valuetype && !stack_slot_is_boxed_value (value))
3026 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot call a valuetype baseclass at 0x%04x", ctx->ip_offset));
3028 if (virtual && mono_class_from_mono_type (value->type)->valuetype && !stack_slot_is_boxed_value (value))
3029 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use a valuetype with callvirt at 0x%04x", ctx->ip_offset));
3031 if (method->klass->valuetype && (stack_slot_is_boxed_value (value) || !stack_slot_is_managed_pointer (value)))
3032 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));
3034 if (!verify_stack_type_compatibility (ctx, type, ©)) {
3035 char *expected = mono_type_full_name (type);
3036 char *effective = stack_slot_full_name (©);
3037 char *method_name = mono_method_full_name (method, TRUE);
3038 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Incompatible this argument on stack with method signature expected '%s' but got '%s' for a call to '%s' at 0x%04x",
3039 expected, effective, method_name, ctx->ip_offset));
3040 g_free (method_name);
3045 if (!IS_SKIP_VISIBILITY (ctx) && !mono_method_can_access_method_full (ctx->method, method, mono_class_from_mono_type (value->type))) {
3046 char *name = mono_method_full_name (method, TRUE);
3047 CODE_NOT_VERIFIABLE2 (ctx, g_strdup_printf ("Method %s is not accessible at 0x%04x", name, ctx->ip_offset), MONO_EXCEPTION_METHOD_ACCESS);
3051 } else if (!IS_SKIP_VISIBILITY (ctx) && !mono_method_can_access_method_full (ctx->method, method, NULL)) {
3052 char *name = mono_method_full_name (method, TRUE);
3053 CODE_NOT_VERIFIABLE2 (ctx, g_strdup_printf ("Method %s is not accessible at 0x%04x", name, ctx->ip_offset), MONO_EXCEPTION_METHOD_ACCESS);
3057 if (sig->ret->type != MONO_TYPE_VOID) {
3058 if (check_overflow (ctx)) {
3059 value = stack_push (ctx);
3060 set_stack_value (ctx, value, sig->ret, FALSE);
3061 if ((ctx->prefix_set & PREFIX_READONLY) && method->klass->rank && !strcmp (method->name, "Address")) {
3062 ctx->prefix_set &= ~PREFIX_READONLY;
3063 value->stype |= CMMP_MASK;
3068 if ((ctx->prefix_set & PREFIX_TAIL)) {
3069 if (!mono_delegate_ret_equal (mono_method_signature (ctx->method)->ret, sig->ret))
3070 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Tail call with incompatible return type at 0x%04x", ctx->ip_offset));
3071 if (ctx->header->code [ctx->ip_offset + 5] != CEE_RET)
3072 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Tail call not followed by ret at 0x%04x", ctx->ip_offset));
3078 do_push_static_field (VerifyContext *ctx, int token, gboolean take_addr)
3080 MonoClassField *field;
3082 if (!check_overflow (ctx))
3085 CLEAR_PREFIX (ctx, PREFIX_VOLATILE);
3087 if (!(field = verifier_load_field (ctx, token, &klass, take_addr ? "ldsflda" : "ldsfld")))
3090 if (!(field->type->attrs & FIELD_ATTRIBUTE_STATIC)) {
3091 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Cannot load non static field at 0x%04x", ctx->ip_offset));
3094 /*taking the address of initonly field only works from the static constructor */
3095 if (take_addr && (field->type->attrs & FIELD_ATTRIBUTE_INIT_ONLY) &&
3096 !(field->parent == ctx->method->klass && (ctx->method->flags & (METHOD_ATTRIBUTE_SPECIAL_NAME | METHOD_ATTRIBUTE_STATIC)) && !strcmp (".cctor", ctx->method->name)))
3097 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot take the address of a init-only field at 0x%04x", ctx->ip_offset));
3099 if (!IS_SKIP_VISIBILITY (ctx) && !mono_method_can_access_field_full (ctx->method, field, NULL))
3100 CODE_NOT_VERIFIABLE2 (ctx, g_strdup_printf ("Type at stack is not accessible at 0x%04x", ctx->ip_offset), MONO_EXCEPTION_FIELD_ACCESS);
3102 set_stack_value (ctx, stack_push (ctx), field->type, take_addr);
3106 do_store_static_field (VerifyContext *ctx, int token) {
3107 MonoClassField *field;
3110 CLEAR_PREFIX (ctx, PREFIX_VOLATILE);
3112 if (!check_underflow (ctx, 1))
3115 value = stack_pop (ctx);
3117 if (!(field = verifier_load_field (ctx, token, &klass, "stsfld")))
3120 if (!(field->type->attrs & FIELD_ATTRIBUTE_STATIC)) {
3121 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Cannot store non static field at 0x%04x", ctx->ip_offset));
3125 if (field->type->type == MONO_TYPE_TYPEDBYREF) {
3126 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Typedbyref field is an unverfiable type in store static field at 0x%04x", ctx->ip_offset));
3130 if (!IS_SKIP_VISIBILITY (ctx) && !mono_method_can_access_field_full (ctx->method, field, NULL))
3131 CODE_NOT_VERIFIABLE2 (ctx, g_strdup_printf ("Type at stack is not accessible at 0x%04x", ctx->ip_offset), MONO_EXCEPTION_FIELD_ACCESS);
3133 if (!verify_stack_type_compatibility (ctx, field->type, value)) {
3134 char *stack_name = stack_slot_full_name (value);
3135 char *field_name = mono_type_full_name (field->type);
3136 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Incompatible type in static field store expected '%s' but found '%s' at 0x%04x",
3137 field_name, stack_name, ctx->ip_offset));
3138 g_free (field_name);
3139 g_free (stack_name);
3144 check_is_valid_type_for_field_ops (VerifyContext *ctx, int token, ILStackDesc *obj, MonoClassField **ret_field, const char *opcode)
3146 MonoClassField *field;
3148 gboolean is_pointer;
3150 /*must be a reference type, a managed pointer, an unamanaged pointer, or a valuetype*/
3151 if (!(field = verifier_load_field (ctx, token, &klass, opcode)))
3155 //the value on stack is going to be used as a pointer
3156 is_pointer = stack_slot_get_type (obj) == TYPE_PTR || (stack_slot_get_type (obj) == TYPE_NATIVE_INT && !get_stack_type (&field->parent->byval_arg));
3158 if (field->type->type == MONO_TYPE_TYPEDBYREF) {
3159 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Typedbyref field is an unverfiable type at 0x%04x", ctx->ip_offset));
3162 g_assert (obj->type);
3164 /*The value on the stack must be a subclass of the defining type of the field*/
3165 /* we need to check if we can load the field from the stack value*/
3167 if (stack_slot_get_underlying_type (obj) == TYPE_NATIVE_INT)
3168 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Native int is not a verifiable type to reference a field at 0x%04x", ctx->ip_offset));
3170 if (!IS_SKIP_VISIBILITY (ctx) && !mono_method_can_access_field_full (ctx->method, field, NULL))
3171 CODE_NOT_VERIFIABLE2 (ctx, g_strdup_printf ("Type at stack is not accessible at 0x%04x", ctx->ip_offset), MONO_EXCEPTION_FIELD_ACCESS);
3173 if (!field->parent->valuetype && stack_slot_is_managed_pointer (obj))
3174 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));
3176 /*a value type can be loaded from a value or a managed pointer, but not a boxed object*/
3177 if (field->parent->valuetype && stack_slot_is_boxed_value (obj))
3178 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));
3180 if (!stack_slot_is_null_literal (obj) && !verify_stack_type_compatibility_full (ctx, &field->parent->byval_arg, obj, TRUE, FALSE)) {
3181 char *found = stack_slot_full_name (obj);
3182 char *expected = mono_type_full_name (&field->parent->byval_arg);
3183 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Expected type '%s' but found '%s' referencing the 'this' argument at 0x%04x", expected, found, ctx->ip_offset));
3188 if (!IS_SKIP_VISIBILITY (ctx) && !mono_method_can_access_field_full (ctx->method, field, mono_class_from_mono_type (obj->type)))
3189 CODE_NOT_VERIFIABLE2 (ctx, g_strdup_printf ("Type at stack is not accessible at 0x%04x", ctx->ip_offset), MONO_EXCEPTION_FIELD_ACCESS);
3192 check_unmanaged_pointer (ctx, obj);
3197 do_push_field (VerifyContext *ctx, int token, gboolean take_addr)
3200 MonoClassField *field;
3203 CLEAR_PREFIX (ctx, PREFIX_UNALIGNED | PREFIX_VOLATILE);
3205 if (!check_underflow (ctx, 1))
3207 obj = stack_pop_safe (ctx);
3209 if (!check_is_valid_type_for_field_ops (ctx, token, obj, &field, take_addr ? "ldflda" : "ldfld"))
3212 if (take_addr && field->parent->valuetype && !stack_slot_is_managed_pointer (obj))
3213 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot take the address of a temporary value-type at 0x%04x", ctx->ip_offset));
3215 if (take_addr && (field->type->attrs & FIELD_ATTRIBUTE_INIT_ONLY) &&
3216 !(field->parent == ctx->method->klass && mono_method_is_constructor (ctx->method)))
3217 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot take the address of a init-only field at 0x%04x", ctx->ip_offset));
3219 set_stack_value (ctx, stack_push (ctx), field->type, take_addr);
3223 do_store_field (VerifyContext *ctx, int token)
3225 ILStackDesc *value, *obj;
3226 MonoClassField *field;
3227 CLEAR_PREFIX (ctx, PREFIX_UNALIGNED | PREFIX_VOLATILE);
3229 if (!check_underflow (ctx, 2))
3232 value = stack_pop (ctx);
3233 obj = stack_pop_safe (ctx);
3235 if (!check_is_valid_type_for_field_ops (ctx, token, obj, &field, "stfld"))
3238 if (!verify_stack_type_compatibility (ctx, field->type, value))
3239 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Incompatible type %s in field store at 0x%04x", stack_slot_get_name (value), ctx->ip_offset));
3242 /*TODO proper handle for Nullable<T>*/
3244 do_box_value (VerifyContext *ctx, int klass_token)
3247 MonoType *type = get_boxable_mono_type (ctx, klass_token, "box");
3253 if (!check_underflow (ctx, 1))
3256 value = stack_pop (ctx);
3257 /*box is a nop for reference types*/
3259 if (stack_slot_get_underlying_type (value) == TYPE_COMPLEX && MONO_TYPE_IS_REFERENCE (value->type) && MONO_TYPE_IS_REFERENCE (type)) {
3260 stack_push_stack_val (ctx, value)->stype |= BOXED_MASK;
3265 if (!verify_stack_type_compatibility (ctx, type, value))
3266 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid type at stack for boxing operation at 0x%04x", ctx->ip_offset));
3268 klass = mono_class_from_mono_type (type);
3269 if (mono_class_is_nullable (klass))
3270 type = &mono_class_get_nullable_param (klass)->byval_arg;
3271 stack_push_val (ctx, TYPE_COMPLEX | BOXED_MASK, type);
3275 do_unbox_value (VerifyContext *ctx, int klass_token)
3278 MonoType *type = get_boxable_mono_type (ctx, klass_token, "unbox");
3283 if (!check_underflow (ctx, 1))
3286 if (!mono_class_from_mono_type (type)->valuetype)
3287 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid reference type for unbox at 0x%04x", ctx->ip_offset));
3289 value = stack_pop (ctx);
3291 /*Value should be: a boxed valuetype or a reference type*/
3292 if (!(stack_slot_get_type (value) == TYPE_COMPLEX &&
3293 (stack_slot_is_boxed_value (value) || !mono_class_from_mono_type (value->type)->valuetype)))
3294 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid type %s at stack for unbox operation at 0x%04x", stack_slot_get_name (value), ctx->ip_offset));
3296 set_stack_value (ctx, value = stack_push (ctx), mono_type_get_type_byref (type), FALSE);
3297 value->stype |= CMMP_MASK;
3301 do_unbox_any (VerifyContext *ctx, int klass_token)
3304 MonoType *type = get_boxable_mono_type (ctx, klass_token, "unbox.any");
3309 if (!check_underflow (ctx, 1))
3312 value = stack_pop (ctx);
3314 /*Value should be: a boxed valuetype or a reference type*/
3315 if (!(stack_slot_get_type (value) == TYPE_COMPLEX &&
3316 (stack_slot_is_boxed_value (value) || !mono_class_from_mono_type (value->type)->valuetype)))
3317 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid type %s at stack for unbox.any operation at 0x%04x", stack_slot_get_name (value), ctx->ip_offset));
3319 set_stack_value (ctx, stack_push (ctx), type, FALSE);
3323 do_unary_math_op (VerifyContext *ctx, int op)
3326 if (!check_underflow (ctx, 1))
3328 value = stack_pop (ctx);
3329 switch (stack_slot_get_type (value)) {
3332 case TYPE_NATIVE_INT:
3337 case TYPE_COMPLEX: /*only enums are ok*/
3338 if (mono_type_is_enum_type (value->type))
3341 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid type at stack for unary not at 0x%04x", ctx->ip_offset));
3343 stack_push_stack_val (ctx, value);
3347 do_conversion (VerifyContext *ctx, int kind)
3350 if (!check_underflow (ctx, 1))
3352 value = stack_pop (ctx);
3354 switch (stack_slot_get_type (value)) {
3357 case TYPE_NATIVE_INT:
3361 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));
3366 stack_push_val (ctx, TYPE_I4, &mono_defaults.int32_class->byval_arg);
3369 stack_push_val (ctx,TYPE_I8, &mono_defaults.int64_class->byval_arg);
3372 stack_push_val (ctx, TYPE_R8, &mono_defaults.double_class->byval_arg);
3374 case TYPE_NATIVE_INT:
3375 stack_push_val (ctx, TYPE_NATIVE_INT, &mono_defaults.int_class->byval_arg);
3378 g_error ("unknown type %02x in conversion", kind);
3384 do_load_token (VerifyContext *ctx, int token)
3387 MonoClass *handle_class;
3388 if (!check_overflow (ctx))
3391 switch (token & 0xff000000) {
3392 case MONO_TOKEN_TYPE_DEF:
3393 case MONO_TOKEN_TYPE_REF:
3394 case MONO_TOKEN_TYPE_SPEC:
3395 case MONO_TOKEN_FIELD_DEF:
3396 case MONO_TOKEN_METHOD_DEF:
3397 case MONO_TOKEN_METHOD_SPEC:
3398 case MONO_TOKEN_MEMBER_REF:
3399 if (!token_bounds_check (ctx->image, token)) {
3400 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Table index out of range 0x%x for token %x for ldtoken at 0x%04x", mono_metadata_token_index (token), token, ctx->ip_offset));
3405 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid table 0x%x for token 0x%x for ldtoken at 0x%04x", mono_metadata_token_table (token), token, ctx->ip_offset));
3409 handle = mono_ldtoken (ctx->image, token, &handle_class, ctx->generic_context);
3411 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid token 0x%x for ldtoken at 0x%04x", token, ctx->ip_offset));
3414 if (handle_class == mono_defaults.typehandle_class) {
3415 mono_type_is_valid_in_context (ctx, (MonoType*)handle);
3416 } else if (handle_class == mono_defaults.methodhandle_class) {
3417 mono_method_is_valid_in_context (ctx, (MonoMethod*)handle);
3418 } else if (handle_class == mono_defaults.fieldhandle_class) {
3419 mono_type_is_valid_in_context (ctx, &((MonoClassField*)handle)->parent->byval_arg);
3421 ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid ldtoken type %x at 0x%04x", token, ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE);
3423 stack_push_val (ctx, TYPE_COMPLEX, mono_class_get_type (handle_class));
3427 do_ldobj_value (VerifyContext *ctx, int token)
3430 MonoType *type = get_boxable_mono_type (ctx, token, "ldobj");
3431 CLEAR_PREFIX (ctx, PREFIX_UNALIGNED | PREFIX_VOLATILE);
3436 if (!check_underflow (ctx, 1))
3439 value = stack_pop (ctx);
3440 if (!stack_slot_is_managed_pointer (value)
3441 && stack_slot_get_type (value) != TYPE_NATIVE_INT
3442 && !(stack_slot_get_type (value) == TYPE_PTR && value->type->type != MONO_TYPE_FNPTR)) {
3443 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid argument %s to ldobj at 0x%04x", stack_slot_get_name (value), ctx->ip_offset));
3447 if (stack_slot_get_type (value) == TYPE_NATIVE_INT)
3448 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Using native pointer to ldobj at 0x%04x", ctx->ip_offset));
3450 /*We have a byval on the stack, but the comparison must be strict. */
3451 if (!verify_type_compatibility_full (ctx, type, mono_type_get_type_byval (value->type), TRUE))
3452 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid type at stack for ldojb operation at 0x%04x", ctx->ip_offset));
3454 set_stack_value (ctx, stack_push (ctx), type, FALSE);
3458 do_stobj (VerifyContext *ctx, int token)
3460 ILStackDesc *dest, *src;
3461 MonoType *type = get_boxable_mono_type (ctx, token, "stobj");
3462 CLEAR_PREFIX (ctx, PREFIX_UNALIGNED | PREFIX_VOLATILE);
3467 if (!check_underflow (ctx, 2))
3470 src = stack_pop (ctx);
3471 dest = stack_pop (ctx);
3473 if (stack_slot_is_managed_mutability_pointer (dest))
3474 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use a readonly pointer with stobj at 0x%04x", ctx->ip_offset));
3476 if (!stack_slot_is_managed_pointer (dest))
3477 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid destination of stobj operation at 0x%04x", ctx->ip_offset));
3479 if (stack_slot_is_boxed_value (src) && !MONO_TYPE_IS_REFERENCE (src->type) && !MONO_TYPE_IS_REFERENCE (type))
3480 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));
3482 if (!verify_stack_type_compatibility (ctx, type, src)) {
3483 char *type_name = mono_type_full_name (type);
3484 char *src_name = stack_slot_full_name (src);
3485 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Token '%s' and source '%s' of stobj don't match ' at 0x%04x", type_name, src_name, ctx->ip_offset));
3490 if (!verify_type_compatibility (ctx, mono_type_get_type_byval (dest->type), type))
3491 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Destination and token types of stobj don't match at 0x%04x", ctx->ip_offset));
3495 do_cpobj (VerifyContext *ctx, int token)
3497 ILStackDesc *dest, *src;
3498 MonoType *type = get_boxable_mono_type (ctx, token, "cpobj");
3502 if (!check_underflow (ctx, 2))
3505 src = stack_pop (ctx);
3506 dest = stack_pop (ctx);
3508 if (!stack_slot_is_managed_pointer (src))
3509 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid source of cpobj operation at 0x%04x", ctx->ip_offset));
3511 if (!stack_slot_is_managed_pointer (dest))
3512 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid destination of cpobj operation at 0x%04x", ctx->ip_offset));
3514 if (stack_slot_is_managed_mutability_pointer (dest))
3515 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use a readonly pointer with cpobj at 0x%04x", ctx->ip_offset));
3517 if (!verify_type_compatibility (ctx, type, mono_type_get_type_byval (src->type)))
3518 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Token and source types of cpobj don't match at 0x%04x", ctx->ip_offset));
3520 if (!verify_type_compatibility (ctx, mono_type_get_type_byval (dest->type), type))
3521 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Destination and token types of cpobj don't match at 0x%04x", ctx->ip_offset));
3525 do_initobj (VerifyContext *ctx, int token)
3528 MonoType *stack, *type = get_boxable_mono_type (ctx, token, "initobj");
3532 if (!check_underflow (ctx, 1))
3535 obj = stack_pop (ctx);
3537 if (!stack_slot_is_managed_pointer (obj))
3538 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid object address for initobj at 0x%04x", ctx->ip_offset));
3540 if (stack_slot_is_managed_mutability_pointer (obj))
3541 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use a readonly pointer with initobj at 0x%04x", ctx->ip_offset));
3543 stack = mono_type_get_type_byval (obj->type);
3544 if (MONO_TYPE_IS_REFERENCE (stack)) {
3545 if (!verify_type_compatibility (ctx, stack, type))
3546 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Type token of initobj not compatible with value on stack at 0x%04x", ctx->ip_offset));
3547 else if (IS_STRICT_MODE (ctx) && !mono_metadata_type_equal (type, stack))
3548 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Type token of initobj not compatible with value on stack at 0x%04x", ctx->ip_offset));
3549 } else if (!verify_type_compatibility (ctx, stack, type)) {
3550 char *expected_name = mono_type_full_name (type);
3551 char *stack_name = mono_type_full_name (stack);
3553 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Initobj %s not compatible with value on stack %s at 0x%04x", expected_name, stack_name, ctx->ip_offset));
3554 g_free (expected_name);
3555 g_free (stack_name);
3560 do_newobj (VerifyContext *ctx, int token)
3564 MonoMethodSignature *sig;
3566 gboolean is_delegate = FALSE;
3568 if (!(method = verifier_load_method (ctx, token, "newobj")))
3571 if (!mono_method_is_constructor (method)) {
3572 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Method from token 0x%08x not a constructor at 0x%04x", token, ctx->ip_offset));
3576 if (method->klass->flags & (TYPE_ATTRIBUTE_ABSTRACT | TYPE_ATTRIBUTE_INTERFACE))
3577 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Trying to instantiate an abstract or interface type at 0x%04x", ctx->ip_offset));
3579 if (!mono_method_can_access_method_full (ctx->method, method, NULL)) {
3580 char *from = mono_method_full_name (ctx->method, TRUE);
3581 char *to = mono_method_full_name (method, TRUE);
3582 CODE_NOT_VERIFIABLE2 (ctx, g_strdup_printf ("Constructor %s not visible from %s at 0x%04x", to, from, ctx->ip_offset), MONO_EXCEPTION_METHOD_ACCESS);
3587 //FIXME use mono_method_get_signature_full
3588 sig = mono_method_signature (method);
3590 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid constructor signature to newobj at 0x%04x", ctx->ip_offset));
3594 if (!sig->hasthis) {
3595 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid constructor signature missing hasthis at 0x%04x", ctx->ip_offset));
3599 if (!check_underflow (ctx, sig->param_count))
3602 is_delegate = method->klass->parent == mono_defaults.multicastdelegate_class;
3605 ILStackDesc *funptr;
3606 //first arg is object, second arg is fun ptr
3607 if (sig->param_count != 2) {
3608 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid delegate constructor at 0x%04x", ctx->ip_offset));
3611 funptr = stack_pop (ctx);
3612 value = stack_pop (ctx);
3613 verify_delegate_compatibility (ctx, method->klass, value, funptr);
3615 for (i = sig->param_count - 1; i >= 0; --i) {
3616 VERIFIER_DEBUG ( printf ("verifying constructor argument %d\n", i); );
3617 value = stack_pop (ctx);
3618 if (!verify_stack_type_compatibility (ctx, sig->params [i], value)) {
3619 char *stack_name = stack_slot_full_name (value);
3620 char *sig_name = mono_type_full_name (sig->params [i]);
3621 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Incompatible parameter value with constructor signature: %s X %s at 0x%04x", sig_name, stack_name, ctx->ip_offset));
3622 g_free (stack_name);
3626 if (stack_slot_is_managed_mutability_pointer (value))
3627 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use a readonly pointer as argument of newobj at 0x%04x", ctx->ip_offset));
3631 if (check_overflow (ctx))
3632 set_stack_value (ctx, stack_push (ctx), &method->klass->byval_arg, FALSE);
3636 do_cast (VerifyContext *ctx, int token, const char *opcode) {
3642 if (!check_underflow (ctx, 1))
3645 if (!(type = get_boxable_mono_type (ctx, token, opcode)))
3649 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid %s type at 0x%04x", opcode, ctx->ip_offset));
3653 value = stack_pop (ctx);
3654 is_boxed = stack_slot_is_boxed_value (value);
3656 if (stack_slot_is_managed_pointer (value))
3657 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid value for %s at 0x%04x", opcode, ctx->ip_offset));
3658 else if (!MONO_TYPE_IS_REFERENCE (value->type) && !is_boxed) {
3659 char *name = stack_slot_full_name (value);
3660 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Expected a reference type on stack for %s but found %s at 0x%04x", opcode, name, ctx->ip_offset));
3664 switch (value->type->type) {
3665 case MONO_TYPE_FNPTR:
3667 case MONO_TYPE_TYPEDBYREF:
3668 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid value for %s at 0x%04x", opcode, ctx->ip_offset));
3671 do_box = is_boxed || mono_type_is_generic_argument(type) || mono_class_from_mono_type (type)->valuetype;
3672 stack_push_val (ctx, TYPE_COMPLEX | (do_box ? BOXED_MASK : 0), type);
3676 mono_type_from_opcode (int opcode) {
3684 return &mono_defaults.sbyte_class->byval_arg;
3692 return &mono_defaults.int16_class->byval_arg;
3700 return &mono_defaults.int32_class->byval_arg;
3706 return &mono_defaults.int64_class->byval_arg;
3712 return &mono_defaults.single_class->byval_arg;
3718 return &mono_defaults.double_class->byval_arg;
3724 return &mono_defaults.int_class->byval_arg;
3728 case CEE_LDELEM_REF:
3729 case CEE_STELEM_REF:
3730 return &mono_defaults.object_class->byval_arg;
3733 g_error ("unknown opcode %02x in mono_type_from_opcode ", opcode);
3739 do_load_indirect (VerifyContext *ctx, int opcode)
3742 CLEAR_PREFIX (ctx, PREFIX_UNALIGNED | PREFIX_VOLATILE);
3744 if (!check_underflow (ctx, 1))
3747 value = stack_pop (ctx);
3748 if (!stack_slot_is_managed_pointer (value)) {
3749 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Load indirect not using a manager pointer at 0x%04x", ctx->ip_offset));
3750 set_stack_value (ctx, stack_push (ctx), mono_type_from_opcode (opcode), FALSE);
3754 if (opcode == CEE_LDIND_REF) {
3755 if (stack_slot_get_underlying_type (value) != TYPE_COMPLEX || mono_class_from_mono_type (value->type)->valuetype)
3756 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid type at stack for ldind_ref expected object byref operation at 0x%04x", ctx->ip_offset));
3757 set_stack_value (ctx, stack_push (ctx), mono_type_get_type_byval (value->type), FALSE);
3759 if (!verify_type_compatibility_full (ctx, mono_type_from_opcode (opcode), mono_type_get_type_byval (value->type), TRUE))
3760 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid type at stack for ldind 0x%x operation at 0x%04x", opcode, ctx->ip_offset));
3761 set_stack_value (ctx, stack_push (ctx), mono_type_from_opcode (opcode), FALSE);
3766 do_store_indirect (VerifyContext *ctx, int opcode)
3768 ILStackDesc *addr, *val;
3769 CLEAR_PREFIX (ctx, PREFIX_UNALIGNED | PREFIX_VOLATILE);
3771 if (!check_underflow (ctx, 2))
3774 val = stack_pop (ctx);
3775 addr = stack_pop (ctx);
3777 check_unmanaged_pointer (ctx, addr);
3779 if (!stack_slot_is_managed_pointer (addr) && stack_slot_get_type (addr) != TYPE_PTR) {
3780 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid non-pointer argument to stind at 0x%04x", ctx->ip_offset));
3784 if (stack_slot_is_managed_mutability_pointer (addr)) {
3785 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use a readonly pointer with stind at 0x%04x", ctx->ip_offset));
3789 if (!verify_type_compatibility_full (ctx, mono_type_from_opcode (opcode), mono_type_get_type_byval (addr->type), TRUE))
3790 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid addr type at stack for stind 0x%x operation at 0x%04x", opcode, ctx->ip_offset));
3792 if (!verify_stack_type_compatibility (ctx, mono_type_from_opcode (opcode), val))
3793 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid value type at stack for stind 0x%x operation at 0x%04x", opcode, ctx->ip_offset));
3797 do_newarr (VerifyContext *ctx, int token)
3800 MonoType *type = get_boxable_mono_type (ctx, token, "newarr");
3805 if (!check_underflow (ctx, 1))
3808 value = stack_pop (ctx);
3809 if (stack_slot_get_type (value) != TYPE_I4 && stack_slot_get_type (value) != TYPE_NATIVE_INT)
3810 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Array size type on stack (%s) is not a verifiable type at 0x%04x", stack_slot_get_name (value), ctx->ip_offset));
3812 set_stack_value (ctx, stack_push (ctx), mono_class_get_type (mono_array_class_get (mono_class_from_mono_type (type), 1)), FALSE);
3815 /*FIXME handle arrays that are not 0-indexed*/
3817 do_ldlen (VerifyContext *ctx)
3821 if (!check_underflow (ctx, 1))
3824 value = stack_pop (ctx);
3826 if (stack_slot_get_type (value) != TYPE_COMPLEX || value->type->type != MONO_TYPE_SZARRAY)
3827 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type for ldlen at 0x%04x", ctx->ip_offset));
3829 stack_push_val (ctx, TYPE_NATIVE_INT, &mono_defaults.int_class->byval_arg);
3832 /*FIXME handle arrays that are not 0-indexed*/
3833 /*FIXME handle readonly prefix and CMMP*/
3835 do_ldelema (VerifyContext *ctx, int klass_token)
3837 ILStackDesc *index, *array, *res;
3838 MonoType *type = get_boxable_mono_type (ctx, klass_token, "ldelema");
3844 if (!check_underflow (ctx, 2))
3847 index = stack_pop (ctx);
3848 array = stack_pop (ctx);
3850 if (stack_slot_get_type (index) != TYPE_I4 && stack_slot_get_type (index) != TYPE_NATIVE_INT)
3851 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Index type(%s) for ldelema is not an int or a native int at 0x%04x", stack_slot_get_name (index), ctx->ip_offset));
3853 if (!stack_slot_is_null_literal (array)) {
3854 if (stack_slot_get_type (array) != TYPE_COMPLEX || array->type->type != MONO_TYPE_SZARRAY)
3855 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type(%s) for ldelema at 0x%04x", stack_slot_get_name (array), ctx->ip_offset));
3857 if (get_stack_type (type) == TYPE_I4 || get_stack_type (type) == TYPE_NATIVE_INT) {
3858 valid = verify_type_compatibility_full (ctx, type, &array->type->data.klass->byval_arg, TRUE);
3860 valid = mono_metadata_type_equal (type, &array->type->data.klass->byval_arg);
3863 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type on stack for ldelema at 0x%04x", ctx->ip_offset));
3867 res = stack_push (ctx);
3868 set_stack_value (ctx, res, type, TRUE);
3869 if (ctx->prefix_set & PREFIX_READONLY) {
3870 ctx->prefix_set &= ~PREFIX_READONLY;
3871 res->stype |= CMMP_MASK;
3876 * FIXME handle arrays that are not 0-indexed
3877 * FIXME handle readonly prefix and CMMP
3880 do_ldelem (VerifyContext *ctx, int opcode, int token)
3882 #define IS_ONE_OF2(T, A, B) (T == A || T == B)
3883 ILStackDesc *index, *array;
3885 if (!check_underflow (ctx, 2))
3888 if (opcode == CEE_LDELEM) {
3889 if (!(type = verifier_load_type (ctx, token, "ldelem.any"))) {
3890 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Type (0x%08x) not found at 0x%04x", token, ctx->ip_offset));
3894 type = mono_type_from_opcode (opcode);
3897 index = stack_pop (ctx);
3898 array = stack_pop (ctx);
3900 if (stack_slot_get_type (index) != TYPE_I4 && stack_slot_get_type (index) != TYPE_NATIVE_INT)
3901 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Index type(%s) for ldelem.X is not an int or a native int at 0x%04x", stack_slot_get_name (index), ctx->ip_offset));
3903 if (!stack_slot_is_null_literal (array)) {
3904 if (stack_slot_get_type (array) != TYPE_COMPLEX || array->type->type != MONO_TYPE_SZARRAY)
3905 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type(%s) for ldelem.X at 0x%04x", stack_slot_get_name (array), ctx->ip_offset));
3907 if (opcode == CEE_LDELEM_REF) {
3908 if (array->type->data.klass->valuetype)
3909 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type is not a reference type for ldelem.ref 0x%04x", ctx->ip_offset));
3910 type = &array->type->data.klass->byval_arg;
3912 MonoType *candidate = &array->type->data.klass->byval_arg;
3913 if (IS_STRICT_MODE (ctx)) {
3914 MonoType *underlying_type = mono_type_get_underlying_type_any (type);
3915 MonoType *underlying_candidate = mono_type_get_underlying_type_any (candidate);
3916 if ((IS_ONE_OF2 (underlying_type->type, MONO_TYPE_I4, MONO_TYPE_U4) && IS_ONE_OF2 (underlying_candidate->type, MONO_TYPE_I, MONO_TYPE_U)) ||
3917 (IS_ONE_OF2 (underlying_candidate->type, MONO_TYPE_I4, MONO_TYPE_U4) && IS_ONE_OF2 (underlying_type->type, MONO_TYPE_I, MONO_TYPE_U)))
3918 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type on stack for ldelem.X at 0x%04x", ctx->ip_offset));
3920 if (!verify_type_compatibility_full (ctx, type, candidate, TRUE))
3921 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type on stack for ldelem.X at 0x%04x", ctx->ip_offset));
3926 set_stack_value (ctx, stack_push (ctx), type, FALSE);
3931 * FIXME handle arrays that are not 0-indexed
3934 do_stelem (VerifyContext *ctx, int opcode, int token)
3936 ILStackDesc *index, *array, *value;
3938 if (!check_underflow (ctx, 3))
3941 if (opcode == CEE_STELEM) {
3942 if (!(type = verifier_load_type (ctx, token, "stelem.any"))) {
3943 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Type (0x%08x) not found at 0x%04x", token, ctx->ip_offset));
3947 type = mono_type_from_opcode (opcode);
3950 value = stack_pop (ctx);
3951 index = stack_pop (ctx);
3952 array = stack_pop (ctx);
3954 if (stack_slot_get_type (index) != TYPE_I4 && stack_slot_get_type (index) != TYPE_NATIVE_INT)
3955 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Index type(%s) for stdelem.X is not an int or a native int at 0x%04x", stack_slot_get_name (index), ctx->ip_offset));
3957 if (!stack_slot_is_null_literal (array)) {
3958 if (stack_slot_get_type (array) != TYPE_COMPLEX || array->type->type != MONO_TYPE_SZARRAY) {
3959 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type(%s) for stelem.X at 0x%04x", stack_slot_get_name (array), ctx->ip_offset));
3961 if (opcode == CEE_STELEM_REF) {
3962 if (array->type->data.klass->valuetype)
3963 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type is not a reference type for stelem.ref 0x%04x", ctx->ip_offset));
3964 } else if (!verify_type_compatibility_full (ctx, &array->type->data.klass->byval_arg, type, TRUE)) {
3965 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type on stack for stdelem.X at 0x%04x", ctx->ip_offset));
3969 if (opcode == CEE_STELEM_REF) {
3970 if (!stack_slot_is_boxed_value (value) && mono_class_from_mono_type (value->type)->valuetype)
3971 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid value is not a reference type for stelem.ref 0x%04x", ctx->ip_offset));
3972 } else if (opcode != CEE_STELEM_REF) {
3973 if (!verify_stack_type_compatibility (ctx, type, value))
3974 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid value on stack for stdelem.X at 0x%04x", ctx->ip_offset));
3976 if (stack_slot_is_boxed_value (value) && !MONO_TYPE_IS_REFERENCE (value->type) && !MONO_TYPE_IS_REFERENCE (type))
3977 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));
3983 do_throw (VerifyContext *ctx)
3985 ILStackDesc *exception;
3986 if (!check_underflow (ctx, 1))
3988 exception = stack_pop (ctx);
3990 if (!stack_slot_is_null_literal (exception) && !(stack_slot_get_type (exception) == TYPE_COMPLEX && !mono_class_from_mono_type (exception->type)->valuetype))
3991 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid type on stack for throw, expected reference type at 0x%04x", ctx->ip_offset));
3993 if (mono_type_is_generic_argument (exception->type) && !stack_slot_is_boxed_value (exception)) {
3994 char *name = mono_type_full_name (exception->type);
3995 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid type on stack for throw, expected reference type but found unboxed %s at 0x%04x ", name, ctx->ip_offset));
3998 /*The stack is left empty after a throw*/
4004 do_endfilter (VerifyContext *ctx)
4006 MonoExceptionClause *clause;
4008 if (IS_STRICT_MODE (ctx)) {
4009 if (ctx->eval.size != 1)
4010 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Stack size must have one item for endfilter at 0x%04x", ctx->ip_offset));
4012 if (ctx->eval.size >= 1 && stack_slot_get_type (stack_pop (ctx)) != TYPE_I4)
4013 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Stack item type is not an int32 for endfilter at 0x%04x", ctx->ip_offset));
4016 if ((clause = is_correct_endfilter (ctx, ctx->ip_offset))) {
4017 if (IS_STRICT_MODE (ctx)) {
4018 if (ctx->ip_offset != clause->handler_offset - 2)
4019 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("endfilter is not the last instruction of the filter clause at 0x%04x", ctx->ip_offset));
4021 if ((ctx->ip_offset != clause->handler_offset - 2) && !MONO_OFFSET_IN_HANDLER (clause, ctx->ip_offset))
4022 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("endfilter is not the last instruction of the filter clause at 0x%04x", ctx->ip_offset));
4025 if (IS_STRICT_MODE (ctx) && !is_unverifiable_endfilter (ctx, ctx->ip_offset))
4026 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("endfilter outside filter clause at 0x%04x", ctx->ip_offset));
4028 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("endfilter outside filter clause at 0x%04x", ctx->ip_offset));
4035 do_leave (VerifyContext *ctx, int delta)
4037 int target = ((gint32)ctx->ip_offset) + delta;
4038 if (target >= ctx->code_size || target < 0)
4039 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Branch target out of code at 0x%04x", ctx->ip_offset));
4041 if (!is_correct_leave (ctx->header, ctx->ip_offset, target))
4042 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Leave not allowed in finally block at 0x%04x", ctx->ip_offset));
4044 ctx->target = target;
4050 * Verify br and br.s opcodes.
4053 do_static_branch (VerifyContext *ctx, int delta)
4055 int target = ctx->ip_offset + delta;
4056 if (target < 0 || target >= ctx->code_size) {
4057 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("branch target out of code at 0x%04x", ctx->ip_offset));
4061 switch (is_valid_branch_instruction (ctx->header, ctx->ip_offset, target)) {
4063 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Branch target escapes out of exception block at 0x%04x", ctx->ip_offset));
4066 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Branch target escapes out of exception block at 0x%04x", ctx->ip_offset));
4070 ctx->target = target;
4074 do_switch (VerifyContext *ctx, int count, const unsigned char *data)
4076 int i, base = ctx->ip_offset + 5 + count * 4;
4079 if (!check_underflow (ctx, 1))
4082 value = stack_pop (ctx);
4084 if (stack_slot_get_type (value) != TYPE_I4 && stack_slot_get_type (value) != TYPE_NATIVE_INT)
4085 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid argument to switch at 0x%04x", ctx->ip_offset));
4087 for (i = 0; i < count; ++i) {
4088 int target = base + read32 (data + i * 4);
4090 if (target < 0 || target >= ctx->code_size) {
4091 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Switch target %x out of code at 0x%04x", i, ctx->ip_offset));
4095 switch (is_valid_branch_instruction (ctx->header, ctx->ip_offset, target)) {
4097 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Switch target %x escapes out of exception block at 0x%04x", i, ctx->ip_offset));
4100 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Switch target %x escapes out of exception block at 0x%04x", i, ctx->ip_offset));
4103 merge_stacks (ctx, &ctx->eval, &ctx->code [target], FALSE, TRUE);
4108 do_load_function_ptr (VerifyContext *ctx, guint32 token, gboolean virtual)
4113 if (virtual && !check_underflow (ctx, 1))
4116 if (!virtual && !check_overflow (ctx))
4119 if (!IS_METHOD_DEF_OR_REF_OR_SPEC (token) || !token_bounds_check (ctx->image, token)) {
4120 ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid token %x for ldftn at 0x%04x", token, ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE);
4124 if (!(method = verifier_load_method (ctx, token, virtual ? "ldvirtfrn" : "ldftn")))
4127 if (mono_method_is_constructor (method))
4128 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use ldftn with a constructor at 0x%04x", ctx->ip_offset));
4131 ILStackDesc *top = stack_pop (ctx);
4133 if (stack_slot_get_type (top) != TYPE_COMPLEX || top->type->type == MONO_TYPE_VALUETYPE)
4134 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid argument to ldvirtftn at 0x%04x", ctx->ip_offset));
4136 if (method->flags & METHOD_ATTRIBUTE_STATIC)
4137 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use ldvirtftn with a constructor at 0x%04x", ctx->ip_offset));
4139 if (!verify_stack_type_compatibility (ctx, &method->klass->byval_arg, top))
4140 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Unexpected object for ldvirtftn at 0x%04x", ctx->ip_offset));
4143 if (!mono_method_can_access_method_full (ctx->method, method, NULL))
4144 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);
4146 top = stack_push_val(ctx, TYPE_PTR, mono_type_create_fnptr_from_mono_method (ctx, method));
4147 top->method = method;
4151 do_sizeof (VerifyContext *ctx, int token)
4155 if (!IS_TYPE_DEF_OR_REF_OR_SPEC (token) || !token_bounds_check (ctx->image, token)) {
4156 ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid type token %x at 0x%04x", token, ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE);
4160 if (!(type = verifier_load_type (ctx, token, "sizeof")))
4163 if (type->byref && type->type != MONO_TYPE_TYPEDBYREF) {
4164 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid use of byref type at 0x%04x", ctx->ip_offset));
4168 if (type->type == MONO_TYPE_VOID) {
4169 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid use of void type at 0x%04x", ctx->ip_offset));
4173 if (check_overflow (ctx))
4174 set_stack_value (ctx, stack_push (ctx), &mono_defaults.uint32_class->byval_arg, FALSE);
4177 /* Stack top can be of any type, the runtime doesn't care and treat everything as an int. */
4179 do_localloc (VerifyContext *ctx)
4183 if (ctx->eval.size != 1) {
4184 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Stack must have only size item in localloc at 0x%04x", ctx->ip_offset));
4188 if (in_any_exception_block (ctx->header, ctx->ip_offset)) {
4189 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Stack must have only size item in localloc at 0x%04x", ctx->ip_offset));
4193 /*TODO verify top type*/
4194 top = stack_pop (ctx);
4196 set_stack_value (ctx, stack_push (ctx), &mono_defaults.int_class->byval_arg, FALSE);
4197 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Instruction localloc in never verifiable at 0x%04x", ctx->ip_offset));
4201 do_ldstr (VerifyContext *ctx, guint32 token)
4203 GSList *error = NULL;
4204 if (mono_metadata_token_code (token) != MONO_TOKEN_STRING) {
4205 ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid string token %x at 0x%04x", token, ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE);
4209 if (!ctx->image->dynamic && !mono_verifier_verify_string_signature (ctx->image, mono_metadata_token_index (token), &error)) {
4211 ctx->list = g_slist_concat (ctx->list, error);
4212 ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid string index %x at 0x%04x", token, ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE);
4216 if (check_overflow (ctx))
4217 stack_push_val (ctx, TYPE_COMPLEX, &mono_defaults.string_class->byval_arg);
4221 do_refanyval (VerifyContext *ctx, int token)
4225 if (!check_underflow (ctx, 1))
4228 if (!(type = get_boxable_mono_type (ctx, token, "refanyval")))
4231 top = stack_pop (ctx);
4233 if (top->stype != TYPE_PTR || top->type->type != MONO_TYPE_TYPEDBYREF)
4234 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));
4236 set_stack_value (ctx, stack_push (ctx), type, TRUE);
4240 do_refanytype (VerifyContext *ctx)
4244 if (!check_underflow (ctx, 1))
4247 top = stack_pop (ctx);
4249 if (top->stype != TYPE_PTR || top->type->type != MONO_TYPE_TYPEDBYREF)
4250 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));
4252 set_stack_value (ctx, stack_push (ctx), &mono_defaults.typehandle_class->byval_arg, FALSE);
4257 do_mkrefany (VerifyContext *ctx, int token)
4261 if (!check_underflow (ctx, 1))
4264 if (!(type = get_boxable_mono_type (ctx, token, "refanyval")))
4267 top = stack_pop (ctx);
4269 if (stack_slot_is_managed_mutability_pointer (top))
4270 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use a readonly pointer with mkrefany at 0x%04x", ctx->ip_offset));
4272 if (!stack_slot_is_managed_pointer (top)) {
4273 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));
4275 MonoType *stack_type = mono_type_get_type_byval (top->type);
4276 if (MONO_TYPE_IS_REFERENCE (type) && !mono_metadata_type_equal (type, stack_type))
4277 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Type not compatible for mkrefany at 0x%04x", ctx->ip_offset));
4279 if (!MONO_TYPE_IS_REFERENCE (type) && !verify_type_compatibility_full (ctx, type, stack_type, TRUE))
4280 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Type not compatible for mkrefany at 0x%04x", ctx->ip_offset));
4283 set_stack_value (ctx, stack_push (ctx), &mono_defaults.typed_reference_class->byval_arg, FALSE);
4287 do_ckfinite (VerifyContext *ctx)
4290 if (!check_underflow (ctx, 1))
4293 top = stack_pop (ctx);
4295 if (stack_slot_get_underlying_type (top) != TYPE_R8)
4296 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));
4297 stack_push_stack_val (ctx, top);
4301 * Merge the stacks and perform compat checks. The merge check if types of @from are mergeable with type of @to
4303 * @from holds new values for a given control path
4304 * @to holds the current values of a given control path
4306 * TODO we can eliminate the from argument as all callers pass &ctx->eval
4309 merge_stacks (VerifyContext *ctx, ILCodeDesc *from, ILCodeDesc *to, gboolean start, gboolean external)
4313 stack_init (ctx, to);
4316 if (to->flags == IL_CODE_FLAG_NOT_PROCESSED)
4319 stack_copy (&ctx->eval, to);
4321 } else if (!(to->flags & IL_CODE_STACK_MERGED)) {
4322 stack_copy (to, &ctx->eval);
4325 VERIFIER_DEBUG ( printf ("performing stack merge %d x %d\n", from->size, to->size); );
4327 if (from->size != to->size) {
4328 VERIFIER_DEBUG ( printf ("different stack sizes %d x %d at 0x%04x\n", from->size, to->size, ctx->ip_offset); );
4329 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Could not merge stacks, different sizes (%d x %d) at 0x%04x", from->size, to->size, ctx->ip_offset));
4333 //FIXME we need to preserve CMMP attributes
4334 //FIXME we must take null literals into consideration.
4335 for (i = 0; i < from->size; ++i) {
4336 ILStackDesc *new_slot = from->stack + i;
4337 ILStackDesc *old_slot = to->stack + i;
4338 MonoType *new_type = mono_type_from_stack_slot (new_slot);
4339 MonoType *old_type = mono_type_from_stack_slot (old_slot);
4340 MonoClass *old_class = mono_class_from_mono_type (old_type);
4341 MonoClass *new_class = mono_class_from_mono_type (new_type);
4342 MonoClass *match_class = NULL;
4344 // S := T then U = S (new value is compatible with current value, keep current)
4345 if (verify_stack_type_compatibility (ctx, old_type, new_slot)) {
4346 copy_stack_value (new_slot, old_slot);
4350 // T := S then U = T (old value is compatible with current value, use new)
4351 if (verify_stack_type_compatibility (ctx, new_type, old_slot)) {
4352 copy_stack_value (old_slot, new_slot);
4356 if (mono_type_is_generic_argument (old_type) || mono_type_is_generic_argument (new_type)) {
4357 char *old_name = stack_slot_full_name (old_slot);
4358 char *new_name = stack_slot_full_name (new_slot);
4359 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Could not merge stack at depth %d, types not compatible: %s X %s at 0x%04x", i, old_name, new_name, ctx->ip_offset));
4365 //both are reference types, use closest common super type
4366 if (!mono_class_from_mono_type (old_type)->valuetype
4367 && !mono_class_from_mono_type (new_type)->valuetype
4368 && !stack_slot_is_managed_pointer (old_slot)
4369 && !stack_slot_is_managed_pointer (new_slot)) {
4371 for (j = MIN (old_class->idepth, new_class->idepth) - 1; j > 0; --j) {
4372 if (mono_metadata_type_equal (&old_class->supertypes [j]->byval_arg, &new_class->supertypes [j]->byval_arg)) {
4373 match_class = old_class->supertypes [j];
4378 mono_class_setup_interfaces (old_class, &error);
4379 if (!mono_error_ok (&error)) {
4380 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot merge stacks due to a TypeLoadException %s at 0x%04x", mono_error_get_message (&error), ctx->ip_offset));
4381 mono_error_cleanup (&error);
4384 for (j = 0; j < old_class->interface_count; ++j) {
4385 for (k = 0; k < new_class->interface_count; ++k) {
4386 if (mono_metadata_type_equal (&old_class->interfaces [j]->byval_arg, &new_class->interfaces [k]->byval_arg)) {
4387 match_class = old_class->interfaces [j];
4393 //No decent super type found, use object
4394 match_class = mono_defaults.object_class;
4396 } 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)) {
4397 match_class = mono_defaults.object_class;
4402 char *old_name = stack_slot_full_name (old_slot);
4403 char *new_name = stack_slot_full_name (new_slot);
4404 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Could not merge stack at depth %d, types not compatible: %s X %s at 0x%04x", i, old_name, new_name, ctx->ip_offset));
4408 set_stack_value (ctx, old_slot, &new_class->byval_arg, stack_slot_is_managed_pointer (old_slot));
4412 g_assert (match_class);
4413 set_stack_value (ctx, old_slot, &match_class->byval_arg, stack_slot_is_managed_pointer (old_slot));
4414 set_stack_value (ctx, new_slot, &match_class->byval_arg, stack_slot_is_managed_pointer (old_slot));
4420 to->flags |= IL_CODE_FLAG_WAS_TARGET;
4421 to->flags |= IL_CODE_STACK_MERGED;
4424 #define HANDLER_START(clause) ((clause)->flags == MONO_EXCEPTION_CLAUSE_FILTER ? (clause)->data.filter_offset : clause->handler_offset)
4425 #define IS_CATCH_OR_FILTER(clause) ((clause)->flags == MONO_EXCEPTION_CLAUSE_FILTER || (clause)->flags == MONO_EXCEPTION_CLAUSE_NONE)
4428 * is_clause_in_range :
4430 * Returns TRUE if either the protected block or the handler of @clause is in the @start - @end range.
4433 is_clause_in_range (MonoExceptionClause *clause, guint32 start, guint32 end)
4435 if (clause->try_offset >= start && clause->try_offset < end)
4437 if (HANDLER_START (clause) >= start && HANDLER_START (clause) < end)
4443 * is_clause_inside_range :
4445 * Returns TRUE if @clause lies completely inside the @start - @end range.
4448 is_clause_inside_range (MonoExceptionClause *clause, guint32 start, guint32 end)
4450 if (clause->try_offset < start || (clause->try_offset + clause->try_len) > end)
4452 if (HANDLER_START (clause) < start || (clause->handler_offset + clause->handler_len) > end)
4458 * is_clause_nested :
4460 * Returns TRUE if @nested is nested in @clause.
4463 is_clause_nested (MonoExceptionClause *clause, MonoExceptionClause *nested)
4465 if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER && is_clause_inside_range (nested, clause->data.filter_offset, clause->handler_offset))
4467 return is_clause_inside_range (nested, clause->try_offset, clause->try_offset + clause->try_len) ||
4468 is_clause_inside_range (nested, clause->handler_offset, clause->handler_offset + clause->handler_len);
4471 /* Test the relationship between 2 exception clauses. Follow P.1 12.4.2.7 of ECMA
4472 * the each pair of exception must have the following properties:
4473 * - one is fully nested on another (the outer must not be a filter clause) (the nested one must come earlier)
4474 * - completely disjoin (none of the 3 regions of each entry overlap with the other 3)
4475 * - mutual protection (protected block is EXACT the same, handlers are disjoin and all handler are catch or all handler are filter)
4478 verify_clause_relationship (VerifyContext *ctx, MonoExceptionClause *clause, MonoExceptionClause *to_test)
4480 /*clause is nested*/
4481 if (to_test->flags == MONO_EXCEPTION_CLAUSE_FILTER && is_clause_inside_range (clause, to_test->data.filter_offset, to_test->handler_offset)) {
4482 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Exception clause inside filter"));
4486 /*wrong nesting order.*/
4487 if (is_clause_nested (clause, to_test)) {
4488 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Nested exception clause appears after enclosing clause"));
4492 /*mutual protection*/
4493 if (clause->try_offset == to_test->try_offset && clause->try_len == to_test->try_len) {
4494 /*handlers are not disjoint*/
4495 if (is_clause_in_range (to_test, HANDLER_START (clause), clause->handler_offset + clause->handler_len)) {
4496 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Exception handlers overlap"));
4499 /* handlers are not catch or filter */
4500 if (!IS_CATCH_OR_FILTER (clause) || !IS_CATCH_OR_FILTER (to_test)) {
4501 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Exception clauses with shared protected block are neither catch or filter"));
4508 /*not completelly disjoint*/
4509 if ((is_clause_in_range (to_test, clause->try_offset, clause->try_offset + clause->try_len) ||
4510 is_clause_in_range (to_test, HANDLER_START (clause), clause->handler_offset + clause->handler_len)) && !is_clause_nested (to_test, clause))
4511 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Exception clauses overlap"));
4514 #define code_bounds_check(size) \
4515 if (ADDP_IS_GREATER_OR_OVF (ip, size, end)) {\
4516 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Code overrun starting with 0x%x at 0x%04x", *ip, ctx.ip_offset)); \
4521 mono_opcode_is_prefix (int op)
4524 case MONO_CEE_UNALIGNED_:
4525 case MONO_CEE_VOLATILE_:
4526 case MONO_CEE_TAIL_:
4527 case MONO_CEE_CONSTRAINED_:
4528 case MONO_CEE_READONLY_:
4535 * FIXME: need to distinguish between valid and verifiable.
4536 * Need to keep track of types on the stack.
4537 * Verify types for opcodes.
4540 mono_method_verify (MonoMethod *method, int level)
4543 const unsigned char *ip, *code_start;
4544 const unsigned char *end;
4545 MonoSimpleBasicBlock *bb = NULL, *original_bb = NULL;
4547 int i, n, need_merge = 0, start = 0;
4548 guint token, ip_offset = 0, prefix = 0;
4549 MonoGenericContext *generic_context = NULL;
4553 VERIFIER_DEBUG ( printf ("Verify IL for method %s %s %s\n", method->klass->name_space, method->klass->name, method->name); );
4555 init_verifier_stats ();
4557 if (method->iflags & (METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL | METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
4558 (method->flags & (METHOD_ATTRIBUTE_PINVOKE_IMPL | METHOD_ATTRIBUTE_ABSTRACT))) {
4562 memset (&ctx, 0, sizeof (VerifyContext));
4564 //FIXME use mono_method_get_signature_full
4565 ctx.signature = mono_method_signature (method);
4566 if (!ctx.signature) {
4567 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Could not decode method signature"));
4569 finish_collect_stats ();
4572 ctx.header = mono_method_get_header (method);
4574 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Could not decode method header"));
4575 finish_collect_stats ();
4578 ctx.method = method;
4579 code_start = ip = ctx.header->code;
4580 end = ip + ctx.header->code_size;
4581 ctx.image = image = method->klass->image;
4584 ctx.max_args = ctx.signature->param_count + ctx.signature->hasthis;
4585 ctx.max_stack = ctx.header->max_stack;
4586 ctx.verifiable = ctx.valid = 1;
4589 ctx.code = g_new (ILCodeDesc, ctx.header->code_size);
4590 ctx.code_size = ctx.header->code_size;
4591 MEM_ALLOC (sizeof (ILCodeDesc) * ctx.header->code_size);
4593 memset(ctx.code, 0, sizeof (ILCodeDesc) * ctx.header->code_size);
4595 ctx.num_locals = ctx.header->num_locals;
4596 ctx.locals = g_memdup (ctx.header->locals, sizeof (MonoType*) * ctx.header->num_locals);
4597 MEM_ALLOC (sizeof (MonoType*) * ctx.header->num_locals);
4599 if (ctx.num_locals > 0 && !ctx.header->init_locals)
4600 CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Method with locals variable but without init locals set"));
4602 ctx.params = g_new (MonoType*, ctx.max_args);
4603 MEM_ALLOC (sizeof (MonoType*) * ctx.max_args);
4605 if (ctx.signature->hasthis)
4606 ctx.params [0] = method->klass->valuetype ? &method->klass->this_arg : &method->klass->byval_arg;
4607 memcpy (ctx.params + ctx.signature->hasthis, ctx.signature->params, sizeof (MonoType *) * ctx.signature->param_count);
4609 if (ctx.signature->is_inflated)
4610 ctx.generic_context = generic_context = mono_method_get_context (method);
4612 if (!generic_context && (method->klass->generic_container || method->is_generic)) {
4613 if (method->is_generic)
4614 ctx.generic_context = generic_context = &(mono_method_get_generic_container (method)->context);
4616 ctx.generic_context = generic_context = &method->klass->generic_container->context;
4619 for (i = 0; i < ctx.num_locals; ++i) {
4620 MonoType *uninflated = ctx.locals [i];
4621 ctx.locals [i] = mono_class_inflate_generic_type_checked (ctx.locals [i], ctx.generic_context, &error);
4622 if (!mono_error_ok (&error)) {
4623 char *name = mono_type_full_name (ctx.locals [i] ? ctx.locals [i] : uninflated);
4624 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid local %d of type %s", i, name));
4626 mono_error_cleanup (&error);
4627 /* we must not free (in cleanup) what was not yet allocated (but only copied) */
4633 for (i = 0; i < ctx.max_args; ++i) {
4634 MonoType *uninflated = ctx.params [i];
4635 ctx.params [i] = mono_class_inflate_generic_type_checked (ctx.params [i], ctx.generic_context, &error);
4636 if (!mono_error_ok (&error)) {
4637 char *name = mono_type_full_name (ctx.params [i] ? ctx.params [i] : uninflated);
4638 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid parameter %d of type %s", i, name));
4640 mono_error_cleanup (&error);
4641 /* we must not free (in cleanup) what was not yet allocated (but only copied) */
4646 stack_init (&ctx, &ctx.eval);
4648 for (i = 0; i < ctx.num_locals; ++i) {
4649 if (!mono_type_is_valid_in_context (&ctx, ctx.locals [i]))
4651 if (get_stack_type (ctx.locals [i]) == TYPE_INV) {
4652 char *name = mono_type_full_name (ctx.locals [i]);
4653 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid local %i of type %s", i, name));
4660 for (i = 0; i < ctx.max_args; ++i) {
4661 if (!mono_type_is_valid_in_context (&ctx, ctx.params [i]))
4664 if (get_stack_type (ctx.params [i]) == TYPE_INV) {
4665 char *name = mono_type_full_name (ctx.params [i]);
4666 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid parameter %i of type %s", i, name));
4675 for (i = 0; i < ctx.header->num_clauses && ctx.valid; ++i) {
4676 MonoExceptionClause *clause = ctx.header->clauses + i;
4677 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); );
4679 if (clause->try_offset > ctx.code_size || ADD_IS_GREATER_OR_OVF (clause->try_offset, clause->try_len, ctx.code_size))
4680 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("try clause out of bounds at 0x%04x", clause->try_offset));
4682 if (clause->try_len <= 0)
4683 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("try clause len <= 0 at 0x%04x", clause->try_offset));
4685 if (clause->handler_offset > ctx.code_size || ADD_IS_GREATER_OR_OVF (clause->handler_offset, clause->handler_len, ctx.code_size))
4686 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("handler clause out of bounds at 0x%04x", clause->try_offset));
4688 if (clause->handler_len <= 0)
4689 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("handler clause len <= 0 at 0x%04x", clause->try_offset));
4691 if (clause->try_offset < clause->handler_offset && ADD_IS_GREATER_OR_OVF (clause->try_offset, clause->try_len, HANDLER_START (clause)))
4692 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("try block (at 0x%04x) includes handler block (at 0x%04x)", clause->try_offset, clause->handler_offset));
4694 if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
4695 if (clause->data.filter_offset > ctx.code_size)
4696 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("filter clause out of bounds at 0x%04x", clause->try_offset));
4698 if (clause->data.filter_offset >= clause->handler_offset)
4699 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("filter clause must come before the handler clause at 0x%04x", clause->data.filter_offset));
4702 for (n = i + 1; n < ctx.header->num_clauses && ctx.valid; ++n)
4703 verify_clause_relationship (&ctx, clause, ctx.header->clauses + n);
4708 ctx.code [clause->try_offset].flags |= IL_CODE_FLAG_WAS_TARGET;
4709 if (clause->try_offset + clause->try_len < ctx.code_size)
4710 ctx.code [clause->try_offset + clause->try_len].flags |= IL_CODE_FLAG_WAS_TARGET;
4711 if (clause->handler_offset + clause->handler_len < ctx.code_size)
4712 ctx.code [clause->handler_offset + clause->handler_len].flags |= IL_CODE_FLAG_WAS_TARGET;
4714 if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE) {
4715 if (!clause->data.catch_class) {
4716 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Catch clause %d with invalid type", i));
4720 init_stack_with_value_at_exception_boundary (&ctx, ctx.code + clause->handler_offset, clause->data.catch_class);
4722 else if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
4723 init_stack_with_value_at_exception_boundary (&ctx, ctx.code + clause->data.filter_offset, mono_defaults.exception_class);
4724 init_stack_with_value_at_exception_boundary (&ctx, ctx.code + clause->handler_offset, mono_defaults.exception_class);
4728 original_bb = bb = mono_basic_block_split (method, &error);
4729 if (!mono_error_ok (&error)) {
4730 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid branch target: %s", mono_error_get_message (&error)));
4731 mono_error_cleanup (&error);
4736 while (ip < end && ctx.valid) {
4738 ip_offset = ip - code_start;
4740 const unsigned char *ip_copy = ip;
4743 if (ip_offset > bb->end) {
4744 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Branch or EH block at [0x%04x] targets middle instruction at 0x%04x", bb->end, ip_offset));
4748 if (ip_offset == bb->end)
4751 op_size = mono_opcode_value_and_size (&ip_copy, end, &op);
4752 if (op_size == -1) {
4753 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid instruction %x at 0x%04x", *ip, ip_offset));
4757 if (ADD_IS_GREATER_OR_OVF (ip_offset, op_size, bb->end)) {
4758 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Branch or EH block targets middle of instruction at 0x%04x", ip_offset));
4762 /*Last Instruction*/
4763 if (ip_offset + op_size == bb->end && mono_opcode_is_prefix (op)) {
4764 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Branch or EH block targets between prefix '%s' and instruction at 0x%04x", mono_opcode_name (op), ip_offset));
4769 ctx.ip_offset = ip_offset = ip - code_start;
4771 /*We need to check against fallthrou in and out of protected blocks.
4772 * For fallout we check the once a protected block ends, if the start flag is not set.
4773 * Likewise for fallthru in, we check if ip is the start of a protected block and start is not set
4774 * TODO convert these checks to be done using flags and not this loop
4776 for (i = 0; i < ctx.header->num_clauses && ctx.valid; ++i) {
4777 MonoExceptionClause *clause = ctx.header->clauses + i;
4779 if ((clause->try_offset + clause->try_len == ip_offset) && start == 0) {
4780 CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("fallthru off try block at 0x%04x", ip_offset));
4784 if ((clause->handler_offset + clause->handler_len == ip_offset) && start == 0) {
4785 if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER)
4786 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("fallout of handler block at 0x%04x", ip_offset));
4788 CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("fallout of handler block at 0x%04x", ip_offset));
4792 if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER && clause->handler_offset == ip_offset && start == 0) {
4793 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("fallout of filter block at 0x%04x", ip_offset));
4797 if (clause->handler_offset == ip_offset && start == 0) {
4798 CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("fallthru handler block at 0x%04x", ip_offset));
4802 if (clause->try_offset == ip_offset && ctx.eval.size > 0 && start == 0) {
4803 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Try to enter try block with a non-empty stack at 0x%04x", ip_offset));
4808 /*This must be done after fallthru detection otherwise it won't happen.*/
4810 /*FIXME remove this once we move all bad branch checking code to use BB only*/
4811 ctx.code [ip_offset].flags |= IL_CODE_FLAG_SEEN;
4820 VERIFIER_DEBUG ( printf ("extra merge needed! 0x%04x \n", ctx.target); );
4821 merge_stacks (&ctx, &ctx.eval, &ctx.code [ctx.target], FALSE, TRUE);
4824 merge_stacks (&ctx, &ctx.eval, &ctx.code[ip_offset], start, FALSE);
4827 /*TODO we can fast detect a forward branch or exception block targeting code after prefix, we should fail fast*/
4828 #ifdef MONO_VERIFIER_DEBUG
4831 discode = mono_disasm_code_one (NULL, method, ip, NULL);
4832 discode [strlen (discode) - 1] = 0; /* no \n */
4833 g_print ("[%d] %-29s (%d)\n", ip_offset, discode, ctx.eval.size);
4836 dump_stack_state (&ctx.code [ip_offset]);
4837 dump_stack_state (&ctx.eval);
4850 push_arg (&ctx, *ip - CEE_LDARG_0, FALSE);
4856 code_bounds_check (2);
4857 push_arg (&ctx, ip [1], *ip == CEE_LDARGA_S);
4861 case CEE_ADD_OVF_UN:
4862 do_binop (&ctx, *ip, add_ovf_un_table);
4866 case CEE_SUB_OVF_UN:
4867 do_binop (&ctx, *ip, sub_ovf_un_table);
4874 case CEE_MUL_OVF_UN:
4875 do_binop (&ctx, *ip, bin_ovf_table);
4880 do_binop (&ctx, *ip, add_table);
4885 do_binop (&ctx, *ip, sub_table);
4892 do_binop (&ctx, *ip, bin_op_table);
4901 do_binop (&ctx, *ip, int_bin_op_table);
4908 do_binop (&ctx, *ip, shift_op_table);
4913 if (!check_underflow (&ctx, 1))
4915 stack_pop_safe (&ctx);
4929 /*TODO support definite assignment verification? */
4930 push_local (&ctx, *ip - CEE_LDLOC_0, FALSE);
4938 store_local (&ctx, *ip - CEE_STLOC_0);
4943 code_bounds_check (2);
4944 store_local (&ctx, ip [1]);
4949 code_bounds_check (2);
4950 store_arg (&ctx, ip [1]);
4964 if (check_overflow (&ctx))
4965 stack_push_val (&ctx, TYPE_I4, &mono_defaults.int32_class->byval_arg);
4970 code_bounds_check (2);
4971 if (check_overflow (&ctx))
4972 stack_push_val (&ctx, TYPE_I4, &mono_defaults.int32_class->byval_arg);
4977 code_bounds_check (5);
4978 if (check_overflow (&ctx))
4979 stack_push_val (&ctx,TYPE_I4, &mono_defaults.int32_class->byval_arg);
4984 code_bounds_check (9);
4985 if (check_overflow (&ctx))
4986 stack_push_val (&ctx,TYPE_I8, &mono_defaults.int64_class->byval_arg);
4991 code_bounds_check (5);
4992 if (check_overflow (&ctx))
4993 stack_push_val (&ctx, TYPE_R8, &mono_defaults.double_class->byval_arg);
4998 code_bounds_check (9);
4999 if (check_overflow (&ctx))
5000 stack_push_val (&ctx, TYPE_R8, &mono_defaults.double_class->byval_arg);
5005 if (check_overflow (&ctx))
5006 stack_push_val (&ctx, TYPE_COMPLEX | NULL_LITERAL_MASK, &mono_defaults.object_class->byval_arg);
5012 code_bounds_check (2);
5013 do_branch_op (&ctx, (signed char)ip [1] + 2, cmp_br_eq_op);
5026 code_bounds_check (2);
5027 do_branch_op (&ctx, (signed char)ip [1] + 2, cmp_br_op);
5034 code_bounds_check (5);
5035 do_branch_op (&ctx, (gint32)read32 (ip + 1) + 5, cmp_br_eq_op);
5048 code_bounds_check (5);
5049 do_branch_op (&ctx, (gint32)read32 (ip + 1) + 5, cmp_br_op);
5056 code_bounds_check (2);
5057 push_local (&ctx, ip[1], *ip == CEE_LDLOCA_S);
5062 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Use of the `unused' opcode"));
5068 if (!check_underflow (&ctx, 1))
5070 if (!check_overflow (&ctx))
5072 top = stack_push (&ctx);
5073 copy_stack_value (top, stack_peek (&ctx, 1));
5079 code_bounds_check (5);
5081 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Eval stack must be empty in jmp at 0x%04x", ip_offset));
5082 token = read32 (ip + 1);
5083 if (in_any_block (ctx.header, ip_offset))
5084 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("jmp cannot escape exception blocks at 0x%04x", ip_offset));
5086 CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Intruction jmp is not verifiable at 0x%04x", ctx.ip_offset));
5088 * FIXME: check signature, retval, arguments etc.
5094 code_bounds_check (5);
5095 do_invoke_method (&ctx, read32 (ip + 1), *ip == CEE_CALLVIRT);
5100 code_bounds_check (5);
5101 token = read32 (ip + 1);
5103 * FIXME: check signature, retval, arguments etc.
5104 * FIXME: check requirements for tail call
5106 CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Intruction calli is not verifiable at 0x%04x", ctx.ip_offset));
5110 code_bounds_check (2);
5111 do_static_branch (&ctx, (signed char)ip [1] + 2);
5119 code_bounds_check (2);
5120 do_boolean_branch_op (&ctx, (signed char)ip [1] + 2);
5126 code_bounds_check (5);
5127 do_static_branch (&ctx, (gint32)read32 (ip + 1) + 5);
5135 code_bounds_check (5);
5136 do_boolean_branch_op (&ctx, (gint32)read32 (ip + 1) + 5);
5143 code_bounds_check (5);
5144 entries = read32 (ip + 1);
5146 if (entries > 0xFFFFFFFFU / sizeof (guint32))
5147 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Too many switch entries %x at 0x%04x", entries, ctx.ip_offset));
5150 code_bounds_check (sizeof (guint32) * entries);
5152 do_switch (&ctx, entries, ip);
5153 ip += sizeof (guint32) * entries;
5167 do_load_indirect (&ctx, *ip);
5179 do_store_indirect (&ctx, *ip);
5185 do_unary_math_op (&ctx, *ip);
5195 do_conversion (&ctx, TYPE_I4);
5201 do_conversion (&ctx, TYPE_I8);
5208 do_conversion (&ctx, TYPE_R8);
5214 do_conversion (&ctx, TYPE_NATIVE_INT);
5219 code_bounds_check (5);
5220 do_cpobj (&ctx, read32 (ip + 1));
5225 code_bounds_check (5);
5226 do_ldobj_value (&ctx, read32 (ip + 1));
5231 code_bounds_check (5);
5232 do_ldstr (&ctx, read32 (ip + 1));
5237 code_bounds_check (5);
5238 do_newobj (&ctx, read32 (ip + 1));
5244 code_bounds_check (5);
5245 do_cast (&ctx, read32 (ip + 1), *ip == CEE_CASTCLASS ? "castclass" : "isinst");
5251 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Use of the `unused' opcode"));
5256 code_bounds_check (5);
5257 do_unbox_value (&ctx, read32 (ip + 1));
5269 code_bounds_check (5);
5270 do_push_field (&ctx, read32 (ip + 1), *ip == CEE_LDFLDA);
5276 code_bounds_check (5);
5277 do_push_static_field (&ctx, read32 (ip + 1), *ip == CEE_LDSFLDA);
5282 code_bounds_check (5);
5283 do_store_field (&ctx, read32 (ip + 1));
5288 code_bounds_check (5);
5289 do_store_static_field (&ctx, read32 (ip + 1));
5294 code_bounds_check (5);
5295 do_stobj (&ctx, read32 (ip + 1));
5299 case CEE_CONV_OVF_I1_UN:
5300 case CEE_CONV_OVF_I2_UN:
5301 case CEE_CONV_OVF_I4_UN:
5302 case CEE_CONV_OVF_U1_UN:
5303 case CEE_CONV_OVF_U2_UN:
5304 case CEE_CONV_OVF_U4_UN:
5305 do_conversion (&ctx, TYPE_I4);
5309 case CEE_CONV_OVF_I8_UN:
5310 case CEE_CONV_OVF_U8_UN:
5311 do_conversion (&ctx, TYPE_I8);
5315 case CEE_CONV_OVF_I_UN:
5316 case CEE_CONV_OVF_U_UN:
5317 do_conversion (&ctx, TYPE_NATIVE_INT);
5322 code_bounds_check (5);
5323 do_box_value (&ctx, read32 (ip + 1));
5328 code_bounds_check (5);
5329 do_newarr (&ctx, read32 (ip + 1));
5339 code_bounds_check (5);
5340 do_ldelema (&ctx, read32 (ip + 1));
5354 case CEE_LDELEM_REF:
5355 do_ldelem (&ctx, *ip, 0);
5366 case CEE_STELEM_REF:
5367 do_stelem (&ctx, *ip, 0);
5372 code_bounds_check (5);
5373 do_ldelem (&ctx, *ip, read32 (ip + 1));
5378 code_bounds_check (5);
5379 do_stelem (&ctx, *ip, read32 (ip + 1));
5384 code_bounds_check (5);
5385 do_unbox_any (&ctx, read32 (ip + 1));
5389 case CEE_CONV_OVF_I1:
5390 case CEE_CONV_OVF_U1:
5391 case CEE_CONV_OVF_I2:
5392 case CEE_CONV_OVF_U2:
5393 case CEE_CONV_OVF_I4:
5394 case CEE_CONV_OVF_U4:
5395 do_conversion (&ctx, TYPE_I4);
5399 case CEE_CONV_OVF_I8:
5400 case CEE_CONV_OVF_U8:
5401 do_conversion (&ctx, TYPE_I8);
5405 case CEE_CONV_OVF_I:
5406 case CEE_CONV_OVF_U:
5407 do_conversion (&ctx, TYPE_NATIVE_INT);
5412 code_bounds_check (5);
5413 do_refanyval (&ctx, read32 (ip + 1));
5423 code_bounds_check (5);
5424 do_mkrefany (&ctx, read32 (ip + 1));
5429 code_bounds_check (5);
5430 do_load_token (&ctx, read32 (ip + 1));
5434 case CEE_ENDFINALLY:
5435 if (!is_correct_endfinally (ctx.header, ip_offset))
5436 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("endfinally must be used inside a finally/fault handler at 0x%04x", ctx.ip_offset));
5443 code_bounds_check (5);
5444 do_leave (&ctx, read32 (ip + 1) + 5);
5451 code_bounds_check (2);
5452 do_leave (&ctx, (signed char)ip [1] + 2);
5459 code_bounds_check (2);
5463 code_bounds_check (3);
5464 store_local (&ctx, read16 (ip + 1));
5469 do_cmp_op (&ctx, cmp_br_eq_op, *ip);
5477 do_cmp_op (&ctx, cmp_br_op, *ip);
5482 code_bounds_check (3);
5483 store_arg (&ctx, read16 (ip + 1) );
5489 if (!check_overflow (&ctx))
5491 if (ctx.signature->call_convention != MONO_CALL_VARARG)
5492 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Cannot use arglist on method without VARGARG calling convention at 0x%04x", ctx.ip_offset));
5493 set_stack_value (&ctx, stack_push (&ctx), &mono_defaults.argumenthandle_class->byval_arg, FALSE);
5498 code_bounds_check (5);
5499 do_load_function_ptr (&ctx, read32 (ip + 1), FALSE);
5504 code_bounds_check (5);
5505 do_load_function_ptr (&ctx, read32 (ip + 1), TRUE);
5511 code_bounds_check (3);
5512 push_arg (&ctx, read16 (ip + 1), *ip == CEE_LDARGA);
5518 code_bounds_check (3);
5519 push_local (&ctx, read16 (ip + 1), *ip == CEE_LDLOCA);
5532 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Use of the `unused' opcode"));
5536 do_endfilter (&ctx);
5540 case CEE_UNALIGNED_:
5541 code_bounds_check (2);
5542 prefix |= PREFIX_UNALIGNED;
5546 prefix |= PREFIX_VOLATILE;
5550 prefix |= PREFIX_TAIL;
5552 if (ip < end && (*ip != CEE_CALL && *ip != CEE_CALLI && *ip != CEE_CALLVIRT))
5553 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("tail prefix must be used only with call opcodes at 0x%04x", ip_offset));
5557 code_bounds_check (5);
5558 do_initobj (&ctx, read32 (ip + 1));
5562 case CEE_CONSTRAINED_:
5563 code_bounds_check (5);
5564 ctx.constrained_type = get_boxable_mono_type (&ctx, read32 (ip + 1), "constrained.");
5565 prefix |= PREFIX_CONSTRAINED;
5570 prefix |= PREFIX_READONLY;
5575 CLEAR_PREFIX (&ctx, PREFIX_UNALIGNED | PREFIX_VOLATILE);
5576 if (!check_underflow (&ctx, 3))
5578 CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Instruction cpblk is not verifiable at 0x%04x", ctx.ip_offset));
5583 CLEAR_PREFIX (&ctx, PREFIX_UNALIGNED | PREFIX_VOLATILE);
5584 if (!check_underflow (&ctx, 3))
5586 CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Instruction initblk is not verifiable at 0x%04x", ctx.ip_offset));
5594 if (!is_correct_rethrow (ctx.header, ip_offset))
5595 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("rethrow must be used inside a catch handler at 0x%04x", ctx.ip_offset));
5602 code_bounds_check (5);
5603 do_sizeof (&ctx, read32 (ip + 1));
5607 case CEE_REFANYTYPE:
5608 do_refanytype (&ctx);
5613 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid instruction FE %x at 0x%04x", *ip, ctx.ip_offset));
5619 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid instruction %x at 0x%04x", *ip, ctx.ip_offset));
5623 /*TODO we can fast detect a forward branch or exception block targeting code after prefix, we should fail fast*/
5625 if (!ctx.prefix_set) //first prefix
5626 ctx.code [ctx.ip_offset].flags |= IL_CODE_FLAG_SEEN;
5627 ctx.prefix_set |= prefix;
5628 ctx.has_flags = TRUE;
5632 ctx.code [ctx.ip_offset].flags |= IL_CODE_FLAG_SEEN;
5634 if (ctx.prefix_set & PREFIX_CONSTRAINED)
5635 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid instruction after constrained prefix at 0x%04x", ctx.ip_offset));
5636 if (ctx.prefix_set & PREFIX_READONLY)
5637 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid instruction after readonly prefix at 0x%04x", ctx.ip_offset));
5638 if (ctx.prefix_set & PREFIX_VOLATILE)
5639 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid instruction after volatile prefix at 0x%04x", ctx.ip_offset));
5640 if (ctx.prefix_set & PREFIX_UNALIGNED)
5641 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid instruction after unaligned prefix at 0x%04x", ctx.ip_offset));
5642 ctx.prefix_set = prefix = 0;
5643 ctx.has_flags = FALSE;
5647 * if ip != end we overflowed: mark as error.
5649 if ((ip != end || !start) && ctx.verifiable && !ctx.list) {
5650 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Run ahead of method code at 0x%04x", ip_offset));
5653 /*We should guard against the last decoded opcode, otherwise we might add errors that doesn't make sense.*/
5654 for (i = 0; i < ctx.code_size && i < ip_offset; ++i) {
5655 if (ctx.code [i].flags & IL_CODE_FLAG_WAS_TARGET) {
5656 if (!(ctx.code [i].flags & IL_CODE_FLAG_SEEN))
5657 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Branch or exception block target middle of intruction at 0x%04x", i));
5659 if (ctx.code [i].flags & IL_CODE_DELEGATE_SEQUENCE)
5660 CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Branch to delegate code sequence at 0x%04x", i));
5662 if ((ctx.code [i].flags & IL_CODE_LDFTN_DELEGATE_NONFINAL_VIRTUAL) && ctx.has_this_store)
5663 CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Invalid ldftn with virtual function in method with stdarg 0 at 0x%04x", i));
5665 if ((ctx.code [i].flags & IL_CODE_CALL_NONFINAL_VIRTUAL) && ctx.has_this_store)
5666 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));
5669 if (mono_method_is_constructor (ctx.method) && !ctx.super_ctor_called && !ctx.method->klass->valuetype && ctx.method->klass != mono_defaults.object_class) {
5670 char *method_name = mono_method_full_name (ctx.method, TRUE);
5671 char *type = mono_type_get_full_name (ctx.method->klass);
5672 if (ctx.method->klass->parent && ctx.method->klass->parent->exception_type != MONO_EXCEPTION_NONE)
5673 CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Constructor %s for type %s not calling base type ctor due to a TypeLoadException on base type.", method_name, type));
5675 CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Constructor %s for type %s not calling base type ctor.", method_name, type));
5676 g_free (method_name);
5682 for (i = 0; i < ctx.header->code_size; ++i) {
5683 if (ctx.code [i].stack)
5684 g_free (ctx.code [i].stack);
5688 for (tmp = ctx.funptrs; tmp; tmp = tmp->next)
5690 g_slist_free (ctx.funptrs);
5692 for (tmp = ctx.exception_types; tmp; tmp = tmp->next)
5693 mono_metadata_free_type (tmp->data);
5694 g_slist_free (ctx.exception_types);
5696 for (i = 0; i < ctx.num_locals; ++i) {
5698 mono_metadata_free_type (ctx.locals [i]);
5700 for (i = 0; i < ctx.max_args; ++i) {
5702 mono_metadata_free_type (ctx.params [i]);
5706 g_free (ctx.eval.stack);
5709 g_free (ctx.locals);
5710 g_free (ctx.params);
5711 mono_basic_block_free (original_bb);
5712 mono_metadata_free_mh (ctx.header);
5714 finish_collect_stats ();
5719 mono_verify_corlib ()
5721 /* This is a public API function so cannot be removed */
5726 * Returns true if @method needs to be verified.
5730 mono_verifier_is_enabled_for_method (MonoMethod *method)
5732 return mono_verifier_is_enabled_for_class (method->klass) && method->wrapper_type == MONO_WRAPPER_NONE;
5736 * Returns true if @klass need to be verified.
5740 mono_verifier_is_enabled_for_class (MonoClass *klass)
5742 return verify_all || (verifier_mode > MONO_VERIFIER_MODE_OFF && !(klass->image->assembly && klass->image->assembly->in_gac) && klass->image != mono_defaults.corlib);
5746 mono_verifier_is_enabled_for_image (MonoImage *image)
5748 return verify_all || verifier_mode > MONO_VERIFIER_MODE_OFF;
5752 mono_verifier_is_method_full_trust (MonoMethod *method)
5754 return mono_verifier_is_class_full_trust (method->klass);
5758 * Returns if @klass is under full trust or not.
5760 * TODO This code doesn't take CAS into account.
5762 * Under verify_all all user code must be verifiable if no security option was set
5766 mono_verifier_is_class_full_trust (MonoClass *klass)
5768 /* under CoreCLR code is trusted if it is part of the "platform" otherwise all code inside the GAC is trusted */
5769 gboolean trusted_location = (mono_security_get_mode () != MONO_SECURITY_MODE_CORE_CLR) ?
5770 (klass->image->assembly && klass->image->assembly->in_gac) : mono_security_core_clr_is_platform_image (klass->image);
5772 if (verify_all && verifier_mode == MONO_VERIFIER_MODE_OFF)
5773 return trusted_location || klass->image == mono_defaults.corlib;
5774 return verifier_mode < MONO_VERIFIER_MODE_VERIFIABLE || trusted_location || klass->image == mono_defaults.corlib;
5778 mono_method_verify_with_current_settings (MonoMethod *method, gboolean skip_visibility)
5780 return mono_method_verify (method,
5781 (verifier_mode != MONO_VERIFIER_MODE_STRICT ? MONO_VERIFY_NON_STRICT: 0)
5782 | (!mono_verifier_is_method_full_trust (method) ? MONO_VERIFY_FAIL_FAST : 0)
5783 | (skip_visibility ? MONO_VERIFY_SKIP_VISIBILITY : 0));
5787 get_field_end (MonoClassField *field)
5790 int size = mono_type_size (field->type, &align);
5792 size = 4; /*FIXME Is this a safe bet?*/
5793 return size + field->offset;
5797 verify_class_for_overlapping_reference_fields (MonoClass *class)
5800 gpointer iter = NULL;
5801 MonoClassField *field;
5802 gboolean is_fulltrust = mono_verifier_is_class_full_trust (class);
5803 /*We can't skip types with !has_references since this is calculated after we have run.*/
5804 if (!((class->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_EXPLICIT_LAYOUT))
5808 /*We must check for stuff overlapping reference fields.
5809 The outer loop uses mono_class_get_fields to ensure that MonoClass:fields get inited.
5811 while ((field = mono_class_get_fields (class, &iter))) {
5812 int fieldEnd = get_field_end (field);
5813 gboolean is_valuetype = !MONO_TYPE_IS_REFERENCE (field->type);
5816 if (mono_field_is_deleted (field) || (field->type->attrs & FIELD_ATTRIBUTE_STATIC))
5819 for (j = i; j < class->field.count; ++j) {
5820 MonoClassField *other = &class->fields [j];
5821 int otherEnd = get_field_end (other);
5822 if (mono_field_is_deleted (other) || (is_valuetype && !MONO_TYPE_IS_REFERENCE (other->type)) || (other->type->attrs & FIELD_ATTRIBUTE_STATIC))
5825 if (!is_valuetype && MONO_TYPE_IS_REFERENCE (other->type) && field->offset == other->offset && is_fulltrust)
5828 if ((otherEnd > field->offset && otherEnd <= fieldEnd) || (other->offset >= field->offset && other->offset < fieldEnd))
5836 field_hash (gconstpointer key)
5838 const MonoClassField *field = key;
5839 return g_str_hash (field->name) ^ mono_metadata_type_hash (field->type); /**/
5843 field_equals (gconstpointer _a, gconstpointer _b)
5845 const MonoClassField *a = _a;
5846 const MonoClassField *b = _b;
5847 return !strcmp (a->name, b->name) && mono_metadata_type_equal (a->type, b->type);
5852 verify_class_fields (MonoClass *class)
5854 gpointer iter = NULL;
5855 MonoClassField *field;
5856 MonoGenericContext *context = mono_class_get_context (class);
5857 GHashTable *unique_fields = g_hash_table_new_full (&field_hash, &field_equals, NULL, NULL);
5858 if (class->generic_container)
5859 context = &class->generic_container->context;
5861 while ((field = mono_class_get_fields (class, &iter)) != NULL) {
5862 if (!mono_type_is_valid_type_in_context (field->type, context)) {
5863 g_hash_table_destroy (unique_fields);
5866 if (g_hash_table_lookup (unique_fields, field)) {
5867 g_hash_table_destroy (unique_fields);
5870 g_hash_table_insert (unique_fields, field, field);
5872 g_hash_table_destroy (unique_fields);
5877 verify_interfaces (MonoClass *class)
5880 for (i = 0; i < class->interface_count; ++i) {
5881 MonoClass *iface = class->interfaces [i];
5882 if (!(iface->flags & TYPE_ATTRIBUTE_INTERFACE))
5889 verify_valuetype_layout_with_target (MonoClass *class, MonoClass *target_class)
5892 gpointer iter = NULL;
5893 MonoClassField *field;
5894 MonoClass *field_class;
5896 if (!class->valuetype)
5899 type = class->byval_arg.type;
5900 /*primitive type fields are not properly decoded*/
5901 if ((type >= MONO_TYPE_BOOLEAN && type <= MONO_TYPE_R8) || (type >= MONO_TYPE_I && type <= MONO_TYPE_U))
5904 while ((field = mono_class_get_fields (class, &iter)) != NULL) {
5908 if (field->type->attrs & (FIELD_ATTRIBUTE_STATIC | FIELD_ATTRIBUTE_HAS_FIELD_RVA))
5911 field_class = mono_class_get_generic_type_definition (mono_class_from_mono_type (field->type));
5913 if (field_class == target_class || class == field_class || !verify_valuetype_layout_with_target (field_class, target_class))
5921 verify_valuetype_layout (MonoClass *class)
5924 res = verify_valuetype_layout_with_target (class, class);
5929 recursive_mark_constraint_args (MonoBitSet *used_args, MonoGenericContainer *gc, MonoType *type)
5932 MonoClass **constraints;
5933 MonoGenericParamInfo *param_info;
5935 g_assert (mono_type_is_generic_argument (type));
5937 idx = mono_type_get_generic_param_num (type);
5938 if (mono_bitset_test_fast (used_args, idx))
5941 mono_bitset_set_fast (used_args, idx);
5942 param_info = mono_generic_container_get_param_info (gc, idx);
5944 if (!param_info->constraints)
5947 for (constraints = param_info->constraints; *constraints; ++constraints) {
5948 MonoClass *ctr = *constraints;
5949 MonoType *constraint_type = &ctr->byval_arg;
5951 if (mono_type_is_generic_argument (constraint_type) && !recursive_mark_constraint_args (used_args, gc, constraint_type))
5958 verify_generic_parameters (MonoClass *class)
5961 MonoGenericContainer *gc = class->generic_container;
5962 MonoBitSet *used_args = mono_bitset_new (gc->type_argc, 0);
5964 for (i = 0; i < gc->type_argc; ++i) {
5965 MonoGenericParamInfo *param_info = mono_generic_container_get_param_info (gc, i);
5966 MonoClass **constraints;
5968 if (!param_info->constraints)
5971 mono_bitset_clear_all (used_args);
5972 mono_bitset_set_fast (used_args, i);
5974 for (constraints = param_info->constraints; *constraints; ++constraints) {
5975 MonoClass *ctr = *constraints;
5976 MonoType *constraint_type = &ctr->byval_arg;
5978 if (!mono_type_is_valid_type_in_context (constraint_type, &gc->context))
5981 if (mono_type_is_generic_argument (constraint_type) && !recursive_mark_constraint_args (used_args, gc, constraint_type))
5983 if (ctr->generic_class && !mono_class_is_valid_generic_instantiation (NULL, ctr))
5987 mono_bitset_free (used_args);
5991 mono_bitset_free (used_args);
5996 * Check if the class is verifiable.
5998 * Right now there are no conditions that make a class a valid but not verifiable. Both overlapping reference
5999 * field and invalid generic instantiation are fatal errors.
6001 * This method must be safe to be called from mono_class_init and all code must be carefull about that.
6005 mono_verifier_verify_class (MonoClass *class)
6007 /*Neither <Module>, object or ifaces have parent.*/
6008 if (!class->parent &&
6009 class != mono_defaults.object_class &&
6010 !MONO_CLASS_IS_INTERFACE (class) &&
6011 (!class->image->dynamic && class->type_token != 0x2000001)) /*<Module> is the first type in the assembly*/
6013 if (class->parent) {
6014 if (MONO_CLASS_IS_INTERFACE (class->parent))
6016 if (!class->generic_class && class->parent->generic_container)
6019 if (class->generic_container && (class->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_EXPLICIT_LAYOUT)
6021 if (class->generic_container && !verify_generic_parameters (class))
6023 if (!verify_class_for_overlapping_reference_fields (class))
6025 if (class->generic_class && !mono_class_is_valid_generic_instantiation (NULL, class))
6027 if (class->generic_class == NULL && !verify_class_fields (class))
6029 if (class->valuetype && !verify_valuetype_layout (class))
6031 if (!verify_interfaces (class))
6038 mono_verifier_verify_class (MonoClass *class)
6040 /* The verifier was disabled at compile time */
6045 mono_method_verify_with_current_settings (MonoMethod *method, gboolean skip_visibility)
6047 /* The verifier was disabled at compile time */
6052 mono_verifier_is_class_full_trust (MonoClass *klass)
6054 /* The verifier was disabled at compile time */
6059 mono_verifier_is_method_full_trust (MonoMethod *method)
6061 /* The verifier was disabled at compile time */
6066 mono_verifier_is_enabled_for_image (MonoImage *image)
6068 /* The verifier was disabled at compile time */
6073 mono_verifier_is_enabled_for_class (MonoClass *klass)
6075 /* The verifier was disabled at compile time */
6080 mono_verifier_is_enabled_for_method (MonoMethod *method)
6082 /* The verifier was disabled at compile time */
6087 mono_method_verify (MonoMethod *method, int level)
6089 /* The verifier was disabled at compile time */
6094 mono_free_verify_list (GSList *list)
6096 /* The verifier was disabled at compile time */
6097 /* will always be null if verifier is disabled */