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) && mono_metadata_token_index (token) > 0;
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 (ctx->method->wrapper_type != MONO_WRAPPER_NONE) {
896 field = mono_method_get_wrapper_data (ctx->method, (guint32)token);
897 klass = field ? field->parent : NULL;
899 if (!IS_FIELD_DEF_OR_REF (token) || !token_bounds_check (ctx->image, token)) {
900 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);
904 field = mono_field_from_token (ctx->image, token, &klass, ctx->generic_context);
907 if (!field || !field->parent || !klass || mono_loader_get_last_error ()) {
908 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);
909 mono_loader_clear_error ();
913 if (!mono_type_is_valid_in_context (ctx, &klass->byval_arg))
916 if (mono_field_get_flags (field) & FIELD_ATTRIBUTE_LITERAL) {
917 char *type_name = mono_type_get_full_name (field->parent);
918 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Cannot reference literal field %s::%s at 0x%04x", type_name, field->name, ctx->ip_offset));
928 verifier_load_method (VerifyContext *ctx, int token, const char *opcode) {
931 if (ctx->method->wrapper_type != MONO_WRAPPER_NONE) {
932 method = mono_method_get_wrapper_data (ctx->method, (guint32)token);
934 if (!IS_METHOD_DEF_OR_REF_OR_SPEC (token) || !token_bounds_check (ctx->image, token)) {
935 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);
939 method = mono_get_method_full (ctx->image, token, NULL, ctx->generic_context);
942 if (!method || mono_loader_get_last_error ()) {
943 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);
944 mono_loader_clear_error ();
948 if (mono_method_is_valid_in_context (ctx, method) == RESULT_INVALID)
955 verifier_load_type (VerifyContext *ctx, int token, const char *opcode) {
958 if (ctx->method->wrapper_type != MONO_WRAPPER_NONE) {
959 MonoClass *class = mono_method_get_wrapper_data (ctx->method, (guint32)token);
960 type = class ? &class->byval_arg : NULL;
962 if (!IS_TYPE_DEF_OR_REF_OR_SPEC (token) || !token_bounds_check (ctx->image, token)) {
963 ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid type token 0x%08x at 0x%04x", token, ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE);
966 type = mono_type_get_full (ctx->image, token, ctx->generic_context);
969 if (!type || mono_loader_get_last_error ()) {
970 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);
971 mono_loader_clear_error ();
975 if (!mono_type_is_valid_in_context (ctx, type))
982 /* stack_slot_get_type:
984 * Returns the stack type of @value. This value includes POINTER_MASK.
986 * Use this function to checks that account for a managed pointer.
989 stack_slot_get_type (ILStackDesc *value)
991 return value->stype & RAW_TYPE_MASK;
994 /* stack_slot_get_underlying_type:
996 * Returns the stack type of @value. This value does not include POINTER_MASK.
998 * Use this function is cases where the fact that the value could be a managed pointer is
999 * irrelevant. For example, field load doesn't care about this fact of type on stack.
1002 stack_slot_get_underlying_type (ILStackDesc *value)
1004 return value->stype & TYPE_MASK;
1007 /* stack_slot_is_managed_pointer:
1009 * Returns TRUE is @value is a managed pointer.
1012 stack_slot_is_managed_pointer (ILStackDesc *value)
1014 return (value->stype & POINTER_MASK) == POINTER_MASK;
1017 /* stack_slot_is_managed_mutability_pointer:
1019 * Returns TRUE is @value is a managed mutability pointer.
1021 static G_GNUC_UNUSED gboolean
1022 stack_slot_is_managed_mutability_pointer (ILStackDesc *value)
1024 return (value->stype & CMMP_MASK) == CMMP_MASK;
1027 /* stack_slot_is_null_literal:
1029 * Returns TRUE is @value is the null literal.
1032 stack_slot_is_null_literal (ILStackDesc *value)
1034 return (value->stype & NULL_LITERAL_MASK) == NULL_LITERAL_MASK;
1038 /* stack_slot_is_this_pointer:
1040 * Returns TRUE is @value is the this literal
1043 stack_slot_is_this_pointer (ILStackDesc *value)
1045 return (value->stype & THIS_POINTER_MASK) == THIS_POINTER_MASK;
1048 /* stack_slot_is_boxed_value:
1050 * Returns TRUE is @value is a boxed value
1053 stack_slot_is_boxed_value (ILStackDesc *value)
1055 return (value->stype & BOXED_MASK) == BOXED_MASK;
1059 stack_slot_get_name (ILStackDesc *value)
1061 return type_names [value->stype & TYPE_MASK];
1064 #define APPEND_WITH_PREDICATE(PRED,NAME) do {\
1065 if (PRED (value)) { \
1067 g_string_append (str, ", "); \
1068 g_string_append (str, NAME); \
1073 stack_slot_stack_type_full_name (ILStackDesc *value)
1075 GString *str = g_string_new ("");
1077 gboolean has_pred = FALSE, first = TRUE;
1079 if ((value->stype & TYPE_MASK) != value->stype) {
1080 g_string_append(str, "[");
1081 APPEND_WITH_PREDICATE (stack_slot_is_this_pointer, "this");
1082 APPEND_WITH_PREDICATE (stack_slot_is_boxed_value, "boxed");
1083 APPEND_WITH_PREDICATE (stack_slot_is_null_literal, "null");
1084 APPEND_WITH_PREDICATE (stack_slot_is_managed_mutability_pointer, "cmmp");
1085 APPEND_WITH_PREDICATE (stack_slot_is_managed_pointer, "mp");
1089 if (mono_type_is_generic_argument (value->type) && !stack_slot_is_boxed_value (value)) {
1091 g_string_append(str, "[");
1093 g_string_append (str, ", ");
1094 g_string_append (str, "unboxed");
1099 g_string_append(str, "] ");
1101 g_string_append (str, stack_slot_get_name (value));
1103 g_string_free (str, FALSE);
1108 stack_slot_full_name (ILStackDesc *value)
1110 char *type_name = mono_type_full_name (value->type);
1111 char *stack_name = stack_slot_stack_type_full_name (value);
1112 char *res = g_strdup_printf ("%s (%s)", type_name, stack_name);
1114 g_free (stack_name);
1118 //////////////////////////////////////////////////////////////////
1120 mono_free_verify_list (GSList *list)
1122 MonoVerifyInfoExtended *info;
1125 for (tmp = list; tmp; tmp = tmp->next) {
1127 g_free (info->info.message);
1130 g_slist_free (list);
1133 #define ADD_ERROR(list,msg) \
1135 MonoVerifyInfoExtended *vinfo = g_new (MonoVerifyInfoExtended, 1); \
1136 vinfo->info.status = MONO_VERIFY_ERROR; \
1137 vinfo->info.message = (msg); \
1138 (list) = g_slist_prepend ((list), vinfo); \
1141 #define ADD_WARN(list,code,msg) \
1143 MonoVerifyInfoExtended *vinfo = g_new (MonoVerifyInfoExtended, 1); \
1144 vinfo->info.status = (code); \
1145 vinfo->info.message = (msg); \
1146 (list) = g_slist_prepend ((list), vinfo); \
1149 #define ADD_INVALID(list,msg) \
1151 MonoVerifyInfoExtended *vinfo = g_new (MonoVerifyInfoExtended, 1); \
1152 vinfo->status = MONO_VERIFY_ERROR; \
1153 vinfo->message = (msg); \
1154 (list) = g_slist_prepend ((list), vinfo); \
1155 /*G_BREAKPOINT ();*/ \
1159 #define CHECK_STACK_UNDERFLOW(num) \
1161 if (cur_stack < (num)) \
1162 ADD_INVALID (list, g_strdup_printf ("Stack underflow at 0x%04x (%d items instead of %d)", ip_offset, cur_stack, (num))); \
1165 #define CHECK_STACK_OVERFLOW() \
1167 if (cur_stack >= max_stack) \
1168 ADD_INVALID (list, g_strdup_printf ("Maxstack exceeded at 0x%04x", ip_offset)); \
1173 in_any_block (MonoMethodHeader *header, guint offset)
1176 MonoExceptionClause *clause;
1178 for (i = 0; i < header->num_clauses; ++i) {
1179 clause = &header->clauses [i];
1180 if (MONO_OFFSET_IN_CLAUSE (clause, offset))
1182 if (MONO_OFFSET_IN_HANDLER (clause, offset))
1184 if (MONO_OFFSET_IN_FILTER (clause, offset))
1191 * in_any_exception_block:
1193 * Returns TRUE is @offset is part of any exception clause (filter, handler, catch, finally or fault).
1196 in_any_exception_block (MonoMethodHeader *header, guint offset)
1199 MonoExceptionClause *clause;
1201 for (i = 0; i < header->num_clauses; ++i) {
1202 clause = &header->clauses [i];
1203 if (MONO_OFFSET_IN_HANDLER (clause, offset))
1205 if (MONO_OFFSET_IN_FILTER (clause, offset))
1212 * is_valid_branch_instruction:
1214 * Verify if it's valid to perform a branch from @offset to @target.
1215 * This should be used with br and brtrue/false.
1216 * It returns 0 if valid, 1 for unverifiable and 2 for invalid.
1217 * The major diferent from other similiar functions is that branching into a
1218 * finally/fault block is invalid instead of just unverifiable.
1221 is_valid_branch_instruction (MonoMethodHeader *header, guint offset, guint target)
1224 MonoExceptionClause *clause;
1226 for (i = 0; i < header->num_clauses; ++i) {
1227 clause = &header->clauses [i];
1228 /*branching into a finally block is invalid*/
1229 if ((clause->flags == MONO_EXCEPTION_CLAUSE_FINALLY || clause->flags == MONO_EXCEPTION_CLAUSE_FAULT) &&
1230 !MONO_OFFSET_IN_HANDLER (clause, offset) &&
1231 MONO_OFFSET_IN_HANDLER (clause, target))
1234 if (clause->try_offset != target && (MONO_OFFSET_IN_CLAUSE (clause, offset) ^ MONO_OFFSET_IN_CLAUSE (clause, target)))
1236 if (MONO_OFFSET_IN_HANDLER (clause, offset) ^ MONO_OFFSET_IN_HANDLER (clause, target))
1238 if (MONO_OFFSET_IN_FILTER (clause, offset) ^ MONO_OFFSET_IN_FILTER (clause, target))
1245 * is_valid_cmp_branch_instruction:
1247 * Verify if it's valid to perform a branch from @offset to @target.
1248 * This should be used with binary comparison branching instruction, like beq, bge and similars.
1249 * It returns 0 if valid, 1 for unverifiable and 2 for invalid.
1251 * The major diferences from other similar functions are that most errors lead to invalid
1252 * code and only branching out of finally, filter or fault clauses is unverifiable.
1255 is_valid_cmp_branch_instruction (MonoMethodHeader *header, guint offset, guint target)
1258 MonoExceptionClause *clause;
1260 for (i = 0; i < header->num_clauses; ++i) {
1261 clause = &header->clauses [i];
1262 /*branching out of a handler or finally*/
1263 if (clause->flags != MONO_EXCEPTION_CLAUSE_NONE &&
1264 MONO_OFFSET_IN_HANDLER (clause, offset) &&
1265 !MONO_OFFSET_IN_HANDLER (clause, target))
1268 if (clause->try_offset != target && (MONO_OFFSET_IN_CLAUSE (clause, offset) ^ MONO_OFFSET_IN_CLAUSE (clause, target)))
1270 if (MONO_OFFSET_IN_HANDLER (clause, offset) ^ MONO_OFFSET_IN_HANDLER (clause, target))
1272 if (MONO_OFFSET_IN_FILTER (clause, offset) ^ MONO_OFFSET_IN_FILTER (clause, target))
1279 * A leave can't escape a finally block
1282 is_correct_leave (MonoMethodHeader *header, guint offset, guint target)
1285 MonoExceptionClause *clause;
1287 for (i = 0; i < header->num_clauses; ++i) {
1288 clause = &header->clauses [i];
1289 if (clause->flags == MONO_EXCEPTION_CLAUSE_FINALLY && MONO_OFFSET_IN_HANDLER (clause, offset) && !MONO_OFFSET_IN_HANDLER (clause, target))
1291 if (MONO_OFFSET_IN_FILTER (clause, offset))
1298 * A rethrow can't happen outside of a catch handler.
1301 is_correct_rethrow (MonoMethodHeader *header, guint offset)
1304 MonoExceptionClause *clause;
1306 for (i = 0; i < header->num_clauses; ++i) {
1307 clause = &header->clauses [i];
1308 if (MONO_OFFSET_IN_HANDLER (clause, offset))
1310 if (MONO_OFFSET_IN_FILTER (clause, offset))
1317 * An endfinally can't happen outside of a finally/fault handler.
1320 is_correct_endfinally (MonoMethodHeader *header, guint offset)
1323 MonoExceptionClause *clause;
1325 for (i = 0; i < header->num_clauses; ++i) {
1326 clause = &header->clauses [i];
1327 if (MONO_OFFSET_IN_HANDLER (clause, offset) && (clause->flags == MONO_EXCEPTION_CLAUSE_FAULT || clause->flags == MONO_EXCEPTION_CLAUSE_FINALLY))
1335 * An endfilter can only happens inside a filter clause.
1336 * In non-strict mode filter is allowed inside the handler clause too
1338 static MonoExceptionClause *
1339 is_correct_endfilter (VerifyContext *ctx, guint offset)
1342 MonoExceptionClause *clause;
1344 for (i = 0; i < ctx->header->num_clauses; ++i) {
1345 clause = &ctx->header->clauses [i];
1346 if (clause->flags != MONO_EXCEPTION_CLAUSE_FILTER)
1348 if (MONO_OFFSET_IN_FILTER (clause, offset))
1350 if (!IS_STRICT_MODE (ctx) && MONO_OFFSET_IN_HANDLER (clause, offset))
1358 * Non-strict endfilter can happens inside a try block or any handler block
1361 is_unverifiable_endfilter (VerifyContext *ctx, guint offset)
1364 MonoExceptionClause *clause;
1366 for (i = 0; i < ctx->header->num_clauses; ++i) {
1367 clause = &ctx->header->clauses [i];
1368 if (MONO_OFFSET_IN_CLAUSE (clause, offset))
1375 is_valid_bool_arg (ILStackDesc *arg)
1377 if (stack_slot_is_managed_pointer (arg) || stack_slot_is_boxed_value (arg) || stack_slot_is_null_literal (arg))
1381 switch (stack_slot_get_underlying_type (arg)) {
1384 case TYPE_NATIVE_INT:
1388 g_assert (arg->type);
1389 switch (arg->type->type) {
1390 case MONO_TYPE_CLASS:
1391 case MONO_TYPE_STRING:
1392 case MONO_TYPE_OBJECT:
1393 case MONO_TYPE_SZARRAY:
1394 case MONO_TYPE_ARRAY:
1395 case MONO_TYPE_FNPTR:
1398 case MONO_TYPE_GENERICINST:
1399 /*We need to check if the container class
1400 * of the generic type is a valuetype, iow:
1401 * is it a "class Foo<T>" or a "struct Foo<T>"?
1403 return !arg->type->data.generic_class->container_class->valuetype;
1411 /*Type manipulation helper*/
1413 /*Returns the byref version of the supplied MonoType*/
1415 mono_type_get_type_byref (MonoType *type)
1419 return &mono_class_from_mono_type (type)->this_arg;
1423 /*Returns the byval version of the supplied MonoType*/
1425 mono_type_get_type_byval (MonoType *type)
1429 return &mono_class_from_mono_type (type)->byval_arg;
1433 mono_type_from_stack_slot (ILStackDesc *slot)
1435 if (stack_slot_is_managed_pointer (slot))
1436 return mono_type_get_type_byref (slot->type);
1440 /*Stack manipulation code*/
1443 ensure_stack_size (ILCodeDesc *stack, int required)
1448 if (required < stack->max_size)
1451 /* We don't have to worry about the exponential growth since stack_copy prune unused space */
1452 new_size = MAX (8, MAX (required, stack->max_size * 2));
1454 g_assert (new_size >= stack->size);
1455 g_assert (new_size >= required);
1457 tmp = g_new0 (ILStackDesc, new_size);
1458 MEM_ALLOC (sizeof (ILStackDesc) * new_size);
1462 memcpy (tmp, stack->stack, stack->size * sizeof (ILStackDesc));
1463 g_free (stack->stack);
1464 MEM_FREE (sizeof (ILStackDesc) * stack->max_size);
1468 stack->max_size = new_size;
1472 stack_init (VerifyContext *ctx, ILCodeDesc *state)
1474 if (state->flags & IL_CODE_FLAG_STACK_INITED)
1476 state->size = state->max_size = 0;
1477 state->flags |= IL_CODE_FLAG_STACK_INITED;
1481 stack_copy (ILCodeDesc *to, ILCodeDesc *from)
1483 ensure_stack_size (to, from->size);
1484 to->size = from->size;
1486 /*stack copy happens at merge points, which have small stacks*/
1488 memcpy (to->stack, from->stack, sizeof (ILStackDesc) * from->size);
1492 copy_stack_value (ILStackDesc *to, ILStackDesc *from)
1494 to->stype = from->stype;
1495 to->type = from->type;
1496 to->method = from->method;
1500 check_underflow (VerifyContext *ctx, int size)
1502 if (ctx->eval.size < size) {
1503 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Stack underflow, required %d, but have %d at 0x%04x", size, ctx->eval.size, ctx->ip_offset));
1510 check_overflow (VerifyContext *ctx)
1512 if (ctx->eval.size >= ctx->max_stack) {
1513 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Method doesn't have stack-depth %d at 0x%04x", ctx->eval.size + 1, ctx->ip_offset));
1519 /*This reject out PTR, FNPTR and TYPEDBYREF*/
1521 check_unmanaged_pointer (VerifyContext *ctx, ILStackDesc *value)
1523 if (stack_slot_get_type (value) == TYPE_PTR) {
1524 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Unmanaged pointer is not a verifiable type at 0x%04x", ctx->ip_offset));
1530 /*TODO verify if MONO_TYPE_TYPEDBYREF is not allowed here as well.*/
1532 check_unverifiable_type (VerifyContext *ctx, MonoType *type)
1534 if (type->type == MONO_TYPE_PTR || type->type == MONO_TYPE_FNPTR) {
1535 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Unmanaged pointer is not a verifiable type at 0x%04x", ctx->ip_offset));
1541 static ILStackDesc *
1542 stack_push (VerifyContext *ctx)
1544 g_assert (ctx->eval.size < ctx->max_stack);
1545 g_assert (ctx->eval.size <= ctx->eval.max_size);
1547 ensure_stack_size (&ctx->eval, ctx->eval.size + 1);
1549 return & ctx->eval.stack [ctx->eval.size++];
1552 static ILStackDesc *
1553 stack_push_val (VerifyContext *ctx, int stype, MonoType *type)
1555 ILStackDesc *top = stack_push (ctx);
1561 static ILStackDesc *
1562 stack_pop (VerifyContext *ctx)
1565 g_assert (ctx->eval.size > 0);
1566 ret = ctx->eval.stack + --ctx->eval.size;
1567 if ((ret->stype & UNINIT_THIS_MASK) == UNINIT_THIS_MASK)
1568 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Found use of uninitialized 'this ptr' ref at 0x%04x", ctx->ip_offset));
1572 /* This function allows to safely pop an unititialized this ptr from
1573 * the eval stack without marking the method as unverifiable.
1575 static ILStackDesc *
1576 stack_pop_safe (VerifyContext *ctx)
1578 g_assert (ctx->eval.size > 0);
1579 return ctx->eval.stack + --ctx->eval.size;
1582 /*Positive number distance from stack top. [0] is stack top, [1] is the one below*/
1584 stack_peek (VerifyContext *ctx, int distance)
1586 g_assert (ctx->eval.size - distance > 0);
1587 return ctx->eval.stack + (ctx->eval.size - 1 - distance);
1590 static ILStackDesc *
1591 stack_push_stack_val (VerifyContext *ctx, ILStackDesc *value)
1593 ILStackDesc *top = stack_push (ctx);
1594 copy_stack_value (top, value);
1598 /* Returns the MonoType associated with the token, or NULL if it is invalid.
1600 * A boxable type can be either a reference or value type, but cannot be a byref type or an unmanaged pointer
1603 get_boxable_mono_type (VerifyContext* ctx, int token, const char *opcode)
1608 if (!(type = verifier_load_type (ctx, token, opcode)))
1611 if (type->byref && type->type != MONO_TYPE_TYPEDBYREF) {
1612 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid use of byref type for %s at 0x%04x", opcode, ctx->ip_offset));
1616 if (type->type == MONO_TYPE_VOID) {
1617 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid use of void type for %s at 0x%04x", opcode, ctx->ip_offset));
1621 if (type->type == MONO_TYPE_TYPEDBYREF)
1622 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid use of typedbyref for %s at 0x%04x", opcode, ctx->ip_offset));
1624 if (!(class = mono_class_from_mono_type (type)))
1625 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Could not retrieve type token for %s at 0x%04x", opcode, ctx->ip_offset));
1627 if (class->generic_container && type->type != MONO_TYPE_GENERICINST)
1628 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));
1630 check_unverifiable_type (ctx, type);
1635 /*operation result tables */
1637 static const unsigned char bin_op_table [TYPE_MAX][TYPE_MAX] = {
1638 {TYPE_I4, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV},
1639 {TYPE_INV, TYPE_I8, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
1640 {TYPE_NATIVE_INT, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV},
1641 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_R8, TYPE_INV, TYPE_INV},
1642 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
1643 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
1646 static const unsigned char add_table [TYPE_MAX][TYPE_MAX] = {
1647 {TYPE_I4, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV},
1648 {TYPE_INV, TYPE_I8, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
1649 {TYPE_NATIVE_INT, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV},
1650 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_R8, TYPE_INV, TYPE_INV},
1651 {TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV, TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV, TYPE_INV, TYPE_INV},
1652 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
1655 static const unsigned char sub_table [TYPE_MAX][TYPE_MAX] = {
1656 {TYPE_I4, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV},
1657 {TYPE_INV, TYPE_I8, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
1658 {TYPE_NATIVE_INT, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV},
1659 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_R8, TYPE_INV, TYPE_INV},
1660 {TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV, TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV, TYPE_NATIVE_INT | NON_VERIFIABLE_RESULT, TYPE_INV},
1661 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
1664 static const unsigned char int_bin_op_table [TYPE_MAX][TYPE_MAX] = {
1665 {TYPE_I4, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV},
1666 {TYPE_INV, TYPE_I8, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
1667 {TYPE_NATIVE_INT, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV},
1668 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
1669 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
1670 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
1673 static const unsigned char shift_op_table [TYPE_MAX][TYPE_MAX] = {
1674 {TYPE_I4, TYPE_INV, TYPE_I4, TYPE_INV, TYPE_INV, TYPE_INV},
1675 {TYPE_I8, TYPE_INV, TYPE_I8, TYPE_INV, TYPE_INV, TYPE_INV},
1676 {TYPE_NATIVE_INT, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV},
1677 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
1678 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
1679 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
1682 static const unsigned char cmp_br_op [TYPE_MAX][TYPE_MAX] = {
1683 {TYPE_I4, TYPE_INV, TYPE_I4, TYPE_INV, TYPE_INV, TYPE_INV},
1684 {TYPE_INV, TYPE_I4, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
1685 {TYPE_I4, TYPE_INV, TYPE_I4, TYPE_INV, TYPE_INV, TYPE_INV},
1686 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_I4, TYPE_INV, TYPE_INV},
1687 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_I4, TYPE_INV},
1688 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
1691 static const unsigned char cmp_br_eq_op [TYPE_MAX][TYPE_MAX] = {
1692 {TYPE_I4, TYPE_INV, TYPE_I4, TYPE_INV, TYPE_INV, TYPE_INV},
1693 {TYPE_INV, TYPE_I4, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
1694 {TYPE_I4, TYPE_INV, TYPE_I4, TYPE_INV, TYPE_I4 | NON_VERIFIABLE_RESULT, TYPE_INV},
1695 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_I4, TYPE_INV, TYPE_INV},
1696 {TYPE_INV, TYPE_INV, TYPE_I4 | NON_VERIFIABLE_RESULT, TYPE_INV, TYPE_I4, TYPE_INV},
1697 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_I4},
1700 static const unsigned char add_ovf_un_table [TYPE_MAX][TYPE_MAX] = {
1701 {TYPE_I4, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV},
1702 {TYPE_INV, TYPE_I8, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
1703 {TYPE_NATIVE_INT, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV},
1704 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
1705 {TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV, TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV, TYPE_INV, TYPE_INV},
1706 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
1709 static const unsigned char sub_ovf_un_table [TYPE_MAX][TYPE_MAX] = {
1710 {TYPE_I4, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV},
1711 {TYPE_INV, TYPE_I8, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
1712 {TYPE_NATIVE_INT, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV},
1713 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
1714 {TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV, TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV, TYPE_NATIVE_INT | NON_VERIFIABLE_RESULT, TYPE_INV},
1715 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
1718 static const unsigned char bin_ovf_table [TYPE_MAX][TYPE_MAX] = {
1719 {TYPE_I4, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV},
1720 {TYPE_INV, TYPE_I8, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
1721 {TYPE_NATIVE_INT, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV},
1722 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
1723 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
1724 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
1727 #ifdef MONO_VERIFIER_DEBUG
1731 dump_stack_value (ILStackDesc *value)
1733 printf ("[(%x)(%x)", value->type->type, value->stype);
1735 if (stack_slot_is_this_pointer (value))
1738 if (stack_slot_is_boxed_value (value))
1739 printf ("[boxed] ");
1741 if (stack_slot_is_null_literal (value))
1744 if (stack_slot_is_managed_mutability_pointer (value))
1745 printf ("Controled Mutability MP: ");
1747 if (stack_slot_is_managed_pointer (value))
1748 printf ("Managed Pointer to: ");
1750 switch (stack_slot_get_underlying_type (value)) {
1752 printf ("invalid type]");
1760 case TYPE_NATIVE_INT:
1761 printf ("native int]");
1764 printf ("float64]");
1767 printf ("unmanaged pointer]");
1770 switch (value->type->type) {
1771 case MONO_TYPE_CLASS:
1772 case MONO_TYPE_VALUETYPE:
1773 printf ("complex] (%s)", value->type->data.klass->name);
1775 case MONO_TYPE_STRING:
1776 printf ("complex] (string)");
1778 case MONO_TYPE_OBJECT:
1779 printf ("complex] (object)");
1781 case MONO_TYPE_SZARRAY:
1782 printf ("complex] (%s [])", value->type->data.klass->name);
1784 case MONO_TYPE_ARRAY:
1785 printf ("complex] (%s [%d %d %d])",
1786 value->type->data.array->eklass->name,
1787 value->type->data.array->rank,
1788 value->type->data.array->numsizes,
1789 value->type->data.array->numlobounds);
1791 case MONO_TYPE_GENERICINST:
1792 printf ("complex] (inst of %s )", value->type->data.generic_class->container_class->name);
1795 printf ("complex] (type generic param !%d - %s) ", value->type->data.generic_param->num, mono_generic_param_info (value->type->data.generic_param)->name);
1797 case MONO_TYPE_MVAR:
1798 printf ("complex] (method generic param !!%d - %s) ", value->type->data.generic_param->num, mono_generic_param_info (value->type->data.generic_param)->name);
1801 //should be a boxed value
1802 char * name = mono_type_full_name (value->type);
1803 printf ("complex] %s", name);
1809 printf ("unknown stack %x type]\n", value->stype);
1810 g_assert_not_reached ();
1815 dump_stack_state (ILCodeDesc *state)
1819 printf ("(%d) ", state->size);
1820 for (i = 0; i < state->size; ++i)
1821 dump_stack_value (state->stack + i);
1826 /*Returns TRUE if candidate array type can be assigned to target.
1827 *Both parameters MUST be of type MONO_TYPE_ARRAY (target->type == MONO_TYPE_ARRAY)
1830 is_array_type_compatible (MonoType *target, MonoType *candidate)
1832 MonoArrayType *left = target->data.array;
1833 MonoArrayType *right = candidate->data.array;
1835 g_assert (target->type == MONO_TYPE_ARRAY);
1836 g_assert (candidate->type == MONO_TYPE_ARRAY);
1838 if (left->rank != right->rank)
1841 return mono_class_is_assignable_from (left->eklass, right->eklass);
1845 get_stack_type (MonoType *type)
1848 int type_kind = type->type;
1850 mask = POINTER_MASK;
1851 /*TODO handle CMMP_MASK */
1854 switch (type_kind) {
1857 case MONO_TYPE_BOOLEAN:
1860 case MONO_TYPE_CHAR:
1863 return TYPE_I4 | mask;
1867 return TYPE_NATIVE_INT | mask;
1869 /* FIXME: the spec says that you cannot have a pointer to method pointer, do we need to check this here? */
1870 case MONO_TYPE_FNPTR:
1872 case MONO_TYPE_TYPEDBYREF:
1873 return TYPE_PTR | mask;
1876 case MONO_TYPE_MVAR:
1878 case MONO_TYPE_CLASS:
1879 case MONO_TYPE_STRING:
1880 case MONO_TYPE_OBJECT:
1881 case MONO_TYPE_SZARRAY:
1882 case MONO_TYPE_ARRAY:
1883 return TYPE_COMPLEX | mask;
1887 return TYPE_I8 | mask;
1891 return TYPE_R8 | mask;
1893 case MONO_TYPE_GENERICINST:
1894 case MONO_TYPE_VALUETYPE:
1895 if (mono_type_is_enum_type (type)) {
1896 type = mono_type_get_underlying_type_any (type);
1899 type_kind = type->type;
1902 return TYPE_COMPLEX | mask;
1910 /* convert MonoType to ILStackDesc format (stype) */
1912 set_stack_value (VerifyContext *ctx, ILStackDesc *stack, MonoType *type, int take_addr)
1915 int type_kind = type->type;
1917 if (type->byref || take_addr)
1918 mask = POINTER_MASK;
1919 /* TODO handle CMMP_MASK */
1924 switch (type_kind) {
1927 case MONO_TYPE_BOOLEAN:
1930 case MONO_TYPE_CHAR:
1933 stack->stype = TYPE_I4 | mask;
1937 stack->stype = TYPE_NATIVE_INT | mask;
1940 /*FIXME: Do we need to check if it's a pointer to the method pointer? The spec says it' illegal to have that.*/
1941 case MONO_TYPE_FNPTR:
1943 case MONO_TYPE_TYPEDBYREF:
1944 stack->stype = TYPE_PTR | mask;
1947 case MONO_TYPE_CLASS:
1948 case MONO_TYPE_STRING:
1949 case MONO_TYPE_OBJECT:
1950 case MONO_TYPE_SZARRAY:
1951 case MONO_TYPE_ARRAY:
1954 case MONO_TYPE_MVAR:
1955 stack->stype = TYPE_COMPLEX | mask;
1960 stack->stype = TYPE_I8 | mask;
1964 stack->stype = TYPE_R8 | mask;
1966 case MONO_TYPE_GENERICINST:
1967 case MONO_TYPE_VALUETYPE:
1968 if (mono_type_is_enum_type (type)) {
1969 MonoType *utype = mono_type_get_underlying_type_any (type);
1971 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Could not resolve underlying type of %x at %d", type->type, ctx->ip_offset));
1975 type_kind = type->type;
1978 stack->stype = TYPE_COMPLEX | mask;
1982 VERIFIER_DEBUG ( printf ("unknown type 0x%02x in eval stack type\n", type->type); );
1983 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Illegal value set on stack 0x%02x at %d", type->type, ctx->ip_offset));
1990 * init_stack_with_value_at_exception_boundary:
1992 * Initialize the stack and push a given type.
1993 * The instruction is marked as been on the exception boundary.
1996 init_stack_with_value_at_exception_boundary (VerifyContext *ctx, ILCodeDesc *code, MonoClass *klass)
1999 MonoType *type = mono_class_inflate_generic_type_checked (&klass->byval_arg, ctx->generic_context, &error);
2001 if (!mono_error_ok (&error)) {
2002 char *name = mono_type_get_full_name (klass);
2003 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid class %s used for exception", name));
2005 mono_error_cleanup (&error);
2009 if (!ctx->max_stack) {
2010 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Stack overflow at 0x%04x", ctx->ip_offset));
2014 stack_init (ctx, code);
2015 ensure_stack_size (code, 1);
2016 set_stack_value (ctx, code->stack, type, FALSE);
2017 ctx->exception_types = g_slist_prepend (ctx->exception_types, type);
2019 code->flags |= IL_CODE_FLAG_WAS_TARGET;
2020 if (mono_type_is_generic_argument (type))
2021 code->stack->stype |= BOXED_MASK;
2024 /*Verify if type 'candidate' can be stored in type 'target'.
2026 * If strict, check for the underlying type and not the verification stack types
2029 verify_type_compatibility_full (VerifyContext *ctx, MonoType *target, MonoType *candidate, gboolean strict)
2031 #define IS_ONE_OF3(T, A, B, C) (T == A || T == B || T == C)
2032 #define IS_ONE_OF2(T, A, B) (T == A || T == B)
2034 MonoType *original_candidate = candidate;
2035 VERIFIER_DEBUG ( printf ("checking type compatibility %s x %s strict %d\n", mono_type_full_name (target), mono_type_full_name (candidate), strict); );
2037 /*only one is byref */
2038 if (candidate->byref ^ target->byref) {
2039 /* converting from native int to byref*/
2040 if (get_stack_type (candidate) == TYPE_NATIVE_INT && target->byref) {
2041 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("using byref native int at 0x%04x", ctx->ip_offset));
2046 strict |= target->byref;
2047 /*From now on we don't care about byref anymore, so it's ok to discard it here*/
2048 candidate = mono_type_get_underlying_type_any (candidate);
2051 switch (target->type) {
2052 case MONO_TYPE_VOID:
2053 return candidate->type == MONO_TYPE_VOID;
2056 case MONO_TYPE_BOOLEAN:
2058 return IS_ONE_OF3 (candidate->type, MONO_TYPE_I1, MONO_TYPE_U1, MONO_TYPE_BOOLEAN);
2061 case MONO_TYPE_CHAR:
2063 return IS_ONE_OF3 (candidate->type, MONO_TYPE_I2, MONO_TYPE_U2, MONO_TYPE_CHAR);
2065 case MONO_TYPE_U4: {
2066 gboolean is_native_int = IS_ONE_OF2 (candidate->type, MONO_TYPE_I, MONO_TYPE_U);
2067 gboolean is_int4 = IS_ONE_OF2 (candidate->type, MONO_TYPE_I4, MONO_TYPE_U4);
2069 return is_native_int || is_int4;
2070 return is_native_int || get_stack_type (candidate) == TYPE_I4;
2075 return IS_ONE_OF2 (candidate->type, MONO_TYPE_I8, MONO_TYPE_U8);
2080 return candidate->type == target->type;
2081 return IS_ONE_OF2 (candidate->type, MONO_TYPE_R4, MONO_TYPE_R8);
2085 gboolean is_native_int = IS_ONE_OF2 (candidate->type, MONO_TYPE_I, MONO_TYPE_U);
2086 gboolean is_int4 = IS_ONE_OF2 (candidate->type, MONO_TYPE_I4, MONO_TYPE_U4);
2088 return is_native_int || is_int4;
2089 return is_native_int || get_stack_type (candidate) == TYPE_I4;
2093 if (candidate->type != MONO_TYPE_PTR)
2095 /* check the underlying type */
2096 return verify_type_compatibility_full (ctx, target->data.type, candidate->data.type, TRUE);
2098 case MONO_TYPE_FNPTR: {
2099 MonoMethodSignature *left, *right;
2100 if (candidate->type != MONO_TYPE_FNPTR)
2103 left = mono_type_get_signature (target);
2104 right = mono_type_get_signature (candidate);
2105 return mono_metadata_signature_equal (left, right) && left->call_convention == right->call_convention;
2108 case MONO_TYPE_GENERICINST: {
2109 MonoClass *target_klass;
2110 MonoClass *candidate_klass;
2111 if (mono_type_is_enum_type (target)) {
2112 target = mono_type_get_underlying_type_any (target);
2118 * VAR / MVAR compatibility must be checked by verify_stack_type_compatibility
2119 * to take boxing status into account.
2121 if (mono_type_is_generic_argument (original_candidate))
2124 target_klass = mono_class_from_mono_type (target);
2125 candidate_klass = mono_class_from_mono_type (candidate);
2126 if (mono_class_is_nullable (target_klass)) {
2127 if (!mono_class_is_nullable (candidate_klass))
2129 return target_klass == candidate_klass;
2132 return mono_class_is_assignable_from (target_klass, candidate_klass);
2135 case MONO_TYPE_STRING:
2136 return candidate->type == MONO_TYPE_STRING;
2138 case MONO_TYPE_CLASS:
2140 * VAR / MVAR compatibility must be checked by verify_stack_type_compatibility
2141 * to take boxing status into account.
2143 if (mono_type_is_generic_argument (original_candidate))
2146 if (candidate->type == MONO_TYPE_VALUETYPE)
2149 /* If candidate is an enum it should return true for System.Enum and supertypes.
2150 * That's why here we use the original type and not the underlying type.
2152 return mono_class_is_assignable_from (target->data.klass, mono_class_from_mono_type (original_candidate));
2154 case MONO_TYPE_OBJECT:
2155 return MONO_TYPE_IS_REFERENCE (candidate);
2157 case MONO_TYPE_SZARRAY: {
2160 if (candidate->type != MONO_TYPE_SZARRAY)
2163 left = mono_class_from_mono_type (target);
2164 right = mono_class_from_mono_type (candidate);
2166 return mono_class_is_assignable_from (left, right);
2169 case MONO_TYPE_ARRAY:
2170 if (candidate->type != MONO_TYPE_ARRAY)
2172 return is_array_type_compatible (target, candidate);
2174 case MONO_TYPE_TYPEDBYREF:
2175 return candidate->type == MONO_TYPE_TYPEDBYREF;
2177 case MONO_TYPE_VALUETYPE: {
2178 MonoClass *target_klass;
2179 MonoClass *candidate_klass;
2181 if (candidate->type == MONO_TYPE_CLASS)
2184 target_klass = mono_class_from_mono_type (target);
2185 candidate_klass = mono_class_from_mono_type (candidate);
2186 if (target_klass == candidate_klass)
2188 if (mono_type_is_enum_type (target)) {
2189 target = mono_type_get_underlying_type_any (target);
2198 if (candidate->type != MONO_TYPE_VAR)
2200 return mono_type_get_generic_param_num (candidate) == mono_type_get_generic_param_num (target);
2202 case MONO_TYPE_MVAR:
2203 if (candidate->type != MONO_TYPE_MVAR)
2205 return mono_type_get_generic_param_num (candidate) == mono_type_get_generic_param_num (target);
2208 VERIFIER_DEBUG ( printf ("unknown store type %d\n", target->type); );
2209 g_assert_not_reached ();
2218 verify_type_compatibility (VerifyContext *ctx, MonoType *target, MonoType *candidate)
2220 return verify_type_compatibility_full (ctx, target, candidate, FALSE);
2224 * Returns the generic param bound to the context been verified.
2227 static MonoGenericParam*
2228 get_generic_param (VerifyContext *ctx, MonoType *param)
2230 guint16 param_num = mono_type_get_generic_param_num (param);
2231 if (param->type == MONO_TYPE_VAR) {
2232 if (!ctx->generic_context->class_inst || ctx->generic_context->class_inst->type_argc <= param_num) {
2233 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid generic type argument %d", param_num));
2236 return ctx->generic_context->class_inst->type_argv [param_num]->data.generic_param;
2239 /*param must be a MVAR */
2240 if (!ctx->generic_context->method_inst || ctx->generic_context->method_inst->type_argc <= param_num) {
2241 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid generic method argument %d", param_num));
2244 return ctx->generic_context->method_inst->type_argv [param_num]->data.generic_param;
2249 recursive_boxed_constraint_type_check (VerifyContext *ctx, MonoType *type, MonoClass *constraint_class, int recursion_level)
2251 MonoType *constraint_type = &constraint_class->byval_arg;
2252 if (recursion_level <= 0)
2255 if (verify_type_compatibility_full (ctx, type, mono_type_get_type_byval (constraint_type), FALSE))
2258 if (mono_type_is_generic_argument (constraint_type)) {
2259 MonoGenericParam *param = get_generic_param (ctx, constraint_type);
2263 for (class = mono_generic_param_info (param)->constraints; class && *class; ++class) {
2264 if (recursive_boxed_constraint_type_check (ctx, type, *class, recursion_level - 1))
2272 * is_compatible_boxed_valuetype:
2274 * Returns TRUE if @candidate / @stack is a valid boxed valuetype.
2276 * @type The source type. It it tested to be of the proper type.
2277 * @candidate type of the boxed valuetype.
2278 * @stack stack slot of the boxed valuetype, separate from @candidade since one could be changed before calling this function
2279 * @strict if TRUE candidate must be boxed compatible to the target type
2283 is_compatible_boxed_valuetype (VerifyContext *ctx, MonoType *type, MonoType *candidate, ILStackDesc *stack, gboolean strict)
2285 if (!stack_slot_is_boxed_value (stack))
2287 if (type->byref || candidate->byref)
2290 if (mono_type_is_generic_argument (candidate)) {
2291 MonoGenericParam *param = get_generic_param (ctx, candidate);
2296 for (class = mono_generic_param_info (param)->constraints; class && *class; ++class) {
2297 /*256 should be enough since there can't be more than 255 generic arguments.*/
2298 if (recursive_boxed_constraint_type_check (ctx, type, *class, 256))
2303 if (mono_type_is_generic_argument (type))
2309 return MONO_TYPE_IS_REFERENCE (type) && mono_class_is_assignable_from (mono_class_from_mono_type (type), mono_class_from_mono_type (candidate));
2313 verify_stack_type_compatibility_full (VerifyContext *ctx, MonoType *type, ILStackDesc *stack, gboolean drop_byref, gboolean valuetype_must_be_boxed)
2315 MonoType *candidate = mono_type_from_stack_slot (stack);
2316 if (MONO_TYPE_IS_REFERENCE (type) && !type->byref && stack_slot_is_null_literal (stack))
2319 if (is_compatible_boxed_valuetype (ctx, type, candidate, stack, TRUE))
2322 if (valuetype_must_be_boxed && !stack_slot_is_boxed_value (stack) && !MONO_TYPE_IS_REFERENCE (candidate))
2325 if (!valuetype_must_be_boxed && stack_slot_is_boxed_value (stack))
2329 return verify_type_compatibility_full (ctx, type, mono_type_get_type_byval (candidate), FALSE);
2331 return verify_type_compatibility_full (ctx, type, candidate, FALSE);
2335 verify_stack_type_compatibility (VerifyContext *ctx, MonoType *type, ILStackDesc *stack)
2337 return verify_stack_type_compatibility_full (ctx, type, stack, FALSE, FALSE);
2341 mono_delegate_type_equal (MonoType *target, MonoType *candidate)
2343 if (candidate->byref ^ target->byref)
2346 switch (target->type) {
2347 case MONO_TYPE_VOID:
2350 case MONO_TYPE_BOOLEAN:
2353 case MONO_TYPE_CHAR:
2362 case MONO_TYPE_STRING:
2363 case MONO_TYPE_TYPEDBYREF:
2364 return candidate->type == target->type;
2367 return mono_delegate_type_equal (target->data.type, candidate->data.type);
2369 case MONO_TYPE_FNPTR:
2370 if (candidate->type != MONO_TYPE_FNPTR)
2372 return mono_delegate_signature_equal (mono_type_get_signature (target), mono_type_get_signature (candidate), FALSE);
2374 case MONO_TYPE_GENERICINST: {
2375 MonoClass *target_klass;
2376 MonoClass *candidate_klass;
2377 target_klass = mono_class_from_mono_type (target);
2378 candidate_klass = mono_class_from_mono_type (candidate);
2379 /*FIXME handle nullables and enum*/
2380 return mono_class_is_assignable_from (target_klass, candidate_klass);
2382 case MONO_TYPE_OBJECT:
2383 return MONO_TYPE_IS_REFERENCE (candidate);
2385 case MONO_TYPE_CLASS:
2386 return mono_class_is_assignable_from(target->data.klass, mono_class_from_mono_type (candidate));
2388 case MONO_TYPE_SZARRAY:
2389 if (candidate->type != MONO_TYPE_SZARRAY)
2391 return mono_class_is_assignable_from (mono_class_from_mono_type (target)->element_class, mono_class_from_mono_type (candidate)->element_class);
2393 case MONO_TYPE_ARRAY:
2394 if (candidate->type != MONO_TYPE_ARRAY)
2396 return is_array_type_compatible (target, candidate);
2398 case MONO_TYPE_VALUETYPE:
2399 /*FIXME handle nullables and enum*/
2400 return mono_class_from_mono_type (candidate) == mono_class_from_mono_type (target);
2403 return candidate->type == MONO_TYPE_VAR && mono_type_get_generic_param_num (target) == mono_type_get_generic_param_num (candidate);
2406 case MONO_TYPE_MVAR:
2407 return candidate->type == MONO_TYPE_MVAR && mono_type_get_generic_param_num (target) == mono_type_get_generic_param_num (candidate);
2411 VERIFIER_DEBUG ( printf ("Unknown type %d. Implement me!\n", target->type); );
2412 g_assert_not_reached ();
2418 mono_delegate_param_equal (MonoType *delegate, MonoType *method)
2420 if (mono_metadata_type_equal_full (delegate, method, TRUE))
2423 return mono_delegate_type_equal (method, delegate);
2427 mono_delegate_ret_equal (MonoType *delegate, MonoType *method)
2429 if (mono_metadata_type_equal_full (delegate, method, TRUE))
2432 return mono_delegate_type_equal (delegate, method);
2436 * mono_delegate_signature_equal:
2438 * Compare two signatures in the way expected by delegates.
2440 * This function only exists due to the fact that it should ignore the 'has_this' part of the signature.
2442 * FIXME can this function be eliminated and proper metadata functionality be used?
2445 mono_delegate_signature_equal (MonoMethodSignature *delegate_sig, MonoMethodSignature *method_sig, gboolean is_static_ldftn)
2448 int method_offset = is_static_ldftn ? 1 : 0;
2450 if (delegate_sig->param_count + method_offset != method_sig->param_count)
2453 if (delegate_sig->call_convention != method_sig->call_convention)
2456 for (i = 0; i < delegate_sig->param_count; i++) {
2457 MonoType *p1 = delegate_sig->params [i];
2458 MonoType *p2 = method_sig->params [i + method_offset];
2460 if (!mono_delegate_param_equal (p1, p2))
2464 if (!mono_delegate_ret_equal (delegate_sig->ret, method_sig->ret))
2471 mono_verifier_is_signature_compatible (MonoMethodSignature *target, MonoMethodSignature *candidate)
2473 return mono_delegate_signature_equal (target, candidate, FALSE);
2477 * verify_ldftn_delegate:
2479 * Verify properties of ldftn based delegates.
2482 verify_ldftn_delegate (VerifyContext *ctx, MonoClass *delegate, ILStackDesc *value, ILStackDesc *funptr)
2484 MonoMethod *method = funptr->method;
2486 /*ldftn non-final virtuals only allowed if method is not static,
2487 * the object is a this arg (comes from a ldarg.0), and there is no starg.0.
2488 * This rules doesn't apply if the object on stack is a boxed valuetype.
2490 if ((method->flags & METHOD_ATTRIBUTE_VIRTUAL) && !(method->flags & METHOD_ATTRIBUTE_FINAL) && !(method->klass->flags & TYPE_ATTRIBUTE_SEALED) && !stack_slot_is_boxed_value (value)) {
2491 /*A stdarg 0 must not happen, we fail here only in fail fast mode to avoid double error reports*/
2492 if (IS_FAIL_FAST_MODE (ctx) && ctx->has_this_store)
2493 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid ldftn with virtual function in method with stdarg 0 at 0x%04x", ctx->ip_offset));
2495 /*current method must not be static*/
2496 if (ctx->method->flags & METHOD_ATTRIBUTE_STATIC)
2497 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid ldftn with virtual function at 0x%04x", ctx->ip_offset));
2499 /*value is the this pointer, loaded using ldarg.0 */
2500 if (!stack_slot_is_this_pointer (value))
2501 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));
2503 ctx->code [ctx->ip_offset].flags |= IL_CODE_LDFTN_DELEGATE_NONFINAL_VIRTUAL;
2508 * verify_delegate_compatibility:
2510 * Verify delegate creation sequence.
2514 verify_delegate_compatibility (VerifyContext *ctx, MonoClass *delegate, ILStackDesc *value, ILStackDesc *funptr)
2516 #define IS_VALID_OPCODE(offset, opcode) (ip [ip_offset - offset] == opcode && (ctx->code [ip_offset - offset].flags & IL_CODE_FLAG_SEEN))
2517 #define IS_LOAD_FUN_PTR(kind) (IS_VALID_OPCODE (6, CEE_PREFIX1) && ip [ip_offset - 5] == kind)
2519 MonoMethod *invoke, *method;
2520 const guint8 *ip = ctx->header->code;
2521 guint32 ip_offset = ctx->ip_offset;
2522 gboolean is_static_ldftn = FALSE, is_first_arg_bound = FALSE;
2524 if (stack_slot_get_type (funptr) != TYPE_PTR || !funptr->method) {
2525 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid function pointer parameter for delegate constructor at 0x%04x", ctx->ip_offset));
2529 invoke = mono_get_delegate_invoke (delegate);
2530 method = funptr->method;
2532 if (!method || !mono_method_signature (method)) {
2533 char *name = mono_type_get_full_name (delegate);
2534 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid method on stack to create delegate %s construction at 0x%04x", name, ctx->ip_offset));
2539 if (!invoke || !mono_method_signature (invoke)) {
2540 char *name = mono_type_get_full_name (delegate);
2541 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Delegate type %s with bad Invoke method at 0x%04x", name, ctx->ip_offset));
2546 is_static_ldftn = (ip_offset > 5 && IS_LOAD_FUN_PTR (CEE_LDFTN)) && method->flags & METHOD_ATTRIBUTE_STATIC;
2548 if (is_static_ldftn)
2549 is_first_arg_bound = mono_method_signature (invoke)->param_count + 1 == mono_method_signature (method)->param_count;
2551 if (!mono_delegate_signature_equal (mono_method_signature (invoke), mono_method_signature (method), is_first_arg_bound)) {
2552 char *fun_sig = mono_signature_get_desc (mono_method_signature (method), FALSE);
2553 char *invoke_sig = mono_signature_get_desc (mono_method_signature (invoke), FALSE);
2554 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));
2556 g_free (invoke_sig);
2560 * Delegate code sequences:
2566 * [-6] ldvirtftn token
2570 if (ip_offset > 5 && IS_LOAD_FUN_PTR (CEE_LDFTN)) {
2571 verify_ldftn_delegate (ctx, delegate, value, funptr);
2572 } else if (ip_offset > 6 && IS_VALID_OPCODE (7, CEE_DUP) && IS_LOAD_FUN_PTR (CEE_LDVIRTFTN)) {
2573 ctx->code [ip_offset - 6].flags |= IL_CODE_DELEGATE_SEQUENCE;
2575 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid code sequence for delegate creation at 0x%04x", ctx->ip_offset));
2577 ctx->code [ip_offset].flags |= IL_CODE_DELEGATE_SEQUENCE;
2580 if (is_first_arg_bound) {
2581 if (mono_method_signature (method)->param_count == 0 || !verify_stack_type_compatibility_full (ctx, mono_method_signature (method)->params [0], value, FALSE, TRUE))
2582 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("This object not compatible with function pointer for delegate creation at 0x%04x", ctx->ip_offset));
2584 if (method->flags & METHOD_ATTRIBUTE_STATIC) {
2585 if (!stack_slot_is_null_literal (value) && !is_first_arg_bound)
2586 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Non-null this args used with static function for delegate creation at 0x%04x", ctx->ip_offset));
2588 if (!verify_stack_type_compatibility_full (ctx, &method->klass->byval_arg, value, FALSE, TRUE) && !stack_slot_is_null_literal (value))
2589 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("This object not compatible with function pointer for delegate creation at 0x%04x", ctx->ip_offset));
2593 if (stack_slot_get_type (value) != TYPE_COMPLEX)
2594 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid first parameter for delegate creation at 0x%04x", ctx->ip_offset));
2596 #undef IS_VALID_OPCODE
2597 #undef IS_LOAD_FUN_PTR
2600 /* implement the opcode checks*/
2602 push_arg (VerifyContext *ctx, unsigned int arg, int take_addr)
2606 if (arg >= ctx->max_args) {
2608 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Method doesn't have argument %d", arg + 1));
2610 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Method doesn't have argument %d", arg + 1));
2611 if (check_overflow (ctx)) //FIXME: what sane value could we ever push?
2612 stack_push_val (ctx, TYPE_I4, &mono_defaults.int32_class->byval_arg);
2614 } else if (check_overflow (ctx)) {
2615 /*We must let the value be pushed, otherwise we would get an underflow error*/
2616 check_unverifiable_type (ctx, ctx->params [arg]);
2617 if (ctx->params [arg]->byref && take_addr)
2618 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("ByRef of ByRef at 0x%04x", ctx->ip_offset));
2619 top = stack_push (ctx);
2620 if (!set_stack_value (ctx, top, ctx->params [arg], take_addr))
2623 if (arg == 0 && !(ctx->method->flags & METHOD_ATTRIBUTE_STATIC)) {
2625 ctx->has_this_store = TRUE;
2627 top->stype |= THIS_POINTER_MASK;
2628 if (mono_method_is_constructor (ctx->method) && !ctx->super_ctor_called && !ctx->method->klass->valuetype)
2629 top->stype |= UNINIT_THIS_MASK;
2635 push_local (VerifyContext *ctx, guint32 arg, int take_addr)
2637 if (arg >= ctx->num_locals) {
2638 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Method doesn't have local %d", arg + 1));
2639 } else if (check_overflow (ctx)) {
2640 /*We must let the value be pushed, otherwise we would get an underflow error*/
2641 check_unverifiable_type (ctx, ctx->locals [arg]);
2642 if (ctx->locals [arg]->byref && take_addr)
2643 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("ByRef of ByRef at 0x%04x", ctx->ip_offset));
2645 set_stack_value (ctx, stack_push (ctx), ctx->locals [arg], take_addr);
2650 store_arg (VerifyContext *ctx, guint32 arg)
2654 if (arg >= ctx->max_args) {
2655 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Method doesn't have argument %d at 0x%04x", arg + 1, ctx->ip_offset));
2656 if (check_underflow (ctx, 1))
2661 if (check_underflow (ctx, 1)) {
2662 value = stack_pop (ctx);
2663 if (!verify_stack_type_compatibility (ctx, ctx->params [arg], value)) {
2664 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Incompatible type %s in argument store at 0x%04x", stack_slot_get_name (value), ctx->ip_offset));
2667 if (arg == 0 && !(ctx->method->flags & METHOD_ATTRIBUTE_STATIC))
2668 ctx->has_this_store = 1;
2672 store_local (VerifyContext *ctx, guint32 arg)
2675 if (arg >= ctx->num_locals) {
2676 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Method doesn't have local var %d at 0x%04x", arg + 1, ctx->ip_offset));
2680 /*TODO verify definite assigment */
2681 if (check_underflow (ctx, 1)) {
2682 value = stack_pop(ctx);
2683 if (!verify_stack_type_compatibility (ctx, ctx->locals [arg], value)) {
2684 char *expected = mono_type_full_name (ctx->locals [arg]);
2685 char *found = stack_slot_full_name (value);
2686 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Incompatible type '%s' on stack cannot be stored to local %d with type '%s' at 0x%04x",
2697 /*FIXME add and sub needs special care here*/
2699 do_binop (VerifyContext *ctx, unsigned int opcode, const unsigned char table [TYPE_MAX][TYPE_MAX])
2701 ILStackDesc *a, *b, *top;
2702 int idxa, idxb, complexMerge = 0;
2705 if (!check_underflow (ctx, 2))
2707 b = stack_pop (ctx);
2708 a = stack_pop (ctx);
2710 idxa = stack_slot_get_underlying_type (a);
2711 if (stack_slot_is_managed_pointer (a)) {
2716 idxb = stack_slot_get_underlying_type (b);
2717 if (stack_slot_is_managed_pointer (b)) {
2724 res = table [idxa][idxb];
2726 VERIFIER_DEBUG ( printf ("binop res %d\n", res); );
2727 VERIFIER_DEBUG ( printf ("idxa %d idxb %d\n", idxa, idxb); );
2729 top = stack_push (ctx);
2730 if (res == TYPE_INV) {
2731 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)));
2732 copy_stack_value (top, a);
2736 if (res & NON_VERIFIABLE_RESULT) {
2737 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)));
2739 res = res & ~NON_VERIFIABLE_RESULT;
2742 if (complexMerge && res == TYPE_PTR) {
2743 if (complexMerge == 1)
2744 copy_stack_value (top, a);
2745 else if (complexMerge == 2)
2746 copy_stack_value (top, b);
2748 * There is no need to merge the type of two pointers.
2749 * The only valid operation is subtraction, that returns a native
2750 * int as result and can be used with any 2 pointer kinds.
2751 * This is valid acording to Patition III 1.1.4
2760 do_boolean_branch_op (VerifyContext *ctx, int delta)
2762 int target = ctx->ip_offset + delta;
2765 VERIFIER_DEBUG ( printf ("boolean branch offset %d delta %d target %d\n", ctx->ip_offset, delta, target); );
2767 if (target < 0 || target >= ctx->code_size) {
2768 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Boolean branch target out of code at 0x%04x", ctx->ip_offset));
2772 switch (is_valid_branch_instruction (ctx->header, ctx->ip_offset, target)) {
2774 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Branch target escapes out of exception block at 0x%04x", ctx->ip_offset));
2777 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Branch target escapes out of exception block at 0x%04x", ctx->ip_offset));
2781 ctx->target = target;
2783 if (!check_underflow (ctx, 1))
2786 top = stack_pop (ctx);
2787 if (!is_valid_bool_arg (top))
2788 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));
2790 check_unmanaged_pointer (ctx, top);
2794 stack_slot_is_complex_type_not_reference_type (ILStackDesc *slot)
2796 return stack_slot_get_type (slot) == TYPE_COMPLEX && !MONO_TYPE_IS_REFERENCE (slot->type) && !stack_slot_is_boxed_value (slot);
2800 do_branch_op (VerifyContext *ctx, signed int delta, const unsigned char table [TYPE_MAX][TYPE_MAX])
2805 int target = ctx->ip_offset + delta;
2807 VERIFIER_DEBUG ( printf ("branch offset %d delta %d target %d\n", ctx->ip_offset, delta, target); );
2809 if (target < 0 || target >= ctx->code_size) {
2810 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Branch target out of code at 0x%04x", ctx->ip_offset));
2814 switch (is_valid_cmp_branch_instruction (ctx->header, ctx->ip_offset, target)) {
2815 case 1: /*FIXME use constants and not magic numbers.*/
2816 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Branch target escapes out of exception block at 0x%04x", ctx->ip_offset));
2819 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Branch target escapes out of exception block at 0x%04x", ctx->ip_offset));
2823 ctx->target = target;
2825 if (!check_underflow (ctx, 2))
2828 b = stack_pop (ctx);
2829 a = stack_pop (ctx);
2831 idxa = stack_slot_get_underlying_type (a);
2832 if (stack_slot_is_managed_pointer (a))
2835 idxb = stack_slot_get_underlying_type (b);
2836 if (stack_slot_is_managed_pointer (b))
2839 if (stack_slot_is_complex_type_not_reference_type (a) || stack_slot_is_complex_type_not_reference_type (b)) {
2844 res = table [idxa][idxb];
2847 VERIFIER_DEBUG ( printf ("branch res %d\n", res); );
2848 VERIFIER_DEBUG ( printf ("idxa %d idxb %d\n", idxa, idxb); );
2850 if (res == TYPE_INV) {
2851 CODE_NOT_VERIFIABLE (ctx,
2852 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));
2853 } else if (res & NON_VERIFIABLE_RESULT) {
2854 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));
2855 res = res & ~NON_VERIFIABLE_RESULT;
2860 do_cmp_op (VerifyContext *ctx, const unsigned char table [TYPE_MAX][TYPE_MAX], guint32 opcode)
2866 if (!check_underflow (ctx, 2))
2868 b = stack_pop (ctx);
2869 a = stack_pop (ctx);
2871 if (opcode == CEE_CGT_UN) {
2872 if (stack_slot_get_type (a) == TYPE_COMPLEX && stack_slot_get_type (b) == TYPE_COMPLEX) {
2873 stack_push_val (ctx, TYPE_I4, &mono_defaults.int32_class->byval_arg);
2878 idxa = stack_slot_get_underlying_type (a);
2879 if (stack_slot_is_managed_pointer (a))
2882 idxb = stack_slot_get_underlying_type (b);
2883 if (stack_slot_is_managed_pointer (b))
2886 if (stack_slot_is_complex_type_not_reference_type (a) || stack_slot_is_complex_type_not_reference_type (b)) {
2891 res = table [idxa][idxb];
2894 if(res == TYPE_INV) {
2895 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));
2896 } else if (res & NON_VERIFIABLE_RESULT) {
2897 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));
2898 res = res & ~NON_VERIFIABLE_RESULT;
2900 stack_push_val (ctx, TYPE_I4, &mono_defaults.int32_class->byval_arg);
2904 do_ret (VerifyContext *ctx)
2906 MonoType *ret = ctx->signature->ret;
2907 VERIFIER_DEBUG ( printf ("checking ret\n"); );
2908 if (ret->type != MONO_TYPE_VOID) {
2910 if (!check_underflow (ctx, 1))
2913 top = stack_pop(ctx);
2915 if (!verify_stack_type_compatibility (ctx, ctx->signature->ret, top)) {
2916 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Incompatible return value on stack with method signature ret at 0x%04x", ctx->ip_offset));
2920 if (ret->byref || ret->type == MONO_TYPE_TYPEDBYREF || mono_type_is_value_type (ret, "System", "ArgIterator") || mono_type_is_value_type (ret, "System", "RuntimeArgumentHandle"))
2921 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Method returns byref, TypedReference, ArgIterator or RuntimeArgumentHandle at 0x%04x", ctx->ip_offset));
2924 if (ctx->eval.size > 0) {
2925 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Stack not empty (%d) after ret at 0x%04x", ctx->eval.size, ctx->ip_offset));
2927 if (in_any_block (ctx->header, ctx->ip_offset))
2928 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("ret cannot escape exception blocks at 0x%04x", ctx->ip_offset));
2932 * 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.
2933 * This is illegal but mono_get_method_full decoded it.
2934 * TODO handle calling .ctor outside one or calling the .ctor for other class but super
2937 do_invoke_method (VerifyContext *ctx, int method_token, gboolean virtual)
2940 MonoMethodSignature *sig;
2943 gboolean virt_check_this = FALSE;
2944 gboolean constrained = ctx->prefix_set & PREFIX_CONSTRAINED;
2946 if (!(method = verifier_load_method (ctx, method_token, virtual ? "callvirt" : "call")))
2950 CLEAR_PREFIX (ctx, PREFIX_CONSTRAINED);
2952 if (method->klass->valuetype) // && !constrained ???
2953 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use callvirtual with valuetype method at 0x%04x", ctx->ip_offset));
2955 if ((method->flags & METHOD_ATTRIBUTE_STATIC))
2956 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use callvirtual with static method at 0x%04x", ctx->ip_offset));
2959 if (method->flags & METHOD_ATTRIBUTE_ABSTRACT)
2960 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use call with an abstract method at 0x%04x", ctx->ip_offset));
2962 if ((method->flags & METHOD_ATTRIBUTE_VIRTUAL) && !(method->flags & METHOD_ATTRIBUTE_FINAL) && !(method->klass->flags & TYPE_ATTRIBUTE_SEALED)) {
2963 virt_check_this = TRUE;
2964 ctx->code [ctx->ip_offset].flags |= IL_CODE_CALL_NONFINAL_VIRTUAL;
2968 if (!(sig = mono_method_get_signature_full (method, ctx->image, method_token, ctx->generic_context)))
2969 sig = mono_method_get_signature (method, ctx->image, method_token);
2972 char *name = mono_type_get_full_name (method->klass);
2973 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Could not resolve signature of %s:%s at 0x%04x", name, method->name, ctx->ip_offset));
2978 param_count = sig->param_count + sig->hasthis;
2979 if (!check_underflow (ctx, param_count))
2982 for (i = sig->param_count - 1; i >= 0; --i) {
2983 VERIFIER_DEBUG ( printf ("verifying argument %d\n", i); );
2984 value = stack_pop (ctx);
2985 if (!verify_stack_type_compatibility (ctx, sig->params[i], value)) {
2986 char *stack_name = stack_slot_full_name (value);
2987 char *sig_name = mono_type_full_name (sig->params [i]);
2988 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));
2989 g_free (stack_name);
2993 if (stack_slot_is_managed_mutability_pointer (value))
2994 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));
2996 if ((ctx->prefix_set & PREFIX_TAIL) && stack_slot_is_managed_pointer (value)) {
2997 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));
3003 MonoType *type = &method->klass->byval_arg;
3006 if (mono_method_is_constructor (method) && !method->klass->valuetype) {
3007 if (!mono_method_is_constructor (ctx->method))
3008 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot call a constructor outside one at 0x%04x", ctx->ip_offset));
3009 if (method->klass != ctx->method->klass->parent && method->klass != ctx->method->klass)
3010 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));
3012 ctx->super_ctor_called = TRUE;
3013 value = stack_pop_safe (ctx);
3014 if ((value->stype & THIS_POINTER_MASK) != THIS_POINTER_MASK)
3015 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid 'this ptr' argument for constructor at 0x%04x", ctx->ip_offset));
3017 value = stack_pop (ctx);
3020 copy_stack_value (©, value);
3021 //TODO we should extract this to a 'drop_byref_argument' and use everywhere
3022 //Other parts of the code suffer from the same issue of
3023 copy.type = mono_type_get_type_byval (copy.type);
3024 copy.stype &= ~POINTER_MASK;
3026 if (virt_check_this && !stack_slot_is_this_pointer (value) && !(method->klass->valuetype || stack_slot_is_boxed_value (value)))
3027 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));
3029 if (constrained && virtual) {
3030 if (!stack_slot_is_managed_pointer (value))
3031 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Object is not a managed pointer for a constrained call at 0x%04x", ctx->ip_offset));
3032 if (!mono_metadata_type_equal_full (mono_type_get_type_byval (value->type), ctx->constrained_type, TRUE))
3033 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Object not compatible with constrained type at 0x%04x", ctx->ip_offset));
3034 copy.stype |= BOXED_MASK;
3036 if (stack_slot_is_managed_pointer (value) && !mono_class_from_mono_type (value->type)->valuetype)
3037 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));
3039 if (!virtual && mono_class_from_mono_type (value->type)->valuetype && !method->klass->valuetype && !stack_slot_is_boxed_value (value))
3040 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot call a valuetype baseclass at 0x%04x", ctx->ip_offset));
3042 if (virtual && mono_class_from_mono_type (value->type)->valuetype && !stack_slot_is_boxed_value (value))
3043 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use a valuetype with callvirt at 0x%04x", ctx->ip_offset));
3045 if (method->klass->valuetype && (stack_slot_is_boxed_value (value) || !stack_slot_is_managed_pointer (value)))
3046 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));
3048 if (!verify_stack_type_compatibility (ctx, type, ©)) {
3049 char *expected = mono_type_full_name (type);
3050 char *effective = stack_slot_full_name (©);
3051 char *method_name = mono_method_full_name (method, TRUE);
3052 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",
3053 expected, effective, method_name, ctx->ip_offset));
3054 g_free (method_name);
3059 if (!IS_SKIP_VISIBILITY (ctx) && !mono_method_can_access_method_full (ctx->method, method, mono_class_from_mono_type (value->type))) {
3060 char *name = mono_method_full_name (method, TRUE);
3061 CODE_NOT_VERIFIABLE2 (ctx, g_strdup_printf ("Method %s is not accessible at 0x%04x", name, ctx->ip_offset), MONO_EXCEPTION_METHOD_ACCESS);
3065 } else if (!IS_SKIP_VISIBILITY (ctx) && !mono_method_can_access_method_full (ctx->method, method, NULL)) {
3066 char *name = mono_method_full_name (method, TRUE);
3067 CODE_NOT_VERIFIABLE2 (ctx, g_strdup_printf ("Method %s is not accessible at 0x%04x", name, ctx->ip_offset), MONO_EXCEPTION_METHOD_ACCESS);
3071 if (sig->ret->type != MONO_TYPE_VOID) {
3072 if (!mono_type_is_valid_in_context (ctx, sig->ret))
3075 if (check_overflow (ctx)) {
3076 value = stack_push (ctx);
3077 set_stack_value (ctx, value, sig->ret, FALSE);
3078 if ((ctx->prefix_set & PREFIX_READONLY) && method->klass->rank && !strcmp (method->name, "Address")) {
3079 ctx->prefix_set &= ~PREFIX_READONLY;
3080 value->stype |= CMMP_MASK;
3085 if ((ctx->prefix_set & PREFIX_TAIL)) {
3086 if (!mono_delegate_ret_equal (mono_method_signature (ctx->method)->ret, sig->ret))
3087 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Tail call with incompatible return type at 0x%04x", ctx->ip_offset));
3088 if (ctx->header->code [ctx->ip_offset + 5] != CEE_RET)
3089 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Tail call not followed by ret at 0x%04x", ctx->ip_offset));
3095 do_push_static_field (VerifyContext *ctx, int token, gboolean take_addr)
3097 MonoClassField *field;
3099 if (!check_overflow (ctx))
3102 CLEAR_PREFIX (ctx, PREFIX_VOLATILE);
3104 if (!(field = verifier_load_field (ctx, token, &klass, take_addr ? "ldsflda" : "ldsfld")))
3107 if (!(field->type->attrs & FIELD_ATTRIBUTE_STATIC)) {
3108 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Cannot load non static field at 0x%04x", ctx->ip_offset));
3111 /*taking the address of initonly field only works from the static constructor */
3112 if (take_addr && (field->type->attrs & FIELD_ATTRIBUTE_INIT_ONLY) &&
3113 !(field->parent == ctx->method->klass && (ctx->method->flags & (METHOD_ATTRIBUTE_SPECIAL_NAME | METHOD_ATTRIBUTE_STATIC)) && !strcmp (".cctor", ctx->method->name)))
3114 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot take the address of a init-only field at 0x%04x", ctx->ip_offset));
3116 if (!IS_SKIP_VISIBILITY (ctx) && !mono_method_can_access_field_full (ctx->method, field, NULL))
3117 CODE_NOT_VERIFIABLE2 (ctx, g_strdup_printf ("Type at stack is not accessible at 0x%04x", ctx->ip_offset), MONO_EXCEPTION_FIELD_ACCESS);
3119 set_stack_value (ctx, stack_push (ctx), field->type, take_addr);
3123 do_store_static_field (VerifyContext *ctx, int token) {
3124 MonoClassField *field;
3127 CLEAR_PREFIX (ctx, PREFIX_VOLATILE);
3129 if (!check_underflow (ctx, 1))
3132 value = stack_pop (ctx);
3134 if (!(field = verifier_load_field (ctx, token, &klass, "stsfld")))
3137 if (!(field->type->attrs & FIELD_ATTRIBUTE_STATIC)) {
3138 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Cannot store non static field at 0x%04x", ctx->ip_offset));
3142 if (field->type->type == MONO_TYPE_TYPEDBYREF) {
3143 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Typedbyref field is an unverfiable type in store static field at 0x%04x", ctx->ip_offset));
3147 if (!IS_SKIP_VISIBILITY (ctx) && !mono_method_can_access_field_full (ctx->method, field, NULL))
3148 CODE_NOT_VERIFIABLE2 (ctx, g_strdup_printf ("Type at stack is not accessible at 0x%04x", ctx->ip_offset), MONO_EXCEPTION_FIELD_ACCESS);
3150 if (!verify_stack_type_compatibility (ctx, field->type, value)) {
3151 char *stack_name = stack_slot_full_name (value);
3152 char *field_name = mono_type_full_name (field->type);
3153 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Incompatible type in static field store expected '%s' but found '%s' at 0x%04x",
3154 field_name, stack_name, ctx->ip_offset));
3155 g_free (field_name);
3156 g_free (stack_name);
3161 check_is_valid_type_for_field_ops (VerifyContext *ctx, int token, ILStackDesc *obj, MonoClassField **ret_field, const char *opcode)
3163 MonoClassField *field;
3165 gboolean is_pointer;
3167 /*must be a reference type, a managed pointer, an unamanaged pointer, or a valuetype*/
3168 if (!(field = verifier_load_field (ctx, token, &klass, opcode)))
3172 //the value on stack is going to be used as a pointer
3173 is_pointer = stack_slot_get_type (obj) == TYPE_PTR || (stack_slot_get_type (obj) == TYPE_NATIVE_INT && !get_stack_type (&field->parent->byval_arg));
3175 if (field->type->type == MONO_TYPE_TYPEDBYREF) {
3176 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Typedbyref field is an unverfiable type at 0x%04x", ctx->ip_offset));
3179 g_assert (obj->type);
3181 /*The value on the stack must be a subclass of the defining type of the field*/
3182 /* we need to check if we can load the field from the stack value*/
3184 if (stack_slot_get_underlying_type (obj) == TYPE_NATIVE_INT)
3185 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Native int is not a verifiable type to reference a field at 0x%04x", ctx->ip_offset));
3187 if (!IS_SKIP_VISIBILITY (ctx) && !mono_method_can_access_field_full (ctx->method, field, NULL))
3188 CODE_NOT_VERIFIABLE2 (ctx, g_strdup_printf ("Type at stack is not accessible at 0x%04x", ctx->ip_offset), MONO_EXCEPTION_FIELD_ACCESS);
3190 if (!field->parent->valuetype && stack_slot_is_managed_pointer (obj))
3191 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));
3193 /*a value type can be loaded from a value or a managed pointer, but not a boxed object*/
3194 if (field->parent->valuetype && stack_slot_is_boxed_value (obj))
3195 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));
3197 if (!stack_slot_is_null_literal (obj) && !verify_stack_type_compatibility_full (ctx, &field->parent->byval_arg, obj, TRUE, FALSE)) {
3198 char *found = stack_slot_full_name (obj);
3199 char *expected = mono_type_full_name (&field->parent->byval_arg);
3200 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));
3205 if (!IS_SKIP_VISIBILITY (ctx) && !mono_method_can_access_field_full (ctx->method, field, mono_class_from_mono_type (obj->type)))
3206 CODE_NOT_VERIFIABLE2 (ctx, g_strdup_printf ("Type at stack is not accessible at 0x%04x", ctx->ip_offset), MONO_EXCEPTION_FIELD_ACCESS);
3209 check_unmanaged_pointer (ctx, obj);
3214 do_push_field (VerifyContext *ctx, int token, gboolean take_addr)
3217 MonoClassField *field;
3220 CLEAR_PREFIX (ctx, PREFIX_UNALIGNED | PREFIX_VOLATILE);
3222 if (!check_underflow (ctx, 1))
3224 obj = stack_pop_safe (ctx);
3226 if (!check_is_valid_type_for_field_ops (ctx, token, obj, &field, take_addr ? "ldflda" : "ldfld"))
3229 if (take_addr && field->parent->valuetype && !stack_slot_is_managed_pointer (obj))
3230 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot take the address of a temporary value-type at 0x%04x", ctx->ip_offset));
3232 if (take_addr && (field->type->attrs & FIELD_ATTRIBUTE_INIT_ONLY) &&
3233 !(field->parent == ctx->method->klass && mono_method_is_constructor (ctx->method)))
3234 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot take the address of a init-only field at 0x%04x", ctx->ip_offset));
3236 set_stack_value (ctx, stack_push (ctx), field->type, take_addr);
3240 do_store_field (VerifyContext *ctx, int token)
3242 ILStackDesc *value, *obj;
3243 MonoClassField *field;
3244 CLEAR_PREFIX (ctx, PREFIX_UNALIGNED | PREFIX_VOLATILE);
3246 if (!check_underflow (ctx, 2))
3249 value = stack_pop (ctx);
3250 obj = stack_pop_safe (ctx);
3252 if (!check_is_valid_type_for_field_ops (ctx, token, obj, &field, "stfld"))
3255 if (!verify_stack_type_compatibility (ctx, field->type, value))
3256 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Incompatible type %s in field store at 0x%04x", stack_slot_get_name (value), ctx->ip_offset));
3259 /*TODO proper handle for Nullable<T>*/
3261 do_box_value (VerifyContext *ctx, int klass_token)
3264 MonoType *type = get_boxable_mono_type (ctx, klass_token, "box");
3270 if (!check_underflow (ctx, 1))
3273 value = stack_pop (ctx);
3274 /*box is a nop for reference types*/
3276 if (stack_slot_get_underlying_type (value) == TYPE_COMPLEX && MONO_TYPE_IS_REFERENCE (value->type) && MONO_TYPE_IS_REFERENCE (type)) {
3277 stack_push_stack_val (ctx, value)->stype |= BOXED_MASK;
3282 if (!verify_stack_type_compatibility (ctx, type, value))
3283 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid type at stack for boxing operation at 0x%04x", ctx->ip_offset));
3285 klass = mono_class_from_mono_type (type);
3286 if (mono_class_is_nullable (klass))
3287 type = &mono_class_get_nullable_param (klass)->byval_arg;
3288 stack_push_val (ctx, TYPE_COMPLEX | BOXED_MASK, type);
3292 do_unbox_value (VerifyContext *ctx, int klass_token)
3295 MonoType *type = get_boxable_mono_type (ctx, klass_token, "unbox");
3300 if (!check_underflow (ctx, 1))
3303 if (!mono_class_from_mono_type (type)->valuetype)
3304 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid reference type for unbox at 0x%04x", ctx->ip_offset));
3306 value = stack_pop (ctx);
3308 /*Value should be: a boxed valuetype or a reference type*/
3309 if (!(stack_slot_get_type (value) == TYPE_COMPLEX &&
3310 (stack_slot_is_boxed_value (value) || !mono_class_from_mono_type (value->type)->valuetype)))
3311 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));
3313 set_stack_value (ctx, value = stack_push (ctx), mono_type_get_type_byref (type), FALSE);
3314 value->stype |= CMMP_MASK;
3318 do_unbox_any (VerifyContext *ctx, int klass_token)
3321 MonoType *type = get_boxable_mono_type (ctx, klass_token, "unbox.any");
3326 if (!check_underflow (ctx, 1))
3329 value = stack_pop (ctx);
3331 /*Value should be: a boxed valuetype or a reference type*/
3332 if (!(stack_slot_get_type (value) == TYPE_COMPLEX &&
3333 (stack_slot_is_boxed_value (value) || !mono_class_from_mono_type (value->type)->valuetype)))
3334 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));
3336 set_stack_value (ctx, stack_push (ctx), type, FALSE);
3340 do_unary_math_op (VerifyContext *ctx, int op)
3343 if (!check_underflow (ctx, 1))
3345 value = stack_pop (ctx);
3346 switch (stack_slot_get_type (value)) {
3349 case TYPE_NATIVE_INT:
3354 case TYPE_COMPLEX: /*only enums are ok*/
3355 if (mono_type_is_enum_type (value->type))
3358 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid type at stack for unary not at 0x%04x", ctx->ip_offset));
3360 stack_push_stack_val (ctx, value);
3364 do_conversion (VerifyContext *ctx, int kind)
3367 if (!check_underflow (ctx, 1))
3369 value = stack_pop (ctx);
3371 switch (stack_slot_get_type (value)) {
3374 case TYPE_NATIVE_INT:
3378 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));
3383 stack_push_val (ctx, TYPE_I4, &mono_defaults.int32_class->byval_arg);
3386 stack_push_val (ctx,TYPE_I8, &mono_defaults.int64_class->byval_arg);
3389 stack_push_val (ctx, TYPE_R8, &mono_defaults.double_class->byval_arg);
3391 case TYPE_NATIVE_INT:
3392 stack_push_val (ctx, TYPE_NATIVE_INT, &mono_defaults.int_class->byval_arg);
3395 g_error ("unknown type %02x in conversion", kind);
3401 do_load_token (VerifyContext *ctx, int token)
3404 MonoClass *handle_class;
3405 if (!check_overflow (ctx))
3408 if (ctx->method->wrapper_type != MONO_WRAPPER_NONE) {
3409 handle = mono_method_get_wrapper_data (ctx->method, token);
3410 handle_class = mono_method_get_wrapper_data (ctx->method, token + 1);
3411 if (handle_class == mono_defaults.typehandle_class)
3412 handle = &((MonoClass*)handle)->byval_arg;
3414 switch (token & 0xff000000) {
3415 case MONO_TOKEN_TYPE_DEF:
3416 case MONO_TOKEN_TYPE_REF:
3417 case MONO_TOKEN_TYPE_SPEC:
3418 case MONO_TOKEN_FIELD_DEF:
3419 case MONO_TOKEN_METHOD_DEF:
3420 case MONO_TOKEN_METHOD_SPEC:
3421 case MONO_TOKEN_MEMBER_REF:
3422 if (!token_bounds_check (ctx->image, token)) {
3423 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));
3428 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));
3432 handle = mono_ldtoken (ctx->image, token, &handle_class, ctx->generic_context);
3436 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid token 0x%x for ldtoken at 0x%04x", token, ctx->ip_offset));
3439 if (handle_class == mono_defaults.typehandle_class) {
3440 mono_type_is_valid_in_context (ctx, (MonoType*)handle);
3441 } else if (handle_class == mono_defaults.methodhandle_class) {
3442 mono_method_is_valid_in_context (ctx, (MonoMethod*)handle);
3443 } else if (handle_class == mono_defaults.fieldhandle_class) {
3444 mono_type_is_valid_in_context (ctx, &((MonoClassField*)handle)->parent->byval_arg);
3446 ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid ldtoken type %x at 0x%04x", token, ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE);
3448 stack_push_val (ctx, TYPE_COMPLEX, mono_class_get_type (handle_class));
3452 do_ldobj_value (VerifyContext *ctx, int token)
3455 MonoType *type = get_boxable_mono_type (ctx, token, "ldobj");
3456 CLEAR_PREFIX (ctx, PREFIX_UNALIGNED | PREFIX_VOLATILE);
3461 if (!check_underflow (ctx, 1))
3464 value = stack_pop (ctx);
3465 if (!stack_slot_is_managed_pointer (value)
3466 && stack_slot_get_type (value) != TYPE_NATIVE_INT
3467 && !(stack_slot_get_type (value) == TYPE_PTR && value->type->type != MONO_TYPE_FNPTR)) {
3468 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid argument %s to ldobj at 0x%04x", stack_slot_get_name (value), ctx->ip_offset));
3472 if (stack_slot_get_type (value) == TYPE_NATIVE_INT)
3473 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Using native pointer to ldobj at 0x%04x", ctx->ip_offset));
3475 /*We have a byval on the stack, but the comparison must be strict. */
3476 if (!verify_type_compatibility_full (ctx, type, mono_type_get_type_byval (value->type), TRUE))
3477 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid type at stack for ldojb operation at 0x%04x", ctx->ip_offset));
3479 set_stack_value (ctx, stack_push (ctx), type, FALSE);
3483 do_stobj (VerifyContext *ctx, int token)
3485 ILStackDesc *dest, *src;
3486 MonoType *type = get_boxable_mono_type (ctx, token, "stobj");
3487 CLEAR_PREFIX (ctx, PREFIX_UNALIGNED | PREFIX_VOLATILE);
3492 if (!check_underflow (ctx, 2))
3495 src = stack_pop (ctx);
3496 dest = stack_pop (ctx);
3498 if (stack_slot_is_managed_mutability_pointer (dest))
3499 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use a readonly pointer with stobj at 0x%04x", ctx->ip_offset));
3501 if (!stack_slot_is_managed_pointer (dest))
3502 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid destination of stobj operation at 0x%04x", ctx->ip_offset));
3504 if (stack_slot_is_boxed_value (src) && !MONO_TYPE_IS_REFERENCE (src->type) && !MONO_TYPE_IS_REFERENCE (type))
3505 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));
3507 if (!verify_stack_type_compatibility (ctx, type, src)) {
3508 char *type_name = mono_type_full_name (type);
3509 char *src_name = stack_slot_full_name (src);
3510 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));
3515 if (!verify_type_compatibility (ctx, mono_type_get_type_byval (dest->type), type))
3516 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Destination and token types of stobj don't match at 0x%04x", ctx->ip_offset));
3520 do_cpobj (VerifyContext *ctx, int token)
3522 ILStackDesc *dest, *src;
3523 MonoType *type = get_boxable_mono_type (ctx, token, "cpobj");
3527 if (!check_underflow (ctx, 2))
3530 src = stack_pop (ctx);
3531 dest = stack_pop (ctx);
3533 if (!stack_slot_is_managed_pointer (src))
3534 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid source of cpobj operation at 0x%04x", ctx->ip_offset));
3536 if (!stack_slot_is_managed_pointer (dest))
3537 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid destination of cpobj operation at 0x%04x", ctx->ip_offset));
3539 if (stack_slot_is_managed_mutability_pointer (dest))
3540 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use a readonly pointer with cpobj at 0x%04x", ctx->ip_offset));
3542 if (!verify_type_compatibility (ctx, type, mono_type_get_type_byval (src->type)))
3543 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Token and source types of cpobj don't match at 0x%04x", ctx->ip_offset));
3545 if (!verify_type_compatibility (ctx, mono_type_get_type_byval (dest->type), type))
3546 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Destination and token types of cpobj don't match at 0x%04x", ctx->ip_offset));
3550 do_initobj (VerifyContext *ctx, int token)
3553 MonoType *stack, *type = get_boxable_mono_type (ctx, token, "initobj");
3557 if (!check_underflow (ctx, 1))
3560 obj = stack_pop (ctx);
3562 if (!stack_slot_is_managed_pointer (obj))
3563 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid object address for initobj at 0x%04x", ctx->ip_offset));
3565 if (stack_slot_is_managed_mutability_pointer (obj))
3566 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use a readonly pointer with initobj at 0x%04x", ctx->ip_offset));
3568 stack = mono_type_get_type_byval (obj->type);
3569 if (MONO_TYPE_IS_REFERENCE (stack)) {
3570 if (!verify_type_compatibility (ctx, stack, type))
3571 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Type token of initobj not compatible with value on stack at 0x%04x", ctx->ip_offset));
3572 else if (IS_STRICT_MODE (ctx) && !mono_metadata_type_equal (type, stack))
3573 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Type token of initobj not compatible with value on stack at 0x%04x", ctx->ip_offset));
3574 } else if (!verify_type_compatibility (ctx, stack, type)) {
3575 char *expected_name = mono_type_full_name (type);
3576 char *stack_name = mono_type_full_name (stack);
3578 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));
3579 g_free (expected_name);
3580 g_free (stack_name);
3585 do_newobj (VerifyContext *ctx, int token)
3589 MonoMethodSignature *sig;
3591 gboolean is_delegate = FALSE;
3593 if (!(method = verifier_load_method (ctx, token, "newobj")))
3596 if (!mono_method_is_constructor (method)) {
3597 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Method from token 0x%08x not a constructor at 0x%04x", token, ctx->ip_offset));
3601 if (method->klass->flags & (TYPE_ATTRIBUTE_ABSTRACT | TYPE_ATTRIBUTE_INTERFACE))
3602 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Trying to instantiate an abstract or interface type at 0x%04x", ctx->ip_offset));
3604 if (!mono_method_can_access_method_full (ctx->method, method, NULL)) {
3605 char *from = mono_method_full_name (ctx->method, TRUE);
3606 char *to = mono_method_full_name (method, TRUE);
3607 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);
3612 //FIXME use mono_method_get_signature_full
3613 sig = mono_method_signature (method);
3615 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid constructor signature to newobj at 0x%04x", ctx->ip_offset));
3619 if (!sig->hasthis) {
3620 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid constructor signature missing hasthis at 0x%04x", ctx->ip_offset));
3624 if (!check_underflow (ctx, sig->param_count))
3627 is_delegate = method->klass->parent == mono_defaults.multicastdelegate_class;
3630 ILStackDesc *funptr;
3631 //first arg is object, second arg is fun ptr
3632 if (sig->param_count != 2) {
3633 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid delegate constructor at 0x%04x", ctx->ip_offset));
3636 funptr = stack_pop (ctx);
3637 value = stack_pop (ctx);
3638 verify_delegate_compatibility (ctx, method->klass, value, funptr);
3640 for (i = sig->param_count - 1; i >= 0; --i) {
3641 VERIFIER_DEBUG ( printf ("verifying constructor argument %d\n", i); );
3642 value = stack_pop (ctx);
3643 if (!verify_stack_type_compatibility (ctx, sig->params [i], value)) {
3644 char *stack_name = stack_slot_full_name (value);
3645 char *sig_name = mono_type_full_name (sig->params [i]);
3646 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));
3647 g_free (stack_name);
3651 if (stack_slot_is_managed_mutability_pointer (value))
3652 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use a readonly pointer as argument of newobj at 0x%04x", ctx->ip_offset));
3656 if (check_overflow (ctx))
3657 set_stack_value (ctx, stack_push (ctx), &method->klass->byval_arg, FALSE);
3661 do_cast (VerifyContext *ctx, int token, const char *opcode) {
3667 if (!check_underflow (ctx, 1))
3670 if (!(type = get_boxable_mono_type (ctx, token, opcode)))
3674 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid %s type at 0x%04x", opcode, ctx->ip_offset));
3678 value = stack_pop (ctx);
3679 is_boxed = stack_slot_is_boxed_value (value);
3681 if (stack_slot_is_managed_pointer (value))
3682 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid value for %s at 0x%04x", opcode, ctx->ip_offset));
3683 else if (!MONO_TYPE_IS_REFERENCE (value->type) && !is_boxed) {
3684 char *name = stack_slot_full_name (value);
3685 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));
3689 switch (value->type->type) {
3690 case MONO_TYPE_FNPTR:
3692 case MONO_TYPE_TYPEDBYREF:
3693 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid value for %s at 0x%04x", opcode, ctx->ip_offset));
3696 do_box = is_boxed || mono_type_is_generic_argument(type) || mono_class_from_mono_type (type)->valuetype;
3697 stack_push_val (ctx, TYPE_COMPLEX | (do_box ? BOXED_MASK : 0), type);
3701 mono_type_from_opcode (int opcode) {
3709 return &mono_defaults.sbyte_class->byval_arg;
3717 return &mono_defaults.int16_class->byval_arg;
3725 return &mono_defaults.int32_class->byval_arg;
3731 return &mono_defaults.int64_class->byval_arg;
3737 return &mono_defaults.single_class->byval_arg;
3743 return &mono_defaults.double_class->byval_arg;
3749 return &mono_defaults.int_class->byval_arg;
3753 case CEE_LDELEM_REF:
3754 case CEE_STELEM_REF:
3755 return &mono_defaults.object_class->byval_arg;
3758 g_error ("unknown opcode %02x in mono_type_from_opcode ", opcode);
3764 do_load_indirect (VerifyContext *ctx, int opcode)
3767 CLEAR_PREFIX (ctx, PREFIX_UNALIGNED | PREFIX_VOLATILE);
3769 if (!check_underflow (ctx, 1))
3772 value = stack_pop (ctx);
3773 if (!stack_slot_is_managed_pointer (value)) {
3774 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Load indirect not using a manager pointer at 0x%04x", ctx->ip_offset));
3775 set_stack_value (ctx, stack_push (ctx), mono_type_from_opcode (opcode), FALSE);
3779 if (opcode == CEE_LDIND_REF) {
3780 if (stack_slot_get_underlying_type (value) != TYPE_COMPLEX || mono_class_from_mono_type (value->type)->valuetype)
3781 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid type at stack for ldind_ref expected object byref operation at 0x%04x", ctx->ip_offset));
3782 set_stack_value (ctx, stack_push (ctx), mono_type_get_type_byval (value->type), FALSE);
3784 if (!verify_type_compatibility_full (ctx, mono_type_from_opcode (opcode), mono_type_get_type_byval (value->type), TRUE))
3785 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid type at stack for ldind 0x%x operation at 0x%04x", opcode, ctx->ip_offset));
3786 set_stack_value (ctx, stack_push (ctx), mono_type_from_opcode (opcode), FALSE);
3791 do_store_indirect (VerifyContext *ctx, int opcode)
3793 ILStackDesc *addr, *val;
3794 CLEAR_PREFIX (ctx, PREFIX_UNALIGNED | PREFIX_VOLATILE);
3796 if (!check_underflow (ctx, 2))
3799 val = stack_pop (ctx);
3800 addr = stack_pop (ctx);
3802 check_unmanaged_pointer (ctx, addr);
3804 if (!stack_slot_is_managed_pointer (addr) && stack_slot_get_type (addr) != TYPE_PTR) {
3805 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid non-pointer argument to stind at 0x%04x", ctx->ip_offset));
3809 if (stack_slot_is_managed_mutability_pointer (addr)) {
3810 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use a readonly pointer with stind at 0x%04x", ctx->ip_offset));
3814 if (!verify_type_compatibility_full (ctx, mono_type_from_opcode (opcode), mono_type_get_type_byval (addr->type), TRUE))
3815 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid addr type at stack for stind 0x%x operation at 0x%04x", opcode, ctx->ip_offset));
3817 if (!verify_stack_type_compatibility (ctx, mono_type_from_opcode (opcode), val))
3818 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid value type at stack for stind 0x%x operation at 0x%04x", opcode, ctx->ip_offset));
3822 do_newarr (VerifyContext *ctx, int token)
3825 MonoType *type = get_boxable_mono_type (ctx, token, "newarr");
3830 if (!check_underflow (ctx, 1))
3833 value = stack_pop (ctx);
3834 if (stack_slot_get_type (value) != TYPE_I4 && stack_slot_get_type (value) != TYPE_NATIVE_INT)
3835 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));
3837 set_stack_value (ctx, stack_push (ctx), mono_class_get_type (mono_array_class_get (mono_class_from_mono_type (type), 1)), FALSE);
3840 /*FIXME handle arrays that are not 0-indexed*/
3842 do_ldlen (VerifyContext *ctx)
3846 if (!check_underflow (ctx, 1))
3849 value = stack_pop (ctx);
3851 if (stack_slot_get_type (value) != TYPE_COMPLEX || value->type->type != MONO_TYPE_SZARRAY)
3852 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type for ldlen at 0x%04x", ctx->ip_offset));
3854 stack_push_val (ctx, TYPE_NATIVE_INT, &mono_defaults.int_class->byval_arg);
3857 /*FIXME handle arrays that are not 0-indexed*/
3858 /*FIXME handle readonly prefix and CMMP*/
3860 do_ldelema (VerifyContext *ctx, int klass_token)
3862 ILStackDesc *index, *array, *res;
3863 MonoType *type = get_boxable_mono_type (ctx, klass_token, "ldelema");
3869 if (!check_underflow (ctx, 2))
3872 index = stack_pop (ctx);
3873 array = stack_pop (ctx);
3875 if (stack_slot_get_type (index) != TYPE_I4 && stack_slot_get_type (index) != TYPE_NATIVE_INT)
3876 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));
3878 if (!stack_slot_is_null_literal (array)) {
3879 if (stack_slot_get_type (array) != TYPE_COMPLEX || array->type->type != MONO_TYPE_SZARRAY)
3880 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type(%s) for ldelema at 0x%04x", stack_slot_get_name (array), ctx->ip_offset));
3882 if (get_stack_type (type) == TYPE_I4 || get_stack_type (type) == TYPE_NATIVE_INT) {
3883 valid = verify_type_compatibility_full (ctx, type, &array->type->data.klass->byval_arg, TRUE);
3885 valid = mono_metadata_type_equal (type, &array->type->data.klass->byval_arg);
3888 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type on stack for ldelema at 0x%04x", ctx->ip_offset));
3892 res = stack_push (ctx);
3893 set_stack_value (ctx, res, type, TRUE);
3894 if (ctx->prefix_set & PREFIX_READONLY) {
3895 ctx->prefix_set &= ~PREFIX_READONLY;
3896 res->stype |= CMMP_MASK;
3901 * FIXME handle arrays that are not 0-indexed
3902 * FIXME handle readonly prefix and CMMP
3905 do_ldelem (VerifyContext *ctx, int opcode, int token)
3907 #define IS_ONE_OF2(T, A, B) (T == A || T == B)
3908 ILStackDesc *index, *array;
3910 if (!check_underflow (ctx, 2))
3913 if (opcode == CEE_LDELEM) {
3914 if (!(type = verifier_load_type (ctx, token, "ldelem.any"))) {
3915 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Type (0x%08x) not found at 0x%04x", token, ctx->ip_offset));
3919 type = mono_type_from_opcode (opcode);
3922 index = stack_pop (ctx);
3923 array = stack_pop (ctx);
3925 if (stack_slot_get_type (index) != TYPE_I4 && stack_slot_get_type (index) != TYPE_NATIVE_INT)
3926 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));
3928 if (!stack_slot_is_null_literal (array)) {
3929 if (stack_slot_get_type (array) != TYPE_COMPLEX || array->type->type != MONO_TYPE_SZARRAY)
3930 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));
3932 if (opcode == CEE_LDELEM_REF) {
3933 if (array->type->data.klass->valuetype)
3934 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type is not a reference type for ldelem.ref 0x%04x", ctx->ip_offset));
3935 type = &array->type->data.klass->byval_arg;
3937 MonoType *candidate = &array->type->data.klass->byval_arg;
3938 if (IS_STRICT_MODE (ctx)) {
3939 MonoType *underlying_type = mono_type_get_underlying_type_any (type);
3940 MonoType *underlying_candidate = mono_type_get_underlying_type_any (candidate);
3941 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)) ||
3942 (IS_ONE_OF2 (underlying_candidate->type, MONO_TYPE_I4, MONO_TYPE_U4) && IS_ONE_OF2 (underlying_type->type, MONO_TYPE_I, MONO_TYPE_U)))
3943 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type on stack for ldelem.X at 0x%04x", ctx->ip_offset));
3945 if (!verify_type_compatibility_full (ctx, type, candidate, TRUE))
3946 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type on stack for ldelem.X at 0x%04x", ctx->ip_offset));
3951 set_stack_value (ctx, stack_push (ctx), type, FALSE);
3956 * FIXME handle arrays that are not 0-indexed
3959 do_stelem (VerifyContext *ctx, int opcode, int token)
3961 ILStackDesc *index, *array, *value;
3963 if (!check_underflow (ctx, 3))
3966 if (opcode == CEE_STELEM) {
3967 if (!(type = verifier_load_type (ctx, token, "stelem.any"))) {
3968 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Type (0x%08x) not found at 0x%04x", token, ctx->ip_offset));
3972 type = mono_type_from_opcode (opcode);
3975 value = stack_pop (ctx);
3976 index = stack_pop (ctx);
3977 array = stack_pop (ctx);
3979 if (stack_slot_get_type (index) != TYPE_I4 && stack_slot_get_type (index) != TYPE_NATIVE_INT)
3980 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));
3982 if (!stack_slot_is_null_literal (array)) {
3983 if (stack_slot_get_type (array) != TYPE_COMPLEX || array->type->type != MONO_TYPE_SZARRAY) {
3984 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));
3986 if (opcode == CEE_STELEM_REF) {
3987 if (array->type->data.klass->valuetype)
3988 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type is not a reference type for stelem.ref 0x%04x", ctx->ip_offset));
3989 } else if (!verify_type_compatibility_full (ctx, &array->type->data.klass->byval_arg, type, TRUE)) {
3990 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type on stack for stdelem.X at 0x%04x", ctx->ip_offset));
3994 if (opcode == CEE_STELEM_REF) {
3995 if (!stack_slot_is_boxed_value (value) && mono_class_from_mono_type (value->type)->valuetype)
3996 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid value is not a reference type for stelem.ref 0x%04x", ctx->ip_offset));
3997 } else if (opcode != CEE_STELEM_REF) {
3998 if (!verify_stack_type_compatibility (ctx, type, value))
3999 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid value on stack for stdelem.X at 0x%04x", ctx->ip_offset));
4001 if (stack_slot_is_boxed_value (value) && !MONO_TYPE_IS_REFERENCE (value->type) && !MONO_TYPE_IS_REFERENCE (type))
4002 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));
4008 do_throw (VerifyContext *ctx)
4010 ILStackDesc *exception;
4011 if (!check_underflow (ctx, 1))
4013 exception = stack_pop (ctx);
4015 if (!stack_slot_is_null_literal (exception) && !(stack_slot_get_type (exception) == TYPE_COMPLEX && !mono_class_from_mono_type (exception->type)->valuetype))
4016 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid type on stack for throw, expected reference type at 0x%04x", ctx->ip_offset));
4018 if (mono_type_is_generic_argument (exception->type) && !stack_slot_is_boxed_value (exception)) {
4019 char *name = mono_type_full_name (exception->type);
4020 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));
4023 /*The stack is left empty after a throw*/
4029 do_endfilter (VerifyContext *ctx)
4031 MonoExceptionClause *clause;
4033 if (IS_STRICT_MODE (ctx)) {
4034 if (ctx->eval.size != 1)
4035 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Stack size must have one item for endfilter at 0x%04x", ctx->ip_offset));
4037 if (ctx->eval.size >= 1 && stack_slot_get_type (stack_pop (ctx)) != TYPE_I4)
4038 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Stack item type is not an int32 for endfilter at 0x%04x", ctx->ip_offset));
4041 if ((clause = is_correct_endfilter (ctx, ctx->ip_offset))) {
4042 if (IS_STRICT_MODE (ctx)) {
4043 if (ctx->ip_offset != clause->handler_offset - 2)
4044 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("endfilter is not the last instruction of the filter clause at 0x%04x", ctx->ip_offset));
4046 if ((ctx->ip_offset != clause->handler_offset - 2) && !MONO_OFFSET_IN_HANDLER (clause, ctx->ip_offset))
4047 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("endfilter is not the last instruction of the filter clause at 0x%04x", ctx->ip_offset));
4050 if (IS_STRICT_MODE (ctx) && !is_unverifiable_endfilter (ctx, ctx->ip_offset))
4051 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("endfilter outside filter clause at 0x%04x", ctx->ip_offset));
4053 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("endfilter outside filter clause at 0x%04x", ctx->ip_offset));
4060 do_leave (VerifyContext *ctx, int delta)
4062 int target = ((gint32)ctx->ip_offset) + delta;
4063 if (target >= ctx->code_size || target < 0)
4064 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Branch target out of code at 0x%04x", ctx->ip_offset));
4066 if (!is_correct_leave (ctx->header, ctx->ip_offset, target))
4067 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Leave not allowed in finally block at 0x%04x", ctx->ip_offset));
4069 ctx->target = target;
4075 * Verify br and br.s opcodes.
4078 do_static_branch (VerifyContext *ctx, int delta)
4080 int target = ctx->ip_offset + delta;
4081 if (target < 0 || target >= ctx->code_size) {
4082 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("branch target out of code at 0x%04x", ctx->ip_offset));
4086 switch (is_valid_branch_instruction (ctx->header, ctx->ip_offset, target)) {
4088 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Branch target escapes out of exception block at 0x%04x", ctx->ip_offset));
4091 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Branch target escapes out of exception block at 0x%04x", ctx->ip_offset));
4095 ctx->target = target;
4099 do_switch (VerifyContext *ctx, int count, const unsigned char *data)
4101 int i, base = ctx->ip_offset + 5 + count * 4;
4104 if (!check_underflow (ctx, 1))
4107 value = stack_pop (ctx);
4109 if (stack_slot_get_type (value) != TYPE_I4 && stack_slot_get_type (value) != TYPE_NATIVE_INT)
4110 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid argument to switch at 0x%04x", ctx->ip_offset));
4112 for (i = 0; i < count; ++i) {
4113 int target = base + read32 (data + i * 4);
4115 if (target < 0 || target >= ctx->code_size) {
4116 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Switch target %x out of code at 0x%04x", i, ctx->ip_offset));
4120 switch (is_valid_branch_instruction (ctx->header, ctx->ip_offset, target)) {
4122 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Switch target %x escapes out of exception block at 0x%04x", i, ctx->ip_offset));
4125 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Switch target %x escapes out of exception block at 0x%04x", i, ctx->ip_offset));
4128 merge_stacks (ctx, &ctx->eval, &ctx->code [target], FALSE, TRUE);
4133 do_load_function_ptr (VerifyContext *ctx, guint32 token, gboolean virtual)
4138 if (virtual && !check_underflow (ctx, 1))
4141 if (!virtual && !check_overflow (ctx))
4144 if (ctx->method->wrapper_type != MONO_WRAPPER_NONE) {
4145 method = mono_method_get_wrapper_data (ctx->method, (guint32)token);
4147 ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid token %x for ldftn at 0x%04x", token, ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE);
4151 if (!IS_METHOD_DEF_OR_REF_OR_SPEC (token) || !token_bounds_check (ctx->image, token)) {
4152 ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid token %x for ldftn at 0x%04x", token, ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE);
4156 if (!(method = verifier_load_method (ctx, token, virtual ? "ldvirtfrn" : "ldftn")))
4160 if (mono_method_is_constructor (method))
4161 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use ldftn with a constructor at 0x%04x", ctx->ip_offset));
4164 ILStackDesc *top = stack_pop (ctx);
4166 if (stack_slot_get_type (top) != TYPE_COMPLEX || top->type->type == MONO_TYPE_VALUETYPE)
4167 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid argument to ldvirtftn at 0x%04x", ctx->ip_offset));
4169 if (method->flags & METHOD_ATTRIBUTE_STATIC)
4170 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use ldvirtftn with a constructor at 0x%04x", ctx->ip_offset));
4172 if (!verify_stack_type_compatibility (ctx, &method->klass->byval_arg, top))
4173 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Unexpected object for ldvirtftn at 0x%04x", ctx->ip_offset));
4176 if (!mono_method_can_access_method_full (ctx->method, method, NULL))
4177 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);
4179 top = stack_push_val(ctx, TYPE_PTR, mono_type_create_fnptr_from_mono_method (ctx, method));
4180 top->method = method;
4184 do_sizeof (VerifyContext *ctx, int token)
4188 if (!(type = verifier_load_type (ctx, token, "sizeof")))
4191 if (type->byref && type->type != MONO_TYPE_TYPEDBYREF) {
4192 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid use of byref type at 0x%04x", ctx->ip_offset));
4196 if (type->type == MONO_TYPE_VOID) {
4197 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid use of void type at 0x%04x", ctx->ip_offset));
4201 if (check_overflow (ctx))
4202 set_stack_value (ctx, stack_push (ctx), &mono_defaults.uint32_class->byval_arg, FALSE);
4205 /* Stack top can be of any type, the runtime doesn't care and treat everything as an int. */
4207 do_localloc (VerifyContext *ctx)
4211 if (ctx->eval.size != 1) {
4212 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Stack must have only size item in localloc at 0x%04x", ctx->ip_offset));
4216 if (in_any_exception_block (ctx->header, ctx->ip_offset)) {
4217 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Stack must have only size item in localloc at 0x%04x", ctx->ip_offset));
4221 /*TODO verify top type*/
4222 top = stack_pop (ctx);
4224 set_stack_value (ctx, stack_push (ctx), &mono_defaults.int_class->byval_arg, FALSE);
4225 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Instruction localloc in never verifiable at 0x%04x", ctx->ip_offset));
4229 do_ldstr (VerifyContext *ctx, guint32 token)
4231 GSList *error = NULL;
4232 if (ctx->method->wrapper_type == MONO_WRAPPER_NONE) {
4233 if (mono_metadata_token_code (token) != MONO_TOKEN_STRING) {
4234 ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid string token %x at 0x%04x", token, ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE);
4238 if (!mono_verifier_verify_string_signature (ctx->image, mono_metadata_token_index (token), &error)) {
4240 ctx->list = g_slist_concat (ctx->list, error);
4241 ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid string index %x at 0x%04x", token, ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE);
4246 if (check_overflow (ctx))
4247 stack_push_val (ctx, TYPE_COMPLEX, &mono_defaults.string_class->byval_arg);
4251 do_refanyval (VerifyContext *ctx, int token)
4255 if (!check_underflow (ctx, 1))
4258 if (!(type = get_boxable_mono_type (ctx, token, "refanyval")))
4261 top = stack_pop (ctx);
4263 if (top->stype != TYPE_PTR || top->type->type != MONO_TYPE_TYPEDBYREF)
4264 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));
4266 set_stack_value (ctx, stack_push (ctx), type, TRUE);
4270 do_refanytype (VerifyContext *ctx)
4274 if (!check_underflow (ctx, 1))
4277 top = stack_pop (ctx);
4279 if (top->stype != TYPE_PTR || top->type->type != MONO_TYPE_TYPEDBYREF)
4280 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));
4282 set_stack_value (ctx, stack_push (ctx), &mono_defaults.typehandle_class->byval_arg, FALSE);
4287 do_mkrefany (VerifyContext *ctx, int token)
4291 if (!check_underflow (ctx, 1))
4294 if (!(type = get_boxable_mono_type (ctx, token, "refanyval")))
4297 top = stack_pop (ctx);
4299 if (stack_slot_is_managed_mutability_pointer (top))
4300 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use a readonly pointer with mkrefany at 0x%04x", ctx->ip_offset));
4302 if (!stack_slot_is_managed_pointer (top)) {
4303 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));
4305 MonoType *stack_type = mono_type_get_type_byval (top->type);
4306 if (MONO_TYPE_IS_REFERENCE (type) && !mono_metadata_type_equal (type, stack_type))
4307 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Type not compatible for mkrefany at 0x%04x", ctx->ip_offset));
4309 if (!MONO_TYPE_IS_REFERENCE (type) && !verify_type_compatibility_full (ctx, type, stack_type, TRUE))
4310 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Type not compatible for mkrefany at 0x%04x", ctx->ip_offset));
4313 set_stack_value (ctx, stack_push (ctx), &mono_defaults.typed_reference_class->byval_arg, FALSE);
4317 do_ckfinite (VerifyContext *ctx)
4320 if (!check_underflow (ctx, 1))
4323 top = stack_pop (ctx);
4325 if (stack_slot_get_underlying_type (top) != TYPE_R8)
4326 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));
4327 stack_push_stack_val (ctx, top);
4331 * Merge the stacks and perform compat checks. The merge check if types of @from are mergeable with type of @to
4333 * @from holds new values for a given control path
4334 * @to holds the current values of a given control path
4336 * TODO we can eliminate the from argument as all callers pass &ctx->eval
4339 merge_stacks (VerifyContext *ctx, ILCodeDesc *from, ILCodeDesc *to, gboolean start, gboolean external)
4343 stack_init (ctx, to);
4346 if (to->flags == IL_CODE_FLAG_NOT_PROCESSED)
4349 stack_copy (&ctx->eval, to);
4351 } else if (!(to->flags & IL_CODE_STACK_MERGED)) {
4352 stack_copy (to, &ctx->eval);
4355 VERIFIER_DEBUG ( printf ("performing stack merge %d x %d\n", from->size, to->size); );
4357 if (from->size != to->size) {
4358 VERIFIER_DEBUG ( printf ("different stack sizes %d x %d at 0x%04x\n", from->size, to->size, ctx->ip_offset); );
4359 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));
4363 //FIXME we need to preserve CMMP attributes
4364 //FIXME we must take null literals into consideration.
4365 for (i = 0; i < from->size; ++i) {
4366 ILStackDesc *new_slot = from->stack + i;
4367 ILStackDesc *old_slot = to->stack + i;
4368 MonoType *new_type = mono_type_from_stack_slot (new_slot);
4369 MonoType *old_type = mono_type_from_stack_slot (old_slot);
4370 MonoClass *old_class = mono_class_from_mono_type (old_type);
4371 MonoClass *new_class = mono_class_from_mono_type (new_type);
4372 MonoClass *match_class = NULL;
4374 // S := T then U = S (new value is compatible with current value, keep current)
4375 if (verify_stack_type_compatibility (ctx, old_type, new_slot)) {
4376 copy_stack_value (new_slot, old_slot);
4380 // T := S then U = T (old value is compatible with current value, use new)
4381 if (verify_stack_type_compatibility (ctx, new_type, old_slot)) {
4382 copy_stack_value (old_slot, new_slot);
4386 if (mono_type_is_generic_argument (old_type) || mono_type_is_generic_argument (new_type)) {
4387 char *old_name = stack_slot_full_name (old_slot);
4388 char *new_name = stack_slot_full_name (new_slot);
4389 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));
4395 //both are reference types, use closest common super type
4396 if (!mono_class_from_mono_type (old_type)->valuetype
4397 && !mono_class_from_mono_type (new_type)->valuetype
4398 && !stack_slot_is_managed_pointer (old_slot)
4399 && !stack_slot_is_managed_pointer (new_slot)) {
4401 for (j = MIN (old_class->idepth, new_class->idepth) - 1; j > 0; --j) {
4402 if (mono_metadata_type_equal (&old_class->supertypes [j]->byval_arg, &new_class->supertypes [j]->byval_arg)) {
4403 match_class = old_class->supertypes [j];
4408 mono_class_setup_interfaces (old_class, &error);
4409 if (!mono_error_ok (&error)) {
4410 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));
4411 mono_error_cleanup (&error);
4414 for (j = 0; j < old_class->interface_count; ++j) {
4415 for (k = 0; k < new_class->interface_count; ++k) {
4416 if (mono_metadata_type_equal (&old_class->interfaces [j]->byval_arg, &new_class->interfaces [k]->byval_arg)) {
4417 match_class = old_class->interfaces [j];
4423 //No decent super type found, use object
4424 match_class = mono_defaults.object_class;
4426 } 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)) {
4427 match_class = mono_defaults.object_class;
4432 char *old_name = stack_slot_full_name (old_slot);
4433 char *new_name = stack_slot_full_name (new_slot);
4434 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));
4438 set_stack_value (ctx, old_slot, &new_class->byval_arg, stack_slot_is_managed_pointer (old_slot));
4442 g_assert (match_class);
4443 set_stack_value (ctx, old_slot, &match_class->byval_arg, stack_slot_is_managed_pointer (old_slot));
4444 set_stack_value (ctx, new_slot, &match_class->byval_arg, stack_slot_is_managed_pointer (old_slot));
4450 to->flags |= IL_CODE_FLAG_WAS_TARGET;
4451 to->flags |= IL_CODE_STACK_MERGED;
4454 #define HANDLER_START(clause) ((clause)->flags == MONO_EXCEPTION_CLAUSE_FILTER ? (clause)->data.filter_offset : clause->handler_offset)
4455 #define IS_CATCH_OR_FILTER(clause) ((clause)->flags == MONO_EXCEPTION_CLAUSE_FILTER || (clause)->flags == MONO_EXCEPTION_CLAUSE_NONE)
4458 * is_clause_in_range :
4460 * Returns TRUE if either the protected block or the handler of @clause is in the @start - @end range.
4463 is_clause_in_range (MonoExceptionClause *clause, guint32 start, guint32 end)
4465 if (clause->try_offset >= start && clause->try_offset < end)
4467 if (HANDLER_START (clause) >= start && HANDLER_START (clause) < end)
4473 * is_clause_inside_range :
4475 * Returns TRUE if @clause lies completely inside the @start - @end range.
4478 is_clause_inside_range (MonoExceptionClause *clause, guint32 start, guint32 end)
4480 if (clause->try_offset < start || (clause->try_offset + clause->try_len) > end)
4482 if (HANDLER_START (clause) < start || (clause->handler_offset + clause->handler_len) > end)
4488 * is_clause_nested :
4490 * Returns TRUE if @nested is nested in @clause.
4493 is_clause_nested (MonoExceptionClause *clause, MonoExceptionClause *nested)
4495 if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER && is_clause_inside_range (nested, clause->data.filter_offset, clause->handler_offset))
4497 return is_clause_inside_range (nested, clause->try_offset, clause->try_offset + clause->try_len) ||
4498 is_clause_inside_range (nested, clause->handler_offset, clause->handler_offset + clause->handler_len);
4501 /* Test the relationship between 2 exception clauses. Follow P.1 12.4.2.7 of ECMA
4502 * the each pair of exception must have the following properties:
4503 * - one is fully nested on another (the outer must not be a filter clause) (the nested one must come earlier)
4504 * - completely disjoin (none of the 3 regions of each entry overlap with the other 3)
4505 * - mutual protection (protected block is EXACT the same, handlers are disjoin and all handler are catch or all handler are filter)
4508 verify_clause_relationship (VerifyContext *ctx, MonoExceptionClause *clause, MonoExceptionClause *to_test)
4510 /*clause is nested*/
4511 if (to_test->flags == MONO_EXCEPTION_CLAUSE_FILTER && is_clause_inside_range (clause, to_test->data.filter_offset, to_test->handler_offset)) {
4512 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Exception clause inside filter"));
4516 /*wrong nesting order.*/
4517 if (is_clause_nested (clause, to_test)) {
4518 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Nested exception clause appears after enclosing clause"));
4522 /*mutual protection*/
4523 if (clause->try_offset == to_test->try_offset && clause->try_len == to_test->try_len) {
4524 /*handlers are not disjoint*/
4525 if (is_clause_in_range (to_test, HANDLER_START (clause), clause->handler_offset + clause->handler_len)) {
4526 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Exception handlers overlap"));
4529 /* handlers are not catch or filter */
4530 if (!IS_CATCH_OR_FILTER (clause) || !IS_CATCH_OR_FILTER (to_test)) {
4531 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Exception clauses with shared protected block are neither catch or filter"));
4538 /*not completelly disjoint*/
4539 if ((is_clause_in_range (to_test, clause->try_offset, clause->try_offset + clause->try_len) ||
4540 is_clause_in_range (to_test, HANDLER_START (clause), clause->handler_offset + clause->handler_len)) && !is_clause_nested (to_test, clause))
4541 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Exception clauses overlap"));
4544 #define code_bounds_check(size) \
4545 if (ADDP_IS_GREATER_OR_OVF (ip, size, end)) {\
4546 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Code overrun starting with 0x%x at 0x%04x", *ip, ctx.ip_offset)); \
4551 mono_opcode_is_prefix (int op)
4554 case MONO_CEE_UNALIGNED_:
4555 case MONO_CEE_VOLATILE_:
4556 case MONO_CEE_TAIL_:
4557 case MONO_CEE_CONSTRAINED_:
4558 case MONO_CEE_READONLY_:
4565 * FIXME: need to distinguish between valid and verifiable.
4566 * Need to keep track of types on the stack.
4567 * Verify types for opcodes.
4570 mono_method_verify (MonoMethod *method, int level)
4573 const unsigned char *ip, *code_start;
4574 const unsigned char *end;
4575 MonoSimpleBasicBlock *bb = NULL, *original_bb = NULL;
4577 int i, n, need_merge = 0, start = 0;
4578 guint token, ip_offset = 0, prefix = 0;
4579 MonoGenericContext *generic_context = NULL;
4583 VERIFIER_DEBUG ( printf ("Verify IL for method %s %s %s\n", method->klass->name_space, method->klass->name, method->name); );
4585 init_verifier_stats ();
4587 if (method->iflags & (METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL | METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
4588 (method->flags & (METHOD_ATTRIBUTE_PINVOKE_IMPL | METHOD_ATTRIBUTE_ABSTRACT))) {
4592 memset (&ctx, 0, sizeof (VerifyContext));
4594 //FIXME use mono_method_get_signature_full
4595 ctx.signature = mono_method_signature (method);
4596 if (!ctx.signature) {
4597 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Could not decode method signature"));
4599 finish_collect_stats ();
4602 ctx.header = mono_method_get_header (method);
4604 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Could not decode method header"));
4605 finish_collect_stats ();
4608 ctx.method = method;
4609 code_start = ip = ctx.header->code;
4610 end = ip + ctx.header->code_size;
4611 ctx.image = image = method->klass->image;
4614 ctx.max_args = ctx.signature->param_count + ctx.signature->hasthis;
4615 ctx.max_stack = ctx.header->max_stack;
4616 ctx.verifiable = ctx.valid = 1;
4619 ctx.code = g_new (ILCodeDesc, ctx.header->code_size);
4620 ctx.code_size = ctx.header->code_size;
4621 MEM_ALLOC (sizeof (ILCodeDesc) * ctx.header->code_size);
4623 memset(ctx.code, 0, sizeof (ILCodeDesc) * ctx.header->code_size);
4625 ctx.num_locals = ctx.header->num_locals;
4626 ctx.locals = g_memdup (ctx.header->locals, sizeof (MonoType*) * ctx.header->num_locals);
4627 MEM_ALLOC (sizeof (MonoType*) * ctx.header->num_locals);
4629 if (ctx.num_locals > 0 && !ctx.header->init_locals)
4630 CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Method with locals variable but without init locals set"));
4632 ctx.params = g_new (MonoType*, ctx.max_args);
4633 MEM_ALLOC (sizeof (MonoType*) * ctx.max_args);
4635 if (ctx.signature->hasthis)
4636 ctx.params [0] = method->klass->valuetype ? &method->klass->this_arg : &method->klass->byval_arg;
4637 memcpy (ctx.params + ctx.signature->hasthis, ctx.signature->params, sizeof (MonoType *) * ctx.signature->param_count);
4639 if (ctx.signature->is_inflated)
4640 ctx.generic_context = generic_context = mono_method_get_context (method);
4642 if (!generic_context && (method->klass->generic_container || method->is_generic)) {
4643 if (method->is_generic)
4644 ctx.generic_context = generic_context = &(mono_method_get_generic_container (method)->context);
4646 ctx.generic_context = generic_context = &method->klass->generic_container->context;
4649 for (i = 0; i < ctx.num_locals; ++i) {
4650 MonoType *uninflated = ctx.locals [i];
4651 ctx.locals [i] = mono_class_inflate_generic_type_checked (ctx.locals [i], ctx.generic_context, &error);
4652 if (!mono_error_ok (&error)) {
4653 char *name = mono_type_full_name (ctx.locals [i] ? ctx.locals [i] : uninflated);
4654 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid local %d of type %s", i, name));
4656 mono_error_cleanup (&error);
4657 /* we must not free (in cleanup) what was not yet allocated (but only copied) */
4663 for (i = 0; i < ctx.max_args; ++i) {
4664 MonoType *uninflated = ctx.params [i];
4665 ctx.params [i] = mono_class_inflate_generic_type_checked (ctx.params [i], ctx.generic_context, &error);
4666 if (!mono_error_ok (&error)) {
4667 char *name = mono_type_full_name (ctx.params [i] ? ctx.params [i] : uninflated);
4668 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid parameter %d of type %s", i, name));
4670 mono_error_cleanup (&error);
4671 /* we must not free (in cleanup) what was not yet allocated (but only copied) */
4676 stack_init (&ctx, &ctx.eval);
4678 for (i = 0; i < ctx.num_locals; ++i) {
4679 if (!mono_type_is_valid_in_context (&ctx, ctx.locals [i]))
4681 if (get_stack_type (ctx.locals [i]) == TYPE_INV) {
4682 char *name = mono_type_full_name (ctx.locals [i]);
4683 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid local %i of type %s", i, name));
4690 for (i = 0; i < ctx.max_args; ++i) {
4691 if (!mono_type_is_valid_in_context (&ctx, ctx.params [i]))
4694 if (get_stack_type (ctx.params [i]) == TYPE_INV) {
4695 char *name = mono_type_full_name (ctx.params [i]);
4696 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid parameter %i of type %s", i, name));
4705 for (i = 0; i < ctx.header->num_clauses && ctx.valid; ++i) {
4706 MonoExceptionClause *clause = ctx.header->clauses + i;
4707 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); );
4709 if (clause->try_offset > ctx.code_size || ADD_IS_GREATER_OR_OVF (clause->try_offset, clause->try_len, ctx.code_size))
4710 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("try clause out of bounds at 0x%04x", clause->try_offset));
4712 if (clause->try_len <= 0)
4713 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("try clause len <= 0 at 0x%04x", clause->try_offset));
4715 if (clause->handler_offset > ctx.code_size || ADD_IS_GREATER_OR_OVF (clause->handler_offset, clause->handler_len, ctx.code_size))
4716 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("handler clause out of bounds at 0x%04x", clause->try_offset));
4718 if (clause->handler_len <= 0)
4719 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("handler clause len <= 0 at 0x%04x", clause->try_offset));
4721 if (clause->try_offset < clause->handler_offset && ADD_IS_GREATER_OR_OVF (clause->try_offset, clause->try_len, HANDLER_START (clause)))
4722 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("try block (at 0x%04x) includes handler block (at 0x%04x)", clause->try_offset, clause->handler_offset));
4724 if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
4725 if (clause->data.filter_offset > ctx.code_size)
4726 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("filter clause out of bounds at 0x%04x", clause->try_offset));
4728 if (clause->data.filter_offset >= clause->handler_offset)
4729 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("filter clause must come before the handler clause at 0x%04x", clause->data.filter_offset));
4732 for (n = i + 1; n < ctx.header->num_clauses && ctx.valid; ++n)
4733 verify_clause_relationship (&ctx, clause, ctx.header->clauses + n);
4738 ctx.code [clause->try_offset].flags |= IL_CODE_FLAG_WAS_TARGET;
4739 if (clause->try_offset + clause->try_len < ctx.code_size)
4740 ctx.code [clause->try_offset + clause->try_len].flags |= IL_CODE_FLAG_WAS_TARGET;
4741 if (clause->handler_offset + clause->handler_len < ctx.code_size)
4742 ctx.code [clause->handler_offset + clause->handler_len].flags |= IL_CODE_FLAG_WAS_TARGET;
4744 if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE) {
4745 if (!clause->data.catch_class) {
4746 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Catch clause %d with invalid type", i));
4750 init_stack_with_value_at_exception_boundary (&ctx, ctx.code + clause->handler_offset, clause->data.catch_class);
4752 else if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
4753 init_stack_with_value_at_exception_boundary (&ctx, ctx.code + clause->data.filter_offset, mono_defaults.exception_class);
4754 init_stack_with_value_at_exception_boundary (&ctx, ctx.code + clause->handler_offset, mono_defaults.exception_class);
4758 original_bb = bb = mono_basic_block_split (method, &error);
4759 if (!mono_error_ok (&error)) {
4760 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid branch target: %s", mono_error_get_message (&error)));
4761 mono_error_cleanup (&error);
4766 while (ip < end && ctx.valid) {
4768 ip_offset = ip - code_start;
4770 const unsigned char *ip_copy = ip;
4773 if (ip_offset > bb->end) {
4774 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Branch or EH block at [0x%04x] targets middle instruction at 0x%04x", bb->end, ip_offset));
4778 if (ip_offset == bb->end)
4781 op_size = mono_opcode_value_and_size (&ip_copy, end, &op);
4782 if (op_size == -1) {
4783 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid instruction %x at 0x%04x", *ip, ip_offset));
4787 if (ADD_IS_GREATER_OR_OVF (ip_offset, op_size, bb->end)) {
4788 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Branch or EH block targets middle of instruction at 0x%04x", ip_offset));
4792 /*Last Instruction*/
4793 if (ip_offset + op_size == bb->end && mono_opcode_is_prefix (op)) {
4794 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));
4799 ctx.ip_offset = ip_offset = ip - code_start;
4801 /*We need to check against fallthrou in and out of protected blocks.
4802 * For fallout we check the once a protected block ends, if the start flag is not set.
4803 * Likewise for fallthru in, we check if ip is the start of a protected block and start is not set
4804 * TODO convert these checks to be done using flags and not this loop
4806 for (i = 0; i < ctx.header->num_clauses && ctx.valid; ++i) {
4807 MonoExceptionClause *clause = ctx.header->clauses + i;
4809 if ((clause->try_offset + clause->try_len == ip_offset) && start == 0) {
4810 CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("fallthru off try block at 0x%04x", ip_offset));
4814 if ((clause->handler_offset + clause->handler_len == ip_offset) && start == 0) {
4815 if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER)
4816 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("fallout of handler block at 0x%04x", ip_offset));
4818 CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("fallout of handler block at 0x%04x", ip_offset));
4822 if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER && clause->handler_offset == ip_offset && start == 0) {
4823 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("fallout of filter block at 0x%04x", ip_offset));
4827 if (clause->handler_offset == ip_offset && start == 0) {
4828 CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("fallthru handler block at 0x%04x", ip_offset));
4832 if (clause->try_offset == ip_offset && ctx.eval.size > 0 && start == 0) {
4833 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Try to enter try block with a non-empty stack at 0x%04x", ip_offset));
4838 /*This must be done after fallthru detection otherwise it won't happen.*/
4840 /*FIXME remove this once we move all bad branch checking code to use BB only*/
4841 ctx.code [ip_offset].flags |= IL_CODE_FLAG_SEEN;
4850 VERIFIER_DEBUG ( printf ("extra merge needed! 0x%04x \n", ctx.target); );
4851 merge_stacks (&ctx, &ctx.eval, &ctx.code [ctx.target], FALSE, TRUE);
4854 merge_stacks (&ctx, &ctx.eval, &ctx.code[ip_offset], start, FALSE);
4857 /*TODO we can fast detect a forward branch or exception block targeting code after prefix, we should fail fast*/
4858 #ifdef MONO_VERIFIER_DEBUG
4861 discode = mono_disasm_code_one (NULL, method, ip, NULL);
4862 discode [strlen (discode) - 1] = 0; /* no \n */
4863 g_print ("[%d] %-29s (%d)\n", ip_offset, discode, ctx.eval.size);
4866 dump_stack_state (&ctx.code [ip_offset]);
4867 dump_stack_state (&ctx.eval);
4880 push_arg (&ctx, *ip - CEE_LDARG_0, FALSE);
4886 code_bounds_check (2);
4887 push_arg (&ctx, ip [1], *ip == CEE_LDARGA_S);
4891 case CEE_ADD_OVF_UN:
4892 do_binop (&ctx, *ip, add_ovf_un_table);
4896 case CEE_SUB_OVF_UN:
4897 do_binop (&ctx, *ip, sub_ovf_un_table);
4904 case CEE_MUL_OVF_UN:
4905 do_binop (&ctx, *ip, bin_ovf_table);
4910 do_binop (&ctx, *ip, add_table);
4915 do_binop (&ctx, *ip, sub_table);
4922 do_binop (&ctx, *ip, bin_op_table);
4931 do_binop (&ctx, *ip, int_bin_op_table);
4938 do_binop (&ctx, *ip, shift_op_table);
4943 if (!check_underflow (&ctx, 1))
4945 stack_pop_safe (&ctx);
4959 /*TODO support definite assignment verification? */
4960 push_local (&ctx, *ip - CEE_LDLOC_0, FALSE);
4968 store_local (&ctx, *ip - CEE_STLOC_0);
4973 code_bounds_check (2);
4974 store_local (&ctx, ip [1]);
4979 code_bounds_check (2);
4980 store_arg (&ctx, ip [1]);
4994 if (check_overflow (&ctx))
4995 stack_push_val (&ctx, TYPE_I4, &mono_defaults.int32_class->byval_arg);
5000 code_bounds_check (2);
5001 if (check_overflow (&ctx))
5002 stack_push_val (&ctx, TYPE_I4, &mono_defaults.int32_class->byval_arg);
5007 code_bounds_check (5);
5008 if (check_overflow (&ctx))
5009 stack_push_val (&ctx,TYPE_I4, &mono_defaults.int32_class->byval_arg);
5014 code_bounds_check (9);
5015 if (check_overflow (&ctx))
5016 stack_push_val (&ctx,TYPE_I8, &mono_defaults.int64_class->byval_arg);
5021 code_bounds_check (5);
5022 if (check_overflow (&ctx))
5023 stack_push_val (&ctx, TYPE_R8, &mono_defaults.double_class->byval_arg);
5028 code_bounds_check (9);
5029 if (check_overflow (&ctx))
5030 stack_push_val (&ctx, TYPE_R8, &mono_defaults.double_class->byval_arg);
5035 if (check_overflow (&ctx))
5036 stack_push_val (&ctx, TYPE_COMPLEX | NULL_LITERAL_MASK, &mono_defaults.object_class->byval_arg);
5042 code_bounds_check (2);
5043 do_branch_op (&ctx, (signed char)ip [1] + 2, cmp_br_eq_op);
5056 code_bounds_check (2);
5057 do_branch_op (&ctx, (signed char)ip [1] + 2, cmp_br_op);
5064 code_bounds_check (5);
5065 do_branch_op (&ctx, (gint32)read32 (ip + 1) + 5, cmp_br_eq_op);
5078 code_bounds_check (5);
5079 do_branch_op (&ctx, (gint32)read32 (ip + 1) + 5, cmp_br_op);
5086 code_bounds_check (2);
5087 push_local (&ctx, ip[1], *ip == CEE_LDLOCA_S);
5092 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Use of the `unused' opcode"));
5098 if (!check_underflow (&ctx, 1))
5100 if (!check_overflow (&ctx))
5102 top = stack_push (&ctx);
5103 copy_stack_value (top, stack_peek (&ctx, 1));
5109 code_bounds_check (5);
5111 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Eval stack must be empty in jmp at 0x%04x", ip_offset));
5112 token = read32 (ip + 1);
5113 if (in_any_block (ctx.header, ip_offset))
5114 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("jmp cannot escape exception blocks at 0x%04x", ip_offset));
5116 CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Intruction jmp is not verifiable at 0x%04x", ctx.ip_offset));
5118 * FIXME: check signature, retval, arguments etc.
5124 code_bounds_check (5);
5125 do_invoke_method (&ctx, read32 (ip + 1), *ip == CEE_CALLVIRT);
5130 code_bounds_check (5);
5131 token = read32 (ip + 1);
5133 * FIXME: check signature, retval, arguments etc.
5134 * FIXME: check requirements for tail call
5136 CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Intruction calli is not verifiable at 0x%04x", ctx.ip_offset));
5140 code_bounds_check (2);
5141 do_static_branch (&ctx, (signed char)ip [1] + 2);
5149 code_bounds_check (2);
5150 do_boolean_branch_op (&ctx, (signed char)ip [1] + 2);
5156 code_bounds_check (5);
5157 do_static_branch (&ctx, (gint32)read32 (ip + 1) + 5);
5165 code_bounds_check (5);
5166 do_boolean_branch_op (&ctx, (gint32)read32 (ip + 1) + 5);
5173 code_bounds_check (5);
5174 entries = read32 (ip + 1);
5176 if (entries > 0xFFFFFFFFU / sizeof (guint32))
5177 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Too many switch entries %x at 0x%04x", entries, ctx.ip_offset));
5180 code_bounds_check (sizeof (guint32) * entries);
5182 do_switch (&ctx, entries, ip);
5183 ip += sizeof (guint32) * entries;
5197 do_load_indirect (&ctx, *ip);
5209 do_store_indirect (&ctx, *ip);
5215 do_unary_math_op (&ctx, *ip);
5225 do_conversion (&ctx, TYPE_I4);
5231 do_conversion (&ctx, TYPE_I8);
5238 do_conversion (&ctx, TYPE_R8);
5244 do_conversion (&ctx, TYPE_NATIVE_INT);
5249 code_bounds_check (5);
5250 do_cpobj (&ctx, read32 (ip + 1));
5255 code_bounds_check (5);
5256 do_ldobj_value (&ctx, read32 (ip + 1));
5261 code_bounds_check (5);
5262 do_ldstr (&ctx, read32 (ip + 1));
5267 code_bounds_check (5);
5268 do_newobj (&ctx, read32 (ip + 1));
5274 code_bounds_check (5);
5275 do_cast (&ctx, read32 (ip + 1), *ip == CEE_CASTCLASS ? "castclass" : "isinst");
5281 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Use of the `unused' opcode"));
5286 code_bounds_check (5);
5287 do_unbox_value (&ctx, read32 (ip + 1));
5299 code_bounds_check (5);
5300 do_push_field (&ctx, read32 (ip + 1), *ip == CEE_LDFLDA);
5306 code_bounds_check (5);
5307 do_push_static_field (&ctx, read32 (ip + 1), *ip == CEE_LDSFLDA);
5312 code_bounds_check (5);
5313 do_store_field (&ctx, read32 (ip + 1));
5318 code_bounds_check (5);
5319 do_store_static_field (&ctx, read32 (ip + 1));
5324 code_bounds_check (5);
5325 do_stobj (&ctx, read32 (ip + 1));
5329 case CEE_CONV_OVF_I1_UN:
5330 case CEE_CONV_OVF_I2_UN:
5331 case CEE_CONV_OVF_I4_UN:
5332 case CEE_CONV_OVF_U1_UN:
5333 case CEE_CONV_OVF_U2_UN:
5334 case CEE_CONV_OVF_U4_UN:
5335 do_conversion (&ctx, TYPE_I4);
5339 case CEE_CONV_OVF_I8_UN:
5340 case CEE_CONV_OVF_U8_UN:
5341 do_conversion (&ctx, TYPE_I8);
5345 case CEE_CONV_OVF_I_UN:
5346 case CEE_CONV_OVF_U_UN:
5347 do_conversion (&ctx, TYPE_NATIVE_INT);
5352 code_bounds_check (5);
5353 do_box_value (&ctx, read32 (ip + 1));
5358 code_bounds_check (5);
5359 do_newarr (&ctx, read32 (ip + 1));
5369 code_bounds_check (5);
5370 do_ldelema (&ctx, read32 (ip + 1));
5384 case CEE_LDELEM_REF:
5385 do_ldelem (&ctx, *ip, 0);
5396 case CEE_STELEM_REF:
5397 do_stelem (&ctx, *ip, 0);
5402 code_bounds_check (5);
5403 do_ldelem (&ctx, *ip, read32 (ip + 1));
5408 code_bounds_check (5);
5409 do_stelem (&ctx, *ip, read32 (ip + 1));
5414 code_bounds_check (5);
5415 do_unbox_any (&ctx, read32 (ip + 1));
5419 case CEE_CONV_OVF_I1:
5420 case CEE_CONV_OVF_U1:
5421 case CEE_CONV_OVF_I2:
5422 case CEE_CONV_OVF_U2:
5423 case CEE_CONV_OVF_I4:
5424 case CEE_CONV_OVF_U4:
5425 do_conversion (&ctx, TYPE_I4);
5429 case CEE_CONV_OVF_I8:
5430 case CEE_CONV_OVF_U8:
5431 do_conversion (&ctx, TYPE_I8);
5435 case CEE_CONV_OVF_I:
5436 case CEE_CONV_OVF_U:
5437 do_conversion (&ctx, TYPE_NATIVE_INT);
5442 code_bounds_check (5);
5443 do_refanyval (&ctx, read32 (ip + 1));
5453 code_bounds_check (5);
5454 do_mkrefany (&ctx, read32 (ip + 1));
5459 code_bounds_check (5);
5460 do_load_token (&ctx, read32 (ip + 1));
5464 case CEE_ENDFINALLY:
5465 if (!is_correct_endfinally (ctx.header, ip_offset))
5466 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("endfinally must be used inside a finally/fault handler at 0x%04x", ctx.ip_offset));
5473 code_bounds_check (5);
5474 do_leave (&ctx, read32 (ip + 1) + 5);
5481 code_bounds_check (2);
5482 do_leave (&ctx, (signed char)ip [1] + 2);
5489 code_bounds_check (2);
5493 code_bounds_check (3);
5494 store_local (&ctx, read16 (ip + 1));
5499 do_cmp_op (&ctx, cmp_br_eq_op, *ip);
5507 do_cmp_op (&ctx, cmp_br_op, *ip);
5512 code_bounds_check (3);
5513 store_arg (&ctx, read16 (ip + 1) );
5519 if (!check_overflow (&ctx))
5521 if (ctx.signature->call_convention != MONO_CALL_VARARG)
5522 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Cannot use arglist on method without VARGARG calling convention at 0x%04x", ctx.ip_offset));
5523 set_stack_value (&ctx, stack_push (&ctx), &mono_defaults.argumenthandle_class->byval_arg, FALSE);
5528 code_bounds_check (5);
5529 do_load_function_ptr (&ctx, read32 (ip + 1), FALSE);
5534 code_bounds_check (5);
5535 do_load_function_ptr (&ctx, read32 (ip + 1), TRUE);
5541 code_bounds_check (3);
5542 push_arg (&ctx, read16 (ip + 1), *ip == CEE_LDARGA);
5548 code_bounds_check (3);
5549 push_local (&ctx, read16 (ip + 1), *ip == CEE_LDLOCA);
5562 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Use of the `unused' opcode"));
5566 do_endfilter (&ctx);
5570 case CEE_UNALIGNED_:
5571 code_bounds_check (2);
5572 prefix |= PREFIX_UNALIGNED;
5576 prefix |= PREFIX_VOLATILE;
5580 prefix |= PREFIX_TAIL;
5582 if (ip < end && (*ip != CEE_CALL && *ip != CEE_CALLI && *ip != CEE_CALLVIRT))
5583 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("tail prefix must be used only with call opcodes at 0x%04x", ip_offset));
5587 code_bounds_check (5);
5588 do_initobj (&ctx, read32 (ip + 1));
5592 case CEE_CONSTRAINED_:
5593 code_bounds_check (5);
5594 ctx.constrained_type = get_boxable_mono_type (&ctx, read32 (ip + 1), "constrained.");
5595 prefix |= PREFIX_CONSTRAINED;
5600 prefix |= PREFIX_READONLY;
5605 CLEAR_PREFIX (&ctx, PREFIX_UNALIGNED | PREFIX_VOLATILE);
5606 if (!check_underflow (&ctx, 3))
5608 CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Instruction cpblk is not verifiable at 0x%04x", ctx.ip_offset));
5613 CLEAR_PREFIX (&ctx, PREFIX_UNALIGNED | PREFIX_VOLATILE);
5614 if (!check_underflow (&ctx, 3))
5616 CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Instruction initblk is not verifiable at 0x%04x", ctx.ip_offset));
5624 if (!is_correct_rethrow (ctx.header, ip_offset))
5625 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("rethrow must be used inside a catch handler at 0x%04x", ctx.ip_offset));
5632 code_bounds_check (5);
5633 do_sizeof (&ctx, read32 (ip + 1));
5637 case CEE_REFANYTYPE:
5638 do_refanytype (&ctx);
5643 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid instruction FE %x at 0x%04x", *ip, ctx.ip_offset));
5649 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid instruction %x at 0x%04x", *ip, ctx.ip_offset));
5653 /*TODO we can fast detect a forward branch or exception block targeting code after prefix, we should fail fast*/
5655 if (!ctx.prefix_set) //first prefix
5656 ctx.code [ctx.ip_offset].flags |= IL_CODE_FLAG_SEEN;
5657 ctx.prefix_set |= prefix;
5658 ctx.has_flags = TRUE;
5662 ctx.code [ctx.ip_offset].flags |= IL_CODE_FLAG_SEEN;
5664 if (ctx.prefix_set & PREFIX_CONSTRAINED)
5665 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid instruction after constrained prefix at 0x%04x", ctx.ip_offset));
5666 if (ctx.prefix_set & PREFIX_READONLY)
5667 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid instruction after readonly prefix at 0x%04x", ctx.ip_offset));
5668 if (ctx.prefix_set & PREFIX_VOLATILE)
5669 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid instruction after volatile prefix at 0x%04x", ctx.ip_offset));
5670 if (ctx.prefix_set & PREFIX_UNALIGNED)
5671 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid instruction after unaligned prefix at 0x%04x", ctx.ip_offset));
5672 ctx.prefix_set = prefix = 0;
5673 ctx.has_flags = FALSE;
5677 * if ip != end we overflowed: mark as error.
5679 if ((ip != end || !start) && ctx.verifiable && !ctx.list) {
5680 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Run ahead of method code at 0x%04x", ip_offset));
5683 /*We should guard against the last decoded opcode, otherwise we might add errors that doesn't make sense.*/
5684 for (i = 0; i < ctx.code_size && i < ip_offset; ++i) {
5685 if (ctx.code [i].flags & IL_CODE_FLAG_WAS_TARGET) {
5686 if (!(ctx.code [i].flags & IL_CODE_FLAG_SEEN))
5687 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Branch or exception block target middle of intruction at 0x%04x", i));
5689 if (ctx.code [i].flags & IL_CODE_DELEGATE_SEQUENCE)
5690 CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Branch to delegate code sequence at 0x%04x", i));
5692 if ((ctx.code [i].flags & IL_CODE_LDFTN_DELEGATE_NONFINAL_VIRTUAL) && ctx.has_this_store)
5693 CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Invalid ldftn with virtual function in method with stdarg 0 at 0x%04x", i));
5695 if ((ctx.code [i].flags & IL_CODE_CALL_NONFINAL_VIRTUAL) && ctx.has_this_store)
5696 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));
5699 if (mono_method_is_constructor (ctx.method) && !ctx.super_ctor_called && !ctx.method->klass->valuetype && ctx.method->klass != mono_defaults.object_class) {
5700 char *method_name = mono_method_full_name (ctx.method, TRUE);
5701 char *type = mono_type_get_full_name (ctx.method->klass);
5702 if (ctx.method->klass->parent && ctx.method->klass->parent->exception_type != MONO_EXCEPTION_NONE)
5703 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));
5705 CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Constructor %s for type %s not calling base type ctor.", method_name, type));
5706 g_free (method_name);
5712 for (i = 0; i < ctx.header->code_size; ++i) {
5713 if (ctx.code [i].stack)
5714 g_free (ctx.code [i].stack);
5718 for (tmp = ctx.funptrs; tmp; tmp = tmp->next)
5720 g_slist_free (ctx.funptrs);
5722 for (tmp = ctx.exception_types; tmp; tmp = tmp->next)
5723 mono_metadata_free_type (tmp->data);
5724 g_slist_free (ctx.exception_types);
5726 for (i = 0; i < ctx.num_locals; ++i) {
5728 mono_metadata_free_type (ctx.locals [i]);
5730 for (i = 0; i < ctx.max_args; ++i) {
5732 mono_metadata_free_type (ctx.params [i]);
5736 g_free (ctx.eval.stack);
5739 g_free (ctx.locals);
5740 g_free (ctx.params);
5741 mono_basic_block_free (original_bb);
5742 mono_metadata_free_mh (ctx.header);
5744 finish_collect_stats ();
5749 mono_verify_corlib ()
5751 /* This is a public API function so cannot be removed */
5756 * Returns true if @method needs to be verified.
5760 mono_verifier_is_enabled_for_method (MonoMethod *method)
5762 return mono_verifier_is_enabled_for_class (method->klass) && (method->wrapper_type == MONO_WRAPPER_NONE || method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD);
5766 * Returns true if @klass need to be verified.
5770 mono_verifier_is_enabled_for_class (MonoClass *klass)
5772 return verify_all || (verifier_mode > MONO_VERIFIER_MODE_OFF && !(klass->image->assembly && klass->image->assembly->in_gac) && klass->image != mono_defaults.corlib);
5776 mono_verifier_is_enabled_for_image (MonoImage *image)
5778 return verify_all || verifier_mode > MONO_VERIFIER_MODE_OFF;
5782 * Dynamic methods are not considered full trust since if the user is trusted and need to
5783 * generate unsafe code, make the method skip verification - this is a known good way to do it.
5786 mono_verifier_is_method_full_trust (MonoMethod *method)
5788 return mono_verifier_is_class_full_trust (method->klass) && !method->dynamic;
5792 * Returns if @klass is under full trust or not.
5794 * TODO This code doesn't take CAS into account.
5796 * Under verify_all all user code must be verifiable if no security option was set
5800 mono_verifier_is_class_full_trust (MonoClass *klass)
5802 /* under CoreCLR code is trusted if it is part of the "platform" otherwise all code inside the GAC is trusted */
5803 gboolean trusted_location = (mono_security_get_mode () != MONO_SECURITY_MODE_CORE_CLR) ?
5804 (klass->image->assembly && klass->image->assembly->in_gac) : mono_security_core_clr_is_platform_image (klass->image);
5806 if (verify_all && verifier_mode == MONO_VERIFIER_MODE_OFF)
5807 return trusted_location || klass->image == mono_defaults.corlib;
5808 return verifier_mode < MONO_VERIFIER_MODE_VERIFIABLE || trusted_location || klass->image == mono_defaults.corlib;
5812 mono_method_verify_with_current_settings (MonoMethod *method, gboolean skip_visibility)
5814 return mono_method_verify (method,
5815 (verifier_mode != MONO_VERIFIER_MODE_STRICT ? MONO_VERIFY_NON_STRICT: 0)
5816 | (!mono_verifier_is_method_full_trust (method) ? MONO_VERIFY_FAIL_FAST : 0)
5817 | (skip_visibility ? MONO_VERIFY_SKIP_VISIBILITY : 0));
5821 get_field_end (MonoClassField *field)
5824 int size = mono_type_size (field->type, &align);
5826 size = 4; /*FIXME Is this a safe bet?*/
5827 return size + field->offset;
5831 verify_class_for_overlapping_reference_fields (MonoClass *class)
5834 gpointer iter = NULL;
5835 MonoClassField *field;
5836 gboolean is_fulltrust = mono_verifier_is_class_full_trust (class);
5837 /*We can't skip types with !has_references since this is calculated after we have run.*/
5838 if (!((class->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_EXPLICIT_LAYOUT))
5842 /*We must check for stuff overlapping reference fields.
5843 The outer loop uses mono_class_get_fields to ensure that MonoClass:fields get inited.
5845 while ((field = mono_class_get_fields (class, &iter))) {
5846 int fieldEnd = get_field_end (field);
5847 gboolean is_valuetype = !MONO_TYPE_IS_REFERENCE (field->type);
5850 if (mono_field_is_deleted (field) || (field->type->attrs & FIELD_ATTRIBUTE_STATIC))
5853 for (j = i; j < class->field.count; ++j) {
5854 MonoClassField *other = &class->fields [j];
5855 int otherEnd = get_field_end (other);
5856 if (mono_field_is_deleted (other) || (is_valuetype && !MONO_TYPE_IS_REFERENCE (other->type)) || (other->type->attrs & FIELD_ATTRIBUTE_STATIC))
5859 if (!is_valuetype && MONO_TYPE_IS_REFERENCE (other->type) && field->offset == other->offset && is_fulltrust)
5862 if ((otherEnd > field->offset && otherEnd <= fieldEnd) || (other->offset >= field->offset && other->offset < fieldEnd))
5870 field_hash (gconstpointer key)
5872 const MonoClassField *field = key;
5873 return g_str_hash (field->name) ^ mono_metadata_type_hash (field->type); /**/
5877 field_equals (gconstpointer _a, gconstpointer _b)
5879 const MonoClassField *a = _a;
5880 const MonoClassField *b = _b;
5881 return !strcmp (a->name, b->name) && mono_metadata_type_equal (a->type, b->type);
5886 verify_class_fields (MonoClass *class)
5888 gpointer iter = NULL;
5889 MonoClassField *field;
5890 MonoGenericContext *context = mono_class_get_context (class);
5891 GHashTable *unique_fields = g_hash_table_new_full (&field_hash, &field_equals, NULL, NULL);
5892 if (class->generic_container)
5893 context = &class->generic_container->context;
5895 while ((field = mono_class_get_fields (class, &iter)) != NULL) {
5896 if (!mono_type_is_valid_type_in_context (field->type, context)) {
5897 g_hash_table_destroy (unique_fields);
5900 if (g_hash_table_lookup (unique_fields, field)) {
5901 g_hash_table_destroy (unique_fields);
5904 g_hash_table_insert (unique_fields, field, field);
5906 g_hash_table_destroy (unique_fields);
5911 verify_interfaces (MonoClass *class)
5914 for (i = 0; i < class->interface_count; ++i) {
5915 MonoClass *iface = class->interfaces [i];
5916 if (!(iface->flags & TYPE_ATTRIBUTE_INTERFACE))
5923 verify_valuetype_layout_with_target (MonoClass *class, MonoClass *target_class)
5926 gpointer iter = NULL;
5927 MonoClassField *field;
5928 MonoClass *field_class;
5930 if (!class->valuetype)
5933 type = class->byval_arg.type;
5934 /*primitive type fields are not properly decoded*/
5935 if ((type >= MONO_TYPE_BOOLEAN && type <= MONO_TYPE_R8) || (type >= MONO_TYPE_I && type <= MONO_TYPE_U))
5938 while ((field = mono_class_get_fields (class, &iter)) != NULL) {
5942 if (field->type->attrs & (FIELD_ATTRIBUTE_STATIC | FIELD_ATTRIBUTE_HAS_FIELD_RVA))
5945 field_class = mono_class_get_generic_type_definition (mono_class_from_mono_type (field->type));
5947 if (field_class == target_class || class == field_class || !verify_valuetype_layout_with_target (field_class, target_class))
5955 verify_valuetype_layout (MonoClass *class)
5958 res = verify_valuetype_layout_with_target (class, class);
5963 recursive_mark_constraint_args (MonoBitSet *used_args, MonoGenericContainer *gc, MonoType *type)
5966 MonoClass **constraints;
5967 MonoGenericParamInfo *param_info;
5969 g_assert (mono_type_is_generic_argument (type));
5971 idx = mono_type_get_generic_param_num (type);
5972 if (mono_bitset_test_fast (used_args, idx))
5975 mono_bitset_set_fast (used_args, idx);
5976 param_info = mono_generic_container_get_param_info (gc, idx);
5978 if (!param_info->constraints)
5981 for (constraints = param_info->constraints; *constraints; ++constraints) {
5982 MonoClass *ctr = *constraints;
5983 MonoType *constraint_type = &ctr->byval_arg;
5985 if (mono_type_is_generic_argument (constraint_type) && !recursive_mark_constraint_args (used_args, gc, constraint_type))
5992 verify_generic_parameters (MonoClass *class)
5995 MonoGenericContainer *gc = class->generic_container;
5996 MonoBitSet *used_args = mono_bitset_new (gc->type_argc, 0);
5998 for (i = 0; i < gc->type_argc; ++i) {
5999 MonoGenericParamInfo *param_info = mono_generic_container_get_param_info (gc, i);
6000 MonoClass **constraints;
6002 if (!param_info->constraints)
6005 mono_bitset_clear_all (used_args);
6006 mono_bitset_set_fast (used_args, i);
6008 for (constraints = param_info->constraints; *constraints; ++constraints) {
6009 MonoClass *ctr = *constraints;
6010 MonoType *constraint_type = &ctr->byval_arg;
6012 if (!mono_type_is_valid_type_in_context (constraint_type, &gc->context))
6015 if (mono_type_is_generic_argument (constraint_type) && !recursive_mark_constraint_args (used_args, gc, constraint_type))
6017 if (ctr->generic_class && !mono_class_is_valid_generic_instantiation (NULL, ctr))
6021 mono_bitset_free (used_args);
6025 mono_bitset_free (used_args);
6030 * Check if the class is verifiable.
6032 * Right now there are no conditions that make a class a valid but not verifiable. Both overlapping reference
6033 * field and invalid generic instantiation are fatal errors.
6035 * This method must be safe to be called from mono_class_init and all code must be carefull about that.
6039 mono_verifier_verify_class (MonoClass *class)
6041 /*Neither <Module>, object or ifaces have parent.*/
6042 if (!class->parent &&
6043 class != mono_defaults.object_class &&
6044 !MONO_CLASS_IS_INTERFACE (class) &&
6045 (!class->image->dynamic && class->type_token != 0x2000001)) /*<Module> is the first type in the assembly*/
6047 if (class->parent) {
6048 if (MONO_CLASS_IS_INTERFACE (class->parent))
6050 if (!class->generic_class && class->parent->generic_container)
6053 if (class->generic_container && (class->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_EXPLICIT_LAYOUT)
6055 if (class->generic_container && !verify_generic_parameters (class))
6057 if (!verify_class_for_overlapping_reference_fields (class))
6059 if (class->generic_class && !mono_class_is_valid_generic_instantiation (NULL, class))
6061 if (class->generic_class == NULL && !verify_class_fields (class))
6063 if (class->valuetype && !verify_valuetype_layout (class))
6065 if (!verify_interfaces (class))
6071 mono_verifier_class_is_valid_generic_instantiation (MonoClass *class)
6073 return mono_class_is_valid_generic_instantiation (NULL, class);
6077 mono_verifier_is_method_valid_generic_instantiation (MonoMethod *method)
6079 if (!method->is_inflated)
6081 return mono_method_is_valid_generic_instantiation (NULL, method);
6087 mono_verifier_verify_class (MonoClass *class)
6089 /* The verifier was disabled at compile time */
6094 mono_method_verify_with_current_settings (MonoMethod *method, gboolean skip_visibility)
6096 /* The verifier was disabled at compile time */
6101 mono_verifier_is_class_full_trust (MonoClass *klass)
6103 /* The verifier was disabled at compile time */
6108 mono_verifier_is_method_full_trust (MonoMethod *method)
6110 /* The verifier was disabled at compile time */
6115 mono_verifier_is_enabled_for_image (MonoImage *image)
6117 /* The verifier was disabled at compile time */
6122 mono_verifier_is_enabled_for_class (MonoClass *klass)
6124 /* The verifier was disabled at compile time */
6129 mono_verifier_is_enabled_for_method (MonoMethod *method)
6131 /* The verifier was disabled at compile time */
6136 mono_method_verify (MonoMethod *method, int level)
6138 /* The verifier was disabled at compile time */
6143 mono_free_verify_list (GSList *list)
6145 /* The verifier was disabled at compile time */
6146 /* will always be null if verifier is disabled */
6150 mono_verifier_class_is_valid_generic_instantiation (MonoClass *class)
6156 mono_verifier_is_method_valid_generic_instantiation (MonoMethod *method)