2009-05-15 Geoff Norton <gnorton@novell.com>
[mono-project.git] / mono / metadata / verify.c
blobdd71ec610f07f1e3bd142449a4198ad3766d2ecb
1 /*
2 * verify.c:
4 * Author:
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)
9 */
10 #include <config.h>
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 <string.h>
27 #include <signal.h>
28 #include <ctype.h>
31 static MiniVerifierMode verifier_mode = MONO_VERIFIER_MODE_OFF;
32 static gboolean verify_all = FALSE;
35 * Set the desired level of checks for the verfier.
38 void
39 mono_verifier_set_mode (MiniVerifierMode mode)
41 verifier_mode = mode;
44 void
45 mono_verifier_enable_verify_all ()
47 verify_all = TRUE;
50 #ifndef DISABLE_VERIFIER
52 * Pull the list of opcodes
54 #define OPDEF(a,b,c,d,e,f,g,h,i,j) \
55 a = i,
57 enum {
58 #include "mono/cil/opcode.def"
59 LAST = 0xff
61 #undef OPDEF
63 #ifdef MONO_VERIFIER_DEBUG
64 #define VERIFIER_DEBUG(code) do { code } while (0)
65 #else
66 #define VERIFIER_DEBUG(code)
67 #endif
69 //////////////////////////////////////////////////////////////////
70 #define IS_STRICT_MODE(ctx) (((ctx)->level & MONO_VERIFY_NON_STRICT) == 0)
71 #define IS_FAIL_FAST_MODE(ctx) (((ctx)->level & MONO_VERIFY_FAIL_FAST) == MONO_VERIFY_FAIL_FAST)
72 #define IS_SKIP_VISIBILITY(ctx) (((ctx)->level & MONO_VERIFY_SKIP_VISIBILITY) == MONO_VERIFY_SKIP_VISIBILITY)
73 #define IS_REPORT_ALL_ERRORS(ctx) (((ctx)->level & MONO_VERIFY_REPORT_ALL_ERRORS) == MONO_VERIFY_REPORT_ALL_ERRORS)
74 #define CLEAR_PREFIX(ctx, prefix) do { (ctx)->prefix_set &= ~(prefix); } while (0)
75 #define ADD_VERIFY_INFO(__ctx, __msg, __status, __exception) \
76 do { \
77 MonoVerifyInfoExtended *vinfo = g_new (MonoVerifyInfoExtended, 1); \
78 vinfo->info.status = __status; \
79 vinfo->info.message = ( __msg ); \
80 vinfo->exception_type = (__exception); \
81 (__ctx)->list = g_slist_prepend ((__ctx)->list, vinfo); \
82 } while (0)
84 //TODO support MONO_VERIFY_REPORT_ALL_ERRORS
85 #define ADD_VERIFY_ERROR(__ctx, __msg) \
86 do { \
87 ADD_VERIFY_INFO(__ctx, __msg, MONO_VERIFY_ERROR, MONO_EXCEPTION_INVALID_PROGRAM); \
88 (__ctx)->valid = 0; \
89 } while (0)
91 #define CODE_NOT_VERIFIABLE(__ctx, __msg) \
92 do { \
93 if ((__ctx)->verifiable || IS_REPORT_ALL_ERRORS (__ctx)) { \
94 ADD_VERIFY_INFO(__ctx, __msg, MONO_VERIFY_NOT_VERIFIABLE, MONO_EXCEPTION_UNVERIFIABLE_IL); \
95 (__ctx)->verifiable = 0; \
96 if (IS_FAIL_FAST_MODE (__ctx)) \
97 (__ctx)->valid = 0; \
98 } \
99 } while (0)
101 #define ADD_VERIFY_ERROR2(__ctx, __msg, __exception) \
102 do { \
103 ADD_VERIFY_INFO(__ctx, __msg, MONO_VERIFY_ERROR, __exception); \
104 (__ctx)->valid = 0; \
105 } while (0)
107 #define CODE_NOT_VERIFIABLE2(__ctx, __msg, __exception) \
108 do { \
109 if ((__ctx)->verifiable || IS_REPORT_ALL_ERRORS (__ctx)) { \
110 ADD_VERIFY_INFO(__ctx, __msg, MONO_VERIFY_NOT_VERIFIABLE, __exception); \
111 (__ctx)->verifiable = 0; \
112 if (IS_FAIL_FAST_MODE (__ctx)) \
113 (__ctx)->valid = 0; \
115 } while (0)
116 /*Flags to be used with ILCodeDesc::flags */
117 enum {
118 /*Instruction has not been processed.*/
119 IL_CODE_FLAG_NOT_PROCESSED = 0,
120 /*Instruction was decoded by mono_method_verify loop.*/
121 IL_CODE_FLAG_SEEN = 1,
122 /*Instruction was target of a branch or is at a protected block boundary.*/
123 IL_CODE_FLAG_WAS_TARGET = 2,
124 /*Used by stack_init to avoid double initialize each entry.*/
125 IL_CODE_FLAG_STACK_INITED = 4,
126 /*Used by merge_stacks to decide if it should just copy the eval stack.*/
127 IL_CODE_STACK_MERGED = 8,
128 /*This instruction is part of the delegate construction sequence, it cannot be target of a branch.*/
129 IL_CODE_DELEGATE_SEQUENCE = 0x10,
130 /*This is a delegate created from a ldftn to a non final virtual method*/
131 IL_CODE_LDFTN_DELEGATE_NONFINAL_VIRTUAL = 0x20,
132 /*This is a call to a non final virtual method*/
133 IL_CODE_CALL_NONFINAL_VIRTUAL = 0x40,
136 typedef enum {
137 RESULT_VALID,
138 RESULT_UNVERIFIABLE,
139 RESULT_INVALID
140 } verify_result_t;
142 typedef struct {
143 MonoType *type;
144 int stype;
145 MonoMethod *method;
146 } ILStackDesc;
149 typedef struct {
150 ILStackDesc *stack;
151 guint16 size;
152 guint16 flags;
153 } ILCodeDesc;
155 typedef struct {
156 int max_args;
157 int max_stack;
158 int verifiable;
159 int valid;
160 int level;
162 int code_size;
163 ILCodeDesc *code;
164 ILCodeDesc eval;
166 MonoType **params;
167 GSList *list;
168 /*Allocated fnptr MonoType that should be freed by us.*/
169 GSList *funptrs;
170 /*Type dup'ed exception types from catch blocks.*/
171 GSList *exception_types;
173 int num_locals;
174 MonoType **locals;
176 /*TODO get rid of target here, need_merge in mono_method_verify and hoist the merging code in the branching code*/
177 int target;
179 guint32 ip_offset;
180 MonoMethodSignature *signature;
181 MonoMethodHeader *header;
183 MonoGenericContext *generic_context;
184 MonoImage *image;
185 MonoMethod *method;
187 /*This flag helps solving a corner case of delegate verification in that you cannot have a "starg 0"
188 *on a method that creates a delegate for a non-final virtual method using ldftn*/
189 gboolean has_this_store;
191 /*This flag is used to control if the contructor of the parent class has been called.
192 *If the this pointer is pushed on the eval stack and it's a reference type constructor and
193 * super_ctor_called is false, the uninitialized flag is set on the pushed value.
195 * Poping an uninitialized this ptr from the eval stack is an unverifiable operation unless
196 * the safe variant is used. Only a few opcodes can use it : dup, pop, ldfld, stfld and call to a constructor.
198 gboolean super_ctor_called;
200 guint32 prefix_set;
201 gboolean has_flags;
202 MonoType *constrained_type;
203 } VerifyContext;
205 static void
206 merge_stacks (VerifyContext *ctx, ILCodeDesc *from, ILCodeDesc *to, gboolean start, gboolean external);
208 static int
209 get_stack_type (MonoType *type);
211 static gboolean
212 mono_delegate_signature_equal (MonoMethodSignature *delegate_sig, MonoMethodSignature *method_sig, gboolean is_static_ldftn);
214 static gboolean
215 mono_class_is_valid_generic_instantiation (VerifyContext *ctx, MonoClass *klass);
217 static gboolean
218 mono_method_is_valid_generic_instantiation (VerifyContext *ctx, MonoMethod *method);
219 //////////////////////////////////////////////////////////////////
223 enum {
224 TYPE_INV = 0, /* leave at 0. */
225 TYPE_I4 = 1,
226 TYPE_I8 = 2,
227 TYPE_NATIVE_INT = 3,
228 TYPE_R8 = 4,
229 /* Used by operator tables to resolve pointer types (managed & unmanaged) and by unmanaged pointer types*/
230 TYPE_PTR = 5,
231 /* value types and classes */
232 TYPE_COMPLEX = 6,
233 /* Number of types, used to define the size of the tables*/
234 TYPE_MAX = 6,
236 /* Used by tables to signal that a result is not verifiable*/
237 NON_VERIFIABLE_RESULT = 0x80,
239 /*Mask used to extract just the type, excluding flags */
240 TYPE_MASK = 0x0F,
242 /* The stack type is a managed pointer, unmask the value to res */
243 POINTER_MASK = 0x100,
245 /*Stack type with the pointer mask*/
246 RAW_TYPE_MASK = 0x10F,
248 /* Controlled Mutability Manager Pointer */
249 CMMP_MASK = 0x200,
251 /* The stack type is a null literal*/
252 NULL_LITERAL_MASK = 0x400,
254 /**Used by ldarg.0 and family to let delegate verification happens.*/
255 THIS_POINTER_MASK = 0x800,
257 /**Signals that this is a boxed value type*/
258 BOXED_MASK = 0x1000,
260 /*This is an unitialized this ref*/
261 UNINIT_THIS_MASK = 0x2000,
264 static const char* const
265 type_names [TYPE_MAX + 1] = {
266 "Invalid",
267 "Int32",
268 "Int64",
269 "Native Int",
270 "Float64",
271 "Native Pointer",
272 "Complex"
275 enum {
276 PREFIX_UNALIGNED = 1,
277 PREFIX_VOLATILE = 2,
278 PREFIX_TAIL = 4,
279 PREFIX_CONSTRAINED = 8,
280 PREFIX_READONLY = 16
282 //////////////////////////////////////////////////////////////////
285 /*Token validation macros and functions */
286 #define IS_MEMBER_REF(token) (mono_metadata_token_table (token) == MONO_TABLE_MEMBERREF)
287 #define IS_METHOD_DEF(token) (mono_metadata_token_table (token) == MONO_TABLE_METHOD)
288 #define IS_METHOD_SPEC(token) (mono_metadata_token_table (token) == MONO_TABLE_METHODSPEC)
289 #define IS_FIELD_DEF(token) (mono_metadata_token_table (token) == MONO_TABLE_FIELD)
291 #define IS_TYPE_REF(token) (mono_metadata_token_table (token) == MONO_TABLE_TYPEREF)
292 #define IS_TYPE_DEF(token) (mono_metadata_token_table (token) == MONO_TABLE_TYPEDEF)
293 #define IS_TYPE_SPEC(token) (mono_metadata_token_table (token) == MONO_TABLE_TYPESPEC)
294 #define IS_METHOD_DEF_OR_REF_OR_SPEC(token) (IS_METHOD_DEF (token) || IS_MEMBER_REF (token) || IS_METHOD_SPEC (token))
295 #define IS_TYPE_DEF_OR_REF_OR_SPEC(token) (IS_TYPE_DEF (token) || IS_TYPE_REF (token) || IS_TYPE_SPEC (token))
296 #define IS_FIELD_DEF_OR_REF(token) (IS_FIELD_DEF (token) || IS_MEMBER_REF (token))
299 * Verify if @token refers to a valid row on int's table.
301 static gboolean
302 token_bounds_check (MonoImage *image, guint32 token)
304 if (image->dynamic)
305 return mono_reflection_is_valid_dynamic_token ((MonoDynamicImage*)image, token);
306 return image->tables [mono_metadata_token_table (token)].rows >= mono_metadata_token_index (token);
309 static MonoType *
310 mono_type_create_fnptr_from_mono_method (VerifyContext *ctx, MonoMethod *method)
312 MonoType *res = g_new0 (MonoType, 1);
313 //FIXME use mono_method_get_signature_full
314 res->data.method = mono_method_signature (method);
315 res->type = MONO_TYPE_FNPTR;
316 ctx->funptrs = g_slist_prepend (ctx->funptrs, res);
317 return res;
321 * mono_type_is_enum_type:
323 * Returns TRUE if @type is an enum type.
325 static gboolean
326 mono_type_is_enum_type (MonoType *type)
328 if (type->type == MONO_TYPE_VALUETYPE && type->data.klass->enumtype)
329 return TRUE;
330 if (type->type == MONO_TYPE_GENERICINST && type->data.generic_class->container_class->enumtype)
331 return TRUE;
332 return FALSE;
336 * mono_type_is_value_type:
338 * Returns TRUE if @type is named after @namespace.@name.
341 static gboolean
342 mono_type_is_value_type (MonoType *type, const char *namespace, const char *name)
344 return type->type == MONO_TYPE_VALUETYPE &&
345 !strcmp (namespace, type->data.klass->name_space) &&
346 !strcmp (name, type->data.klass->name);
350 * Returns TURE if @type is VAR or MVAR
352 static gboolean
353 mono_type_is_generic_argument (MonoType *type)
355 return type->type == MONO_TYPE_VAR || type->type == MONO_TYPE_MVAR;
359 * mono_type_get_underlying_type_any:
361 * This functions is just like mono_type_get_underlying_type but it doesn't care if the type is byref.
363 * Returns the underlying type of @type regardless if it is byref or not.
365 static MonoType*
366 mono_type_get_underlying_type_any (MonoType *type)
368 if (type->type == MONO_TYPE_VALUETYPE && type->data.klass->enumtype)
369 return mono_class_enum_basetype (type->data.klass);
370 if (type->type == MONO_TYPE_GENERICINST && type->data.generic_class->container_class->enumtype)
371 return mono_class_enum_basetype (type->data.generic_class->container_class);
372 return type;
375 static const char*
376 mono_type_get_stack_name (MonoType *type)
378 return type_names [get_stack_type (type) & TYPE_MASK];
381 #define CTOR_REQUIRED_FLAGS (METHOD_ATTRIBUTE_SPECIAL_NAME | METHOD_ATTRIBUTE_RT_SPECIAL_NAME)
382 #define CTOR_INVALID_FLAGS (METHOD_ATTRIBUTE_STATIC)
384 static gboolean
385 mono_method_is_constructor (MonoMethod *method)
387 return ((method->flags & CTOR_REQUIRED_FLAGS) == CTOR_REQUIRED_FLAGS &&
388 !(method->flags & CTOR_INVALID_FLAGS) &&
389 !strcmp (".ctor", method->name));
392 static gboolean
393 mono_class_has_default_constructor (MonoClass *klass)
395 MonoMethod *method;
396 int i;
398 mono_class_setup_methods (klass);
400 for (i = 0; i < klass->method.count; ++i) {
401 method = klass->methods [i];
402 if (mono_method_is_constructor (method) &&
403 mono_method_signature (method)->param_count == 0 &&
404 (method->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK) == METHOD_ATTRIBUTE_PUBLIC)
405 return TRUE;
407 return FALSE;
410 static gboolean
411 mono_class_interface_implements_interface (MonoClass *candidate, MonoClass *iface)
413 int i;
414 do {
415 if (candidate == iface)
416 return TRUE;
417 mono_class_setup_interfaces (candidate);
418 for (i = 0; i < candidate->interface_count; ++i) {
419 if (candidate->interfaces [i] == iface || mono_class_interface_implements_interface (candidate->interfaces [i], iface))
420 return TRUE;
422 candidate = candidate->parent;
423 } while (candidate);
424 return FALSE;
428 * Verify if @type is valid for the given @ctx verification context.
429 * this function checks for VAR and MVAR types that are invalid under the current verifier,
431 static gboolean
432 mono_type_is_valid_type_in_context (MonoType *type, MonoGenericContext *context)
434 int i;
435 MonoGenericInst *inst;
437 switch (type->type) {
438 case MONO_TYPE_VAR:
439 case MONO_TYPE_MVAR:
440 if (!context)
441 return FALSE;
442 inst = type->type == MONO_TYPE_VAR ? context->class_inst : context->method_inst;
443 if (!inst || mono_type_get_generic_param_num (type) >= inst->type_argc)
444 return FALSE;
445 break;
446 case MONO_TYPE_SZARRAY:
447 return mono_type_is_valid_type_in_context (&type->data.klass->byval_arg, context);
448 case MONO_TYPE_ARRAY:
449 return mono_type_is_valid_type_in_context (&type->data.array->eklass->byval_arg, context);
450 case MONO_TYPE_PTR:
451 return mono_type_is_valid_type_in_context (type->data.type, context);
452 case MONO_TYPE_GENERICINST:
453 inst = type->data.generic_class->context.class_inst;
454 if (!inst->is_open)
455 break;
456 for (i = 0; i < inst->type_argc; ++i)
457 if (!mono_type_is_valid_type_in_context (inst->type_argv [i], context))
458 return FALSE;
459 break;
461 return TRUE;
464 /*This function returns NULL if the type is not instantiatable*/
465 static MonoType*
466 verifier_inflate_type (VerifyContext *ctx, MonoType *type, MonoGenericContext *context)
468 if (!mono_type_is_valid_type_in_context (type, context))
469 return NULL;
470 return mono_class_inflate_generic_type (type, context);
473 * Test if @candidate is a subtype of @target using the minimal possible information
474 * TODO move the code for non finished TypeBuilders to here.
476 static gboolean
477 mono_class_is_constraint_compatible (MonoClass *candidate, MonoClass *target)
479 if (candidate == target)
480 return TRUE;
481 if (target == mono_defaults.object_class)
482 return TRUE;
484 //setup_supertypes don't mono_class_init anything
485 mono_class_setup_supertypes (candidate);
486 mono_class_setup_supertypes (target);
488 if (mono_class_has_parent (candidate, target))
489 return TRUE;
491 //if target is not a supertype it must be an interface
492 if (!MONO_CLASS_IS_INTERFACE (target))
493 return FALSE;
495 if (candidate->image->dynamic && !candidate->wastypebuilder) {
496 MonoReflectionTypeBuilder *tb = candidate->reflection_info;
497 int j;
498 if (tb->interfaces) {
499 for (j = mono_array_length (tb->interfaces) - 1; j >= 0; --j) {
500 MonoReflectionType *iface = mono_array_get (tb->interfaces, MonoReflectionType*, j);
501 MonoClass *ifaceClass = mono_class_from_mono_type (iface->type);
502 if (mono_class_is_constraint_compatible (ifaceClass, target)) {
503 return TRUE;
507 return FALSE;
509 return mono_class_interface_implements_interface (candidate, target);
512 static gboolean
513 is_valid_generic_instantiation (MonoGenericContainer *gc, MonoGenericContext *context, MonoGenericInst *ginst)
515 int i;
517 if (ginst->type_argc != gc->type_argc)
518 return FALSE;
520 for (i = 0; i < gc->type_argc; ++i) {
521 MonoGenericParamInfo *param_info = mono_generic_container_get_param_info (gc, i);
522 MonoClass *paramClass;
523 MonoClass **constraints;
525 if (!param_info->constraints && !(param_info->flags & GENERIC_PARAMETER_ATTRIBUTE_SPECIAL_CONSTRAINTS_MASK))
526 continue;
527 if (mono_type_is_generic_argument (ginst->type_argv [i]))
528 continue; //it's not our job to validate type variables
530 paramClass = mono_class_from_mono_type (ginst->type_argv [i]);
532 if (paramClass->exception_type != MONO_EXCEPTION_NONE)
533 return FALSE;
535 /*it's not safe to call mono_class_init from here*/
536 if (paramClass->generic_class && !paramClass->inited) {
537 if (!mono_class_is_valid_generic_instantiation (NULL, paramClass))
538 return FALSE;
541 if ((param_info->flags & GENERIC_PARAMETER_ATTRIBUTE_VALUE_TYPE_CONSTRAINT) && (!paramClass->valuetype || mono_class_is_nullable (paramClass)))
542 return FALSE;
544 if ((param_info->flags & GENERIC_PARAMETER_ATTRIBUTE_REFERENCE_TYPE_CONSTRAINT) && paramClass->valuetype)
545 return FALSE;
547 if ((param_info->flags & GENERIC_PARAMETER_ATTRIBUTE_CONSTRUCTOR_CONSTRAINT) && !paramClass->valuetype && !mono_class_has_default_constructor (paramClass))
548 return FALSE;
550 if (!param_info->constraints)
551 continue;
553 for (constraints = param_info->constraints; *constraints; ++constraints) {
554 MonoClass *ctr = *constraints;
555 MonoType *inflated;
557 inflated = mono_class_inflate_generic_type (&ctr->byval_arg, context);
558 ctr = mono_class_from_mono_type (inflated);
559 mono_metadata_free_type (inflated);
561 if (!mono_class_is_constraint_compatible (paramClass, ctr))
562 return FALSE;
565 return TRUE;
569 * Return true if @candidate is constraint compatible with @target.
571 * This means that @candidate constraints are a super set of @target constaints
573 static gboolean
574 mono_generic_param_is_constraint_compatible (VerifyContext *ctx, MonoGenericParam *target, MonoGenericParam *candidate, MonoGenericContext *context)
576 MonoGenericParamInfo *tinfo = mono_generic_param_info (target);
577 MonoGenericParamInfo *cinfo = mono_generic_param_info (candidate);
579 int tmask = tinfo->flags & GENERIC_PARAMETER_ATTRIBUTE_SPECIAL_CONSTRAINTS_MASK;
580 int cmask = cinfo->flags & GENERIC_PARAMETER_ATTRIBUTE_SPECIAL_CONSTRAINTS_MASK;
581 if ((tmask & cmask) != tmask)
582 return FALSE;
584 if (tinfo->constraints) {
585 MonoClass **target_class, **candidate_class;
586 if (!cinfo->constraints)
587 return FALSE;
588 for (target_class = tinfo->constraints; *target_class; ++target_class) {
589 MonoClass *tc;
590 MonoType *inflated = verifier_inflate_type (ctx, &(*target_class)->byval_arg, context);
591 if (!inflated)
592 return FALSE;
593 tc = mono_class_from_mono_type (inflated);
594 mono_metadata_free_type (inflated);
596 for (candidate_class = cinfo->constraints; *candidate_class; ++candidate_class) {
597 MonoClass *cc;
598 inflated = verifier_inflate_type (ctx, &(*candidate_class)->byval_arg, ctx->generic_context);
599 if (!inflated)
600 return FALSE;
601 cc = mono_class_from_mono_type (inflated);
602 mono_metadata_free_type (inflated);
604 if (mono_class_is_assignable_from (tc, cc))
605 break;
607 if (!*candidate_class)
608 return FALSE;
611 return TRUE;
614 static MonoGenericParam*
615 verifier_get_generic_param_from_type (VerifyContext *ctx, MonoType *type)
617 MonoGenericContainer *gc;
618 MonoMethod *method = ctx->method;
619 int num;
621 num = mono_type_get_generic_param_num (type);
623 if (type->type == MONO_TYPE_VAR) {
624 MonoClass *gtd = method->klass;
625 if (gtd->generic_class)
626 gtd = gtd->generic_class->container_class;
627 gc = gtd->generic_container;
628 } else { //MVAR
629 MonoMethod *gmd = method;
630 if (method->is_inflated)
631 gmd = ((MonoMethodInflated*)method)->declaring;
632 gc = mono_method_get_generic_container (gmd);
634 if (!gc)
635 return FALSE;
636 return mono_generic_container_get_param (gc, num);
642 * Verify if @type is valid for the given @ctx verification context.
643 * this function checks for VAR and MVAR types that are invalid under the current verifier,
644 * This means that it either
646 static gboolean
647 is_valid_type_in_context (VerifyContext *ctx, MonoType *type)
649 return mono_type_is_valid_type_in_context (type, ctx->generic_context);
652 static gboolean
653 is_valid_generic_instantiation_in_context (VerifyContext *ctx, MonoGenericInst *ginst)
655 int i;
656 for (i = 0; i < ginst->type_argc; ++i) {
657 MonoType *type = ginst->type_argv [i];
658 if (!is_valid_type_in_context (ctx, type))
659 return FALSE;
661 return TRUE;
664 static gboolean
665 generic_arguments_respect_constraints (VerifyContext *ctx, MonoGenericContainer *gc, MonoGenericContext *context, MonoGenericInst *ginst)
667 int i;
668 for (i = 0; i < ginst->type_argc; ++i) {
669 MonoType *type = ginst->type_argv [i];
670 MonoGenericParam *target = mono_generic_container_get_param (gc, i);
671 MonoGenericParam *candidate;
673 if (!mono_type_is_generic_argument (type))
674 continue;
676 if (!is_valid_type_in_context (ctx, type))
677 return FALSE;
679 candidate = verifier_get_generic_param_from_type (ctx, type);
681 if (!mono_generic_param_is_constraint_compatible (ctx, target, candidate, context))
682 return FALSE;
684 return TRUE;
687 static gboolean
688 mono_method_repect_method_constraints (VerifyContext *ctx, MonoMethod *method)
690 MonoMethodInflated *gmethod = (MonoMethodInflated *)method;
691 MonoGenericInst *ginst = gmethod->context.method_inst;
692 MonoGenericContainer *gc = mono_method_get_generic_container (gmethod->declaring);
693 return !gc || generic_arguments_respect_constraints (ctx, gc, &gmethod->context, ginst);
696 static gboolean
697 mono_class_repect_method_constraints (VerifyContext *ctx, MonoClass *klass)
699 MonoGenericClass *gklass = klass->generic_class;
700 MonoGenericInst *ginst = gklass->context.class_inst;
701 MonoGenericContainer *gc = gklass->container_class->generic_container;
702 return !gc || generic_arguments_respect_constraints (ctx, gc, &gklass->context, ginst);
705 static gboolean
706 mono_method_is_valid_generic_instantiation (VerifyContext *ctx, MonoMethod *method)
708 MonoMethodInflated *gmethod = (MonoMethodInflated *)method;
709 MonoGenericInst *ginst = gmethod->context.method_inst;
710 MonoGenericContainer *gc = mono_method_get_generic_container (gmethod->declaring);
711 if (!gc) /*non-generic inflated method - it's part of a generic type */
712 return TRUE;
713 if (ctx && !is_valid_generic_instantiation_in_context (ctx, ginst))
714 return FALSE;
715 return is_valid_generic_instantiation (gc, &gmethod->context, ginst);
719 static gboolean
720 mono_class_is_valid_generic_instantiation (VerifyContext *ctx, MonoClass *klass)
722 MonoGenericClass *gklass = klass->generic_class;
723 MonoGenericInst *ginst = gklass->context.class_inst;
724 MonoGenericContainer *gc = gklass->container_class->generic_container;
725 if (ctx && !is_valid_generic_instantiation_in_context (ctx, ginst))
726 return FALSE;
727 return is_valid_generic_instantiation (gc, &gklass->context, ginst);
730 static gboolean
731 mono_type_is_valid_in_context (VerifyContext *ctx, MonoType *type)
733 MonoClass *klass;
735 if (!is_valid_type_in_context (ctx, type)) {
736 char *str = mono_type_full_name (type);
737 ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid generic type (%s%s) (argument out of range or %s is not generic) at 0x%04x",
738 type->type == MONO_TYPE_VAR ? "!" : "!!",
739 str,
740 type->type == MONO_TYPE_VAR ? "class" : "method",
741 ctx->ip_offset),
742 MONO_EXCEPTION_BAD_IMAGE);
743 g_free (str);
744 return FALSE;
747 klass = mono_class_from_mono_type (type);
748 mono_class_init (klass);
749 if (mono_loader_get_last_error () || klass->exception_type != MONO_EXCEPTION_NONE) {
750 if (klass->generic_class && !mono_class_is_valid_generic_instantiation (NULL, klass))
751 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);
752 else
753 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);
754 return FALSE;
757 if (klass->exception_type != MONO_EXCEPTION_NONE || (klass->generic_class && klass->generic_class->container_class->exception_type != MONO_EXCEPTION_NONE)) {
758 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);
759 return FALSE;
762 if (!klass->generic_class)
763 return TRUE;
765 if (!mono_class_is_valid_generic_instantiation (ctx, klass)) {
766 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);
767 return FALSE;
770 if (!mono_class_repect_method_constraints (ctx, klass)) {
771 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);
772 return FALSE;
775 return TRUE;
778 static verify_result_t
779 mono_method_is_valid_in_context (VerifyContext *ctx, MonoMethod *method)
781 if (!mono_type_is_valid_in_context (ctx, &method->klass->byval_arg))
782 return RESULT_INVALID;
784 if (!method->is_inflated)
785 return RESULT_VALID;
787 if (!mono_method_is_valid_generic_instantiation (ctx, method)) {
788 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);
789 return RESULT_INVALID;
792 if (!mono_method_repect_method_constraints (ctx, method)) {
793 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));
794 return RESULT_UNVERIFIABLE;
796 return RESULT_VALID;
800 static MonoClassField*
801 verifier_load_field (VerifyContext *ctx, int token, MonoClass **klass, const char *opcode) {
802 MonoClassField *field;
804 if (!IS_FIELD_DEF_OR_REF (token) || !token_bounds_check (ctx->image, token)) {
805 ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid field token 0x%x08x for %s at 0x%04x", token, opcode, ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE);
806 return NULL;
809 field = mono_field_from_token (ctx->image, token, klass, ctx->generic_context);
810 if (!field || !field->parent) {
811 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);
812 return NULL;
815 if (!mono_type_is_valid_in_context (ctx, &field->parent->byval_arg))
816 return NULL;
818 return field;
821 static MonoMethod*
822 verifier_load_method (VerifyContext *ctx, int token, const char *opcode) {
823 MonoMethod* method;
825 if (!IS_METHOD_DEF_OR_REF_OR_SPEC (token) || !token_bounds_check (ctx->image, token)) {
826 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);
827 return NULL;
830 method = mono_get_method_full (ctx->image, token, NULL, ctx->generic_context);
832 if (!method) {
833 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);
834 return NULL;
837 if (mono_method_is_valid_in_context (ctx, method) == RESULT_INVALID)
838 return NULL;
840 return method;
843 static MonoType*
844 verifier_load_type (VerifyContext *ctx, int token, const char *opcode) {
845 MonoType* type;
847 if (!IS_TYPE_DEF_OR_REF_OR_SPEC (token) || !token_bounds_check (ctx->image, token)) {
848 ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid type token 0x%08x at 0x%04x", token, ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE);
849 return NULL;
852 type = mono_type_get_full (ctx->image, token, ctx->generic_context);
854 if (!type) {
855 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);
856 return NULL;
859 if (!mono_type_is_valid_in_context (ctx, type))
860 return NULL;
862 return type;
866 /* stack_slot_get_type:
868 * Returns the stack type of @value. This value includes POINTER_MASK.
870 * Use this function to checks that account for a managed pointer.
872 static gint32
873 stack_slot_get_type (ILStackDesc *value)
875 return value->stype & RAW_TYPE_MASK;
878 /* stack_slot_get_underlying_type:
880 * Returns the stack type of @value. This value does not include POINTER_MASK.
882 * Use this function is cases where the fact that the value could be a managed pointer is
883 * irrelevant. For example, field load doesn't care about this fact of type on stack.
885 static gint32
886 stack_slot_get_underlying_type (ILStackDesc *value)
888 return value->stype & TYPE_MASK;
891 /* stack_slot_is_managed_pointer:
893 * Returns TRUE is @value is a managed pointer.
895 static gboolean
896 stack_slot_is_managed_pointer (ILStackDesc *value)
898 return (value->stype & POINTER_MASK) == POINTER_MASK;
901 /* stack_slot_is_managed_mutability_pointer:
903 * Returns TRUE is @value is a managed mutability pointer.
905 static G_GNUC_UNUSED gboolean
906 stack_slot_is_managed_mutability_pointer (ILStackDesc *value)
908 return (value->stype & CMMP_MASK) == CMMP_MASK;
911 /* stack_slot_is_null_literal:
913 * Returns TRUE is @value is the null literal.
915 static gboolean
916 stack_slot_is_null_literal (ILStackDesc *value)
918 return (value->stype & NULL_LITERAL_MASK) == NULL_LITERAL_MASK;
922 /* stack_slot_is_this_pointer:
924 * Returns TRUE is @value is the this literal
926 static gboolean
927 stack_slot_is_this_pointer (ILStackDesc *value)
929 return (value->stype & THIS_POINTER_MASK) == THIS_POINTER_MASK;
932 /* stack_slot_is_boxed_value:
934 * Returns TRUE is @value is a boxed value
936 static gboolean
937 stack_slot_is_boxed_value (ILStackDesc *value)
939 return (value->stype & BOXED_MASK) == BOXED_MASK;
942 static const char *
943 stack_slot_get_name (ILStackDesc *value)
945 return type_names [value->stype & TYPE_MASK];
948 #define APPEND_WITH_PREDICATE(PRED,NAME) do {\
949 if (PRED (value)) { \
950 if (!first) \
951 g_string_append (str, ", "); \
952 g_string_append (str, NAME); \
953 first = FALSE; \
954 } } while (0)
956 static char*
957 stack_slot_stack_type_full_name (ILStackDesc *value)
959 GString *str = g_string_new ("");
960 char *result;
962 if ((value->stype & TYPE_MASK) != value->stype) {
963 gboolean first = TRUE;
964 g_string_append(str, "[");
965 APPEND_WITH_PREDICATE (stack_slot_is_this_pointer, "this");
966 APPEND_WITH_PREDICATE (stack_slot_is_boxed_value, "boxed");
967 APPEND_WITH_PREDICATE (stack_slot_is_null_literal, "null");
968 APPEND_WITH_PREDICATE (stack_slot_is_managed_mutability_pointer, "cmmp");
969 APPEND_WITH_PREDICATE (stack_slot_is_managed_pointer, "mp");
970 g_string_append(str, "] ");
973 g_string_append (str, stack_slot_get_name (value));
974 result = str->str;
975 g_string_free (str, FALSE);
976 return result;
979 static char*
980 stack_slot_full_name (ILStackDesc *value)
982 char *type_name = mono_type_full_name (value->type);
983 char *stack_name = stack_slot_stack_type_full_name (value);
984 char *res = g_strdup_printf ("%s (%s)", type_name, stack_name);
985 g_free (type_name);
986 g_free (stack_name);
987 return res;
990 //////////////////////////////////////////////////////////////////
991 void
992 mono_free_verify_list (GSList *list)
994 MonoVerifyInfoExtended *info;
995 GSList *tmp;
997 for (tmp = list; tmp; tmp = tmp->next) {
998 info = tmp->data;
999 g_free (info->info.message);
1000 g_free (info);
1002 g_slist_free (list);
1005 #define ADD_ERROR(list,msg) \
1006 do { \
1007 MonoVerifyInfoExtended *vinfo = g_new (MonoVerifyInfoExtended, 1); \
1008 vinfo->info.status = MONO_VERIFY_ERROR; \
1009 vinfo->info.message = (msg); \
1010 (list) = g_slist_prepend ((list), vinfo); \
1011 } while (0)
1013 #define ADD_WARN(list,code,msg) \
1014 do { \
1015 MonoVerifyInfoExtended *vinfo = g_new (MonoVerifyInfoExtended, 1); \
1016 vinfo->info.status = (code); \
1017 vinfo->info.message = (msg); \
1018 (list) = g_slist_prepend ((list), vinfo); \
1019 } while (0)
1021 static const char
1022 valid_cultures[][9] = {
1023 "ar-SA", "ar-IQ", "ar-EG", "ar-LY",
1024 "ar-DZ", "ar-MA", "ar-TN", "ar-OM",
1025 "ar-YE", "ar-SY", "ar-JO", "ar-LB",
1026 "ar-KW", "ar-AE", "ar-BH", "ar-QA",
1027 "bg-BG", "ca-ES", "zh-TW", "zh-CN",
1028 "zh-HK", "zh-SG", "zh-MO", "cs-CZ",
1029 "da-DK", "de-DE", "de-CH", "de-AT",
1030 "de-LU", "de-LI", "el-GR", "en-US",
1031 "en-GB", "en-AU", "en-CA", "en-NZ",
1032 "en-IE", "en-ZA", "en-JM", "en-CB",
1033 "en-BZ", "en-TT", "en-ZW", "en-PH",
1034 "es-ES-Ts", "es-MX", "es-ES-Is", "es-GT",
1035 "es-CR", "es-PA", "es-DO", "es-VE",
1036 "es-CO", "es-PE", "es-AR", "es-EC",
1037 "es-CL", "es-UY", "es-PY", "es-BO",
1038 "es-SV", "es-HN", "es-NI", "es-PR",
1039 "Fi-FI", "fr-FR", "fr-BE", "fr-CA",
1040 "Fr-CH", "fr-LU", "fr-MC", "he-IL",
1041 "hu-HU", "is-IS", "it-IT", "it-CH",
1042 "Ja-JP", "ko-KR", "nl-NL", "nl-BE",
1043 "nb-NO", "nn-NO", "pl-PL", "pt-BR",
1044 "pt-PT", "ro-RO", "ru-RU", "hr-HR",
1045 "Lt-sr-SP", "Cy-sr-SP", "sk-SK", "sq-AL",
1046 "sv-SE", "sv-FI", "th-TH", "tr-TR",
1047 "ur-PK", "id-ID", "uk-UA", "be-BY",
1048 "sl-SI", "et-EE", "lv-LV", "lt-LT",
1049 "fa-IR", "vi-VN", "hy-AM", "Lt-az-AZ",
1050 "Cy-az-AZ",
1051 "eu-ES", "mk-MK", "af-ZA",
1052 "ka-GE", "fo-FO", "hi-IN", "ms-MY",
1053 "ms-BN", "kk-KZ", "ky-KZ", "sw-KE",
1054 "Lt-uz-UZ", "Cy-uz-UZ", "tt-TA", "pa-IN",
1055 "gu-IN", "ta-IN", "te-IN", "kn-IN",
1056 "mr-IN", "sa-IN", "mn-MN", "gl-ES",
1057 "kok-IN", "syr-SY", "div-MV"
1060 static int
1061 is_valid_culture (const char *cname)
1063 int i;
1064 int found;
1066 found = *cname == 0;
1067 for (i = 0; i < G_N_ELEMENTS (valid_cultures); ++i) {
1068 if (g_strcasecmp (valid_cultures [i], cname)) {
1069 found = 1;
1070 break;
1073 return found;
1076 static int
1077 is_valid_assembly_flags (guint32 flags) {
1078 /* Metadata: 22.1.2 */
1079 flags &= ~(0x8000 | 0x4000); /* ignore reserved bits 0x0030? */
1080 return ((flags == 1) || (flags == 0));
1083 static int
1084 is_valid_blob (MonoImage *image, guint32 blob_index, int notnull)
1086 guint32 size;
1087 const char *p, *blob_end;
1089 if (blob_index >= image->heap_blob.size)
1090 return 0;
1091 p = mono_metadata_blob_heap (image, blob_index);
1092 size = mono_metadata_decode_blob_size (p, &blob_end);
1093 if (blob_index + size + (blob_end-p) > image->heap_blob.size)
1094 return 0;
1095 if (notnull && !size)
1096 return 0;
1097 return 1;
1100 static const char*
1101 is_valid_string (MonoImage *image, guint32 str_index, int notnull)
1103 const char *p, *blob_end, *res;
1105 if (str_index >= image->heap_strings.size)
1106 return NULL;
1107 res = p = mono_metadata_string_heap (image, str_index);
1108 blob_end = mono_metadata_string_heap (image, image->heap_strings.size - 1);
1109 if (notnull && !*p)
1110 return 0;
1112 * FIXME: should check it's a valid utf8 string, too.
1114 while (p <= blob_end) {
1115 if (!*p)
1116 return res;
1117 ++p;
1119 return *p? NULL: res;
1122 static int
1123 is_valid_cls_ident (const char *p)
1126 * FIXME: we need the full unicode glib support for this.
1127 * Check: http://www.unicode.org/unicode/reports/tr15/Identifier.java
1128 * We do the lame thing for now.
1130 if (!isalpha (*p))
1131 return 0;
1132 ++p;
1133 while (*p) {
1134 if (!isalnum (*p) && *p != '_')
1135 return 0;
1136 ++p;
1138 return 1;
1141 static int
1142 is_valid_filename (const char *p)
1144 if (!*p)
1145 return 0;
1146 return strpbrk (p, "\\//:")? 0: 1;
1149 static GSList*
1150 verify_assembly_table (MonoImage *image, GSList *list, int level)
1152 MonoTableInfo *t = &image->tables [MONO_TABLE_ASSEMBLY];
1153 guint32 cols [MONO_ASSEMBLY_SIZE];
1154 const char *p;
1156 if (level & MONO_VERIFY_ERROR) {
1157 if (t->rows > 1)
1158 ADD_ERROR (list, g_strdup ("Assembly table may only have 0 or 1 rows"));
1159 mono_metadata_decode_row (t, 0, cols, MONO_ASSEMBLY_SIZE);
1161 switch (cols [MONO_ASSEMBLY_HASH_ALG]) {
1162 case ASSEMBLY_HASH_NONE:
1163 case ASSEMBLY_HASH_MD5:
1164 case ASSEMBLY_HASH_SHA1:
1165 break;
1166 default:
1167 ADD_ERROR (list, g_strdup_printf ("Hash algorithm 0x%x unknown", cols [MONO_ASSEMBLY_HASH_ALG]));
1170 if (!is_valid_assembly_flags (cols [MONO_ASSEMBLY_FLAGS]))
1171 ADD_ERROR (list, g_strdup_printf ("Invalid flags in assembly: 0x%x", cols [MONO_ASSEMBLY_FLAGS]));
1173 if (!is_valid_blob (image, cols [MONO_ASSEMBLY_PUBLIC_KEY], FALSE))
1174 ADD_ERROR (list, g_strdup ("Assembly public key is an invalid index"));
1176 if (!(p = is_valid_string (image, cols [MONO_ASSEMBLY_NAME], TRUE))) {
1177 ADD_ERROR (list, g_strdup ("Assembly name is invalid"));
1178 } else {
1179 if (strpbrk (p, ":\\/."))
1180 ADD_ERROR (list, g_strdup_printf ("Assembly name `%s' contains invalid chars", p));
1183 if (!(p = is_valid_string (image, cols [MONO_ASSEMBLY_CULTURE], FALSE))) {
1184 ADD_ERROR (list, g_strdup ("Assembly culture is an invalid index"));
1185 } else {
1186 if (!is_valid_culture (p))
1187 ADD_ERROR (list, g_strdup_printf ("Assembly culture `%s' is invalid", p));
1190 return list;
1193 static GSList*
1194 verify_assemblyref_table (MonoImage *image, GSList *list, int level)
1196 MonoTableInfo *t = &image->tables [MONO_TABLE_ASSEMBLYREF];
1197 guint32 cols [MONO_ASSEMBLYREF_SIZE];
1198 const char *p;
1199 int i;
1201 if (level & MONO_VERIFY_ERROR) {
1202 for (i = 0; i < t->rows; ++i) {
1203 mono_metadata_decode_row (t, i, cols, MONO_ASSEMBLYREF_SIZE);
1204 if (!is_valid_assembly_flags (cols [MONO_ASSEMBLYREF_FLAGS]))
1205 ADD_ERROR (list, g_strdup_printf ("Invalid flags in assemblyref row %d: 0x%x", i + 1, cols [MONO_ASSEMBLY_FLAGS]));
1207 if (!is_valid_blob (image, cols [MONO_ASSEMBLYREF_PUBLIC_KEY], FALSE))
1208 ADD_ERROR (list, g_strdup_printf ("AssemblyRef public key in row %d is an invalid index", i + 1));
1210 if (!(p = is_valid_string (image, cols [MONO_ASSEMBLYREF_CULTURE], FALSE))) {
1211 ADD_ERROR (list, g_strdup_printf ("AssemblyRef culture in row %d is invalid", i + 1));
1212 } else {
1213 if (!is_valid_culture (p))
1214 ADD_ERROR (list, g_strdup_printf ("AssemblyRef culture `%s' in row %d is invalid", p, i + 1));
1217 if (cols [MONO_ASSEMBLYREF_HASH_VALUE] && !is_valid_blob (image, cols [MONO_ASSEMBLYREF_HASH_VALUE], TRUE))
1218 ADD_ERROR (list, g_strdup_printf ("AssemblyRef hash value in row %d is invalid or not null and empty", i + 1));
1221 if (level & MONO_VERIFY_WARNING) {
1222 /* check for duplicated rows */
1223 for (i = 0; i < t->rows; ++i) {
1226 return list;
1229 static GSList*
1230 verify_class_layout_table (MonoImage *image, GSList *list, int level)
1232 MonoTableInfo *t = &image->tables [MONO_TABLE_CLASSLAYOUT];
1233 MonoTableInfo *tdef = &image->tables [MONO_TABLE_TYPEDEF];
1234 guint32 cols [MONO_CLASS_LAYOUT_SIZE];
1235 guint32 value, i;
1237 if (level & MONO_VERIFY_ERROR) {
1238 for (i = 0; i < t->rows; ++i) {
1239 mono_metadata_decode_row (t, i, cols, MONO_CLASS_LAYOUT_SIZE);
1241 if (cols [MONO_CLASS_LAYOUT_PARENT] > tdef->rows || !cols [MONO_CLASS_LAYOUT_PARENT]) {
1242 ADD_ERROR (list, g_strdup_printf ("Parent in class layout is invalid in row %d", i + 1));
1243 } else {
1244 value = mono_metadata_decode_row_col (tdef, cols [MONO_CLASS_LAYOUT_PARENT] - 1, MONO_TYPEDEF_FLAGS);
1245 if (value & TYPE_ATTRIBUTE_INTERFACE)
1246 ADD_ERROR (list, g_strdup_printf ("Parent in class layout row %d is an interface", i + 1));
1247 if (value & TYPE_ATTRIBUTE_AUTO_LAYOUT)
1248 ADD_ERROR (list, g_strdup_printf ("Parent in class layout row %d is AutoLayout", i + 1));
1249 if (value & TYPE_ATTRIBUTE_SEQUENTIAL_LAYOUT) {
1250 switch (cols [MONO_CLASS_LAYOUT_PACKING_SIZE]) {
1251 case 0: case 1: case 2: case 4: case 8: case 16:
1252 case 32: case 64: case 128: break;
1253 default:
1254 ADD_ERROR (list, g_strdup_printf ("Packing size %d in class layout row %d is invalid", cols [MONO_CLASS_LAYOUT_PACKING_SIZE], i + 1));
1256 } else if (value & TYPE_ATTRIBUTE_EXPLICIT_LAYOUT) {
1258 * FIXME: LAMESPEC: it claims it must be 0 (it's 1, instead).
1259 if (cols [MONO_CLASS_LAYOUT_PACKING_SIZE])
1260 ADD_ERROR (list, g_strdup_printf ("Packing size %d in class layout row %d is invalid with explicit layout", cols [MONO_CLASS_LAYOUT_PACKING_SIZE], i + 1));
1264 * FIXME: we need to check that if class size != 0,
1265 * it needs to be greater than the class calculated size.
1266 * If parent is a valuetype it also needs to be smaller than
1267 * 1 MByte (0x100000 bytes).
1268 * To do both these checks we need to load the referenced
1269 * assemblies, though (the spec claims we didn't have to, bah).
1272 * We need to check that the parent types have the same layout
1273 * type as well.
1279 return list;
1282 static GSList*
1283 verify_constant_table (MonoImage *image, GSList *list, int level)
1285 MonoTableInfo *t = &image->tables [MONO_TABLE_CONSTANT];
1286 guint32 cols [MONO_CONSTANT_SIZE];
1287 guint32 value, i;
1288 GHashTable *dups = g_hash_table_new (NULL, NULL);
1290 for (i = 0; i < t->rows; ++i) {
1291 mono_metadata_decode_row (t, i, cols, MONO_CONSTANT_SIZE);
1293 if (level & MONO_VERIFY_ERROR)
1294 if (g_hash_table_lookup (dups, GUINT_TO_POINTER (cols [MONO_CONSTANT_PARENT])))
1295 ADD_ERROR (list, g_strdup_printf ("Parent 0x%08x is duplicated in Constant row %d", cols [MONO_CONSTANT_PARENT], i + 1));
1296 g_hash_table_insert (dups, GUINT_TO_POINTER (cols [MONO_CONSTANT_PARENT]),
1297 GUINT_TO_POINTER (cols [MONO_CONSTANT_PARENT]));
1299 switch (cols [MONO_CONSTANT_TYPE]) {
1300 case MONO_TYPE_U1: /* LAMESPEC: it says I1...*/
1301 case MONO_TYPE_U2:
1302 case MONO_TYPE_U4:
1303 case MONO_TYPE_U8:
1304 if (level & MONO_VERIFY_CLS)
1305 ADD_WARN (list, MONO_VERIFY_CLS, g_strdup_printf ("Type 0x%x not CLS compliant in Constant row %d", cols [MONO_CONSTANT_TYPE], i + 1));
1306 case MONO_TYPE_BOOLEAN:
1307 case MONO_TYPE_CHAR:
1308 case MONO_TYPE_I1:
1309 case MONO_TYPE_I2:
1310 case MONO_TYPE_I4:
1311 case MONO_TYPE_I8:
1312 case MONO_TYPE_R4:
1313 case MONO_TYPE_R8:
1314 case MONO_TYPE_STRING:
1315 case MONO_TYPE_CLASS:
1316 break;
1317 default:
1318 if (level & MONO_VERIFY_ERROR)
1319 ADD_ERROR (list, g_strdup_printf ("Type 0x%x is invalid in Constant row %d", cols [MONO_CONSTANT_TYPE], i + 1));
1321 if (level & MONO_VERIFY_ERROR) {
1322 value = cols [MONO_CONSTANT_PARENT] >> MONO_HASCONSTANT_BITS;
1323 switch (cols [MONO_CONSTANT_PARENT] & MONO_HASCONSTANT_MASK) {
1324 case MONO_HASCONSTANT_FIEDDEF:
1325 if (value > image->tables [MONO_TABLE_FIELD].rows)
1326 ADD_ERROR (list, g_strdup_printf ("Parent (field) is invalid in Constant row %d", i + 1));
1327 break;
1328 case MONO_HASCONSTANT_PARAM:
1329 if (value > image->tables [MONO_TABLE_PARAM].rows)
1330 ADD_ERROR (list, g_strdup_printf ("Parent (param) is invalid in Constant row %d", i + 1));
1331 break;
1332 case MONO_HASCONSTANT_PROPERTY:
1333 if (value > image->tables [MONO_TABLE_PROPERTY].rows)
1334 ADD_ERROR (list, g_strdup_printf ("Parent (property) is invalid in Constant row %d", i + 1));
1335 break;
1336 default:
1337 ADD_ERROR (list, g_strdup_printf ("Parent is invalid in Constant row %d", i + 1));
1338 break;
1341 if (level & MONO_VERIFY_CLS) {
1343 * FIXME: verify types is consistent with the enum type
1344 * is parent is an enum.
1348 g_hash_table_destroy (dups);
1349 return list;
1352 static GSList*
1353 verify_event_map_table (MonoImage *image, GSList *list, int level)
1355 MonoTableInfo *t = &image->tables [MONO_TABLE_EVENTMAP];
1356 guint32 cols [MONO_EVENT_MAP_SIZE];
1357 guint32 i, last_event;
1358 GHashTable *dups = g_hash_table_new (NULL, NULL);
1360 last_event = 0;
1362 for (i = 0; i < t->rows; ++i) {
1363 mono_metadata_decode_row (t, i, cols, MONO_EVENT_MAP_SIZE);
1364 if (level & MONO_VERIFY_ERROR)
1365 if (g_hash_table_lookup (dups, GUINT_TO_POINTER (cols [MONO_EVENT_MAP_PARENT])))
1366 ADD_ERROR (list, g_strdup_printf ("Parent 0x%08x is duplicated in Event Map row %d", cols [MONO_EVENT_MAP_PARENT], i + 1));
1367 g_hash_table_insert (dups, GUINT_TO_POINTER (cols [MONO_EVENT_MAP_PARENT]),
1368 GUINT_TO_POINTER (cols [MONO_EVENT_MAP_PARENT]));
1369 if (level & MONO_VERIFY_ERROR) {
1370 if (cols [MONO_EVENT_MAP_PARENT] > image->tables [MONO_TABLE_TYPEDEF].rows)
1371 ADD_ERROR (list, g_strdup_printf ("Parent 0x%08x is invalid in Event Map row %d", cols [MONO_EVENT_MAP_PARENT], i + 1));
1372 if (cols [MONO_EVENT_MAP_EVENTLIST] > image->tables [MONO_TABLE_EVENT].rows)
1373 ADD_ERROR (list, g_strdup_printf ("EventList 0x%08x is invalid in Event Map row %d", cols [MONO_EVENT_MAP_EVENTLIST], i + 1));
1375 if (cols [MONO_EVENT_MAP_EVENTLIST] <= last_event)
1376 ADD_ERROR (list, g_strdup_printf ("EventList overlap in Event Map row %d", i + 1));
1377 last_event = cols [MONO_EVENT_MAP_EVENTLIST];
1381 g_hash_table_destroy (dups);
1382 return list;
1385 static GSList*
1386 verify_event_table (MonoImage *image, GSList *list, int level)
1388 MonoTableInfo *t = &image->tables [MONO_TABLE_EVENT];
1389 guint32 cols [MONO_EVENT_SIZE];
1390 const char *p;
1391 guint32 value, i;
1393 for (i = 0; i < t->rows; ++i) {
1394 mono_metadata_decode_row (t, i, cols, MONO_EVENT_SIZE);
1396 if (cols [MONO_EVENT_FLAGS] & ~(EVENT_SPECIALNAME|EVENT_RTSPECIALNAME)) {
1397 if (level & MONO_VERIFY_ERROR)
1398 ADD_ERROR (list, g_strdup_printf ("Flags 0x%04x invalid in Event row %d", cols [MONO_EVENT_FLAGS], i + 1));
1400 if (!(p = is_valid_string (image, cols [MONO_EVENT_NAME], TRUE))) {
1401 if (level & MONO_VERIFY_ERROR)
1402 ADD_ERROR (list, g_strdup_printf ("Invalid name in Event row %d", i + 1));
1403 } else {
1404 if (level & MONO_VERIFY_CLS) {
1405 if (!is_valid_cls_ident (p))
1406 ADD_WARN (list, MONO_VERIFY_CLS, g_strdup_printf ("Invalid CLS name '%s` in Event row %d", p, i + 1));
1410 if (level & MONO_VERIFY_ERROR && cols [MONO_EVENT_TYPE]) {
1411 value = cols [MONO_EVENT_TYPE] >> MONO_TYPEDEFORREF_BITS;
1412 switch (cols [MONO_EVENT_TYPE] & MONO_TYPEDEFORREF_MASK) {
1413 case MONO_TYPEDEFORREF_TYPEDEF:
1414 if (!value || value > image->tables [MONO_TABLE_TYPEDEF].rows)
1415 ADD_ERROR (list, g_strdup_printf ("Type invalid in Event row %d", i + 1));
1416 break;
1417 case MONO_TYPEDEFORREF_TYPEREF:
1418 if (!value || value > image->tables [MONO_TABLE_TYPEREF].rows)
1419 ADD_ERROR (list, g_strdup_printf ("Type invalid in Event row %d", i + 1));
1420 break;
1421 case MONO_TYPEDEFORREF_TYPESPEC:
1422 if (!value || value > image->tables [MONO_TABLE_TYPESPEC].rows)
1423 ADD_ERROR (list, g_strdup_printf ("Type invalid in Event row %d", i + 1));
1424 break;
1425 default:
1426 ADD_ERROR (list, g_strdup_printf ("Type invalid in Event row %d", i + 1));
1430 * FIXME: check that there is 1 add and remove row in methodsemantics
1431 * and 0 or 1 raise and 0 or more other (maybe it's better to check for
1432 * these while checking methodsemantics).
1433 * check for duplicated names for the same type [ERROR]
1434 * check for CLS duplicate names for the same type [CLS]
1437 return list;
1440 static GSList*
1441 verify_field_table (MonoImage *image, GSList *list, int level)
1443 MonoTableInfo *t = &image->tables [MONO_TABLE_FIELD];
1444 guint32 cols [MONO_FIELD_SIZE];
1445 const char *p;
1446 guint32 i, flags;
1448 for (i = 0; i < t->rows; ++i) {
1449 mono_metadata_decode_row (t, i, cols, MONO_FIELD_SIZE);
1451 * Check this field has only one owner and that the owner is not
1452 * an interface (done in verify_typedef_table() )
1454 flags = cols [MONO_FIELD_FLAGS];
1455 switch (flags & FIELD_ATTRIBUTE_FIELD_ACCESS_MASK) {
1456 case FIELD_ATTRIBUTE_COMPILER_CONTROLLED:
1457 case FIELD_ATTRIBUTE_PRIVATE:
1458 case FIELD_ATTRIBUTE_FAM_AND_ASSEM:
1459 case FIELD_ATTRIBUTE_ASSEMBLY:
1460 case FIELD_ATTRIBUTE_FAMILY:
1461 case FIELD_ATTRIBUTE_FAM_OR_ASSEM:
1462 case FIELD_ATTRIBUTE_PUBLIC:
1463 break;
1464 default:
1465 if (level & MONO_VERIFY_ERROR)
1466 ADD_ERROR (list, g_strdup_printf ("Invalid access mask in Field row %d", i + 1));
1467 break;
1469 if (level & MONO_VERIFY_ERROR) {
1470 if ((flags & FIELD_ATTRIBUTE_LITERAL) && (flags & FIELD_ATTRIBUTE_INIT_ONLY))
1471 ADD_ERROR (list, g_strdup_printf ("Literal and InitOnly cannot be both set in Field row %d", i + 1));
1472 if ((flags & FIELD_ATTRIBUTE_LITERAL) && !(flags & FIELD_ATTRIBUTE_STATIC))
1473 ADD_ERROR (list, g_strdup_printf ("Literal needs also Static set in Field row %d", i + 1));
1474 if ((flags & FIELD_ATTRIBUTE_RT_SPECIAL_NAME) && !(flags & FIELD_ATTRIBUTE_SPECIAL_NAME))
1475 ADD_ERROR (list, g_strdup_printf ("RTSpecialName needs also SpecialName set in Field row %d", i + 1));
1477 * FIXME: check there is only one owner in the respective table.
1478 * if (flags & FIELD_ATTRIBUTE_HAS_FIELD_MARSHAL)
1479 * if (flags & FIELD_ATTRIBUTE_HAS_DEFAULT)
1480 * if (flags & FIELD_ATTRIBUTE_HAS_FIELD_RVA)
1483 if (!(p = is_valid_string (image, cols [MONO_FIELD_NAME], TRUE))) {
1484 if (level & MONO_VERIFY_ERROR)
1485 ADD_ERROR (list, g_strdup_printf ("Invalid name in Field row %d", i + 1));
1486 } else {
1487 if (level & MONO_VERIFY_CLS) {
1488 if (!is_valid_cls_ident (p))
1489 ADD_WARN (list, MONO_VERIFY_CLS, g_strdup_printf ("Invalid CLS name '%s` in Field row %d", p, i + 1));
1493 * check signature.
1494 * if owner is module needs to be static, access mask needs to be compilercontrolled,
1495 * public or private (not allowed in cls mode).
1496 * if owner is an enum ...
1501 return list;
1504 static GSList*
1505 verify_file_table (MonoImage *image, GSList *list, int level)
1507 MonoTableInfo *t = &image->tables [MONO_TABLE_FILE];
1508 guint32 cols [MONO_FILE_SIZE];
1509 const char *p;
1510 guint32 i;
1511 GHashTable *dups = g_hash_table_new (g_str_hash, g_str_equal);
1513 for (i = 0; i < t->rows; ++i) {
1514 mono_metadata_decode_row (t, i, cols, MONO_FILE_SIZE);
1515 if (level & MONO_VERIFY_ERROR) {
1516 if (cols [MONO_FILE_FLAGS] != FILE_CONTAINS_METADATA && cols [MONO_FILE_FLAGS] != FILE_CONTAINS_NO_METADATA)
1517 ADD_ERROR (list, g_strdup_printf ("Invalid flags in File row %d", i + 1));
1518 if (!is_valid_blob (image, cols [MONO_FILE_HASH_VALUE], TRUE))
1519 ADD_ERROR (list, g_strdup_printf ("File hash value in row %d is invalid or not null and empty", i + 1));
1521 if (!(p = is_valid_string (image, cols [MONO_FILE_NAME], TRUE))) {
1522 if (level & MONO_VERIFY_ERROR)
1523 ADD_ERROR (list, g_strdup_printf ("Invalid name in File row %d", i + 1));
1524 } else {
1525 if (level & MONO_VERIFY_ERROR) {
1526 if (!is_valid_filename (p))
1527 ADD_ERROR (list, g_strdup_printf ("Invalid name '%s` in File row %d", p, i + 1));
1528 else if (g_hash_table_lookup (dups, p)) {
1529 ADD_ERROR (list, g_strdup_printf ("Duplicate name '%s` in File row %d", p, i + 1));
1531 g_hash_table_insert (dups, (gpointer)p, (gpointer)p);
1535 * FIXME: I don't understand what this means:
1536 * If this module contains a row in the Assembly table (that is, if this module "holds the manifest")
1537 * then there shall not be any row in the File table for this module - i.e., no self-reference [ERROR]
1541 if (level & MONO_VERIFY_WARNING) {
1542 if (!t->rows && image->tables [MONO_TABLE_EXPORTEDTYPE].rows)
1543 ADD_WARN (list, MONO_VERIFY_WARNING, g_strdup ("ExportedType table should be empty if File table is empty"));
1545 g_hash_table_destroy (dups);
1546 return list;
1549 static GSList*
1550 verify_moduleref_table (MonoImage *image, GSList *list, int level)
1552 MonoTableInfo *t = &image->tables [MONO_TABLE_MODULEREF];
1553 MonoTableInfo *tfile = &image->tables [MONO_TABLE_FILE];
1554 guint32 cols [MONO_MODULEREF_SIZE];
1555 const char *p, *pf;
1556 guint32 found, i, j, value;
1557 GHashTable *dups = g_hash_table_new (g_str_hash, g_str_equal);
1559 for (i = 0; i < t->rows; ++i) {
1560 mono_metadata_decode_row (t, i, cols, MONO_MODULEREF_SIZE);
1561 if (!(p = is_valid_string (image, cols [MONO_MODULEREF_NAME], TRUE))) {
1562 if (level & MONO_VERIFY_ERROR)
1563 ADD_ERROR (list, g_strdup_printf ("Invalid name in ModuleRef row %d", i + 1));
1564 } else {
1565 if (level & MONO_VERIFY_ERROR) {
1566 if (!is_valid_filename (p))
1567 ADD_ERROR (list, g_strdup_printf ("Invalid name '%s` in ModuleRef row %d", p, i + 1));
1568 else if (g_hash_table_lookup (dups, p)) {
1569 ADD_WARN (list, MONO_VERIFY_WARNING, g_strdup_printf ("Duplicate name '%s` in ModuleRef row %d", p, i + 1));
1570 g_hash_table_insert (dups, (gpointer)p, (gpointer)p);
1571 found = 0;
1572 for (j = 0; j < tfile->rows; ++j) {
1573 value = mono_metadata_decode_row_col (tfile, j, MONO_FILE_NAME);
1574 if ((pf = is_valid_string (image, value, TRUE)))
1575 if (strcmp (p, pf) == 0) {
1576 found = 1;
1577 break;
1580 if (!found)
1581 ADD_ERROR (list, g_strdup_printf ("Name '%s` in ModuleRef row %d doesn't have a match in File table", p, i + 1));
1586 g_hash_table_destroy (dups);
1587 return list;
1590 static GSList*
1591 verify_standalonesig_table (MonoImage *image, GSList *list, int level)
1593 MonoTableInfo *t = &image->tables [MONO_TABLE_STANDALONESIG];
1594 guint32 cols [MONO_STAND_ALONE_SIGNATURE_SIZE];
1595 const char *p;
1596 guint32 i;
1598 for (i = 0; i < t->rows; ++i) {
1599 mono_metadata_decode_row (t, i, cols, MONO_STAND_ALONE_SIGNATURE_SIZE);
1600 if (level & MONO_VERIFY_ERROR) {
1601 if (!is_valid_blob (image, cols [MONO_STAND_ALONE_SIGNATURE], TRUE)) {
1602 ADD_ERROR (list, g_strdup_printf ("Signature is invalid in StandAloneSig row %d", i + 1));
1603 } else {
1604 p = mono_metadata_blob_heap (image, cols [MONO_STAND_ALONE_SIGNATURE]);
1605 /* FIXME: check it's a valid locals or method sig.*/
1609 return list;
1612 GSList*
1613 mono_image_verify_tables (MonoImage *image, int level)
1615 GSList *error_list = NULL;
1617 error_list = verify_assembly_table (image, error_list, level);
1619 * AssemblyOS, AssemblyProcessor, AssemblyRefOs and
1620 * AssemblyRefProcessor should be ignored,
1621 * though we may want to emit a warning, since it should not
1622 * be present in a PE file.
1624 error_list = verify_assemblyref_table (image, error_list, level);
1625 error_list = verify_class_layout_table (image, error_list, level);
1626 error_list = verify_constant_table (image, error_list, level);
1628 * cutom attribute, declsecurity
1630 error_list = verify_event_map_table (image, error_list, level);
1631 error_list = verify_event_table (image, error_list, level);
1632 error_list = verify_field_table (image, error_list, level);
1633 error_list = verify_file_table (image, error_list, level);
1634 error_list = verify_moduleref_table (image, error_list, level);
1635 error_list = verify_standalonesig_table (image, error_list, level);
1637 return g_slist_reverse (error_list);
1640 #define ADD_INVALID(list,msg) \
1641 do { \
1642 MonoVerifyInfoExtended *vinfo = g_new (MonoVerifyInfoExtended, 1); \
1643 vinfo->status = MONO_VERIFY_ERROR; \
1644 vinfo->message = (msg); \
1645 (list) = g_slist_prepend ((list), vinfo); \
1646 /*G_BREAKPOINT ();*/ \
1647 goto invalid_cil; \
1648 } while (0)
1650 #define CHECK_STACK_UNDERFLOW(num) \
1651 do { \
1652 if (cur_stack < (num)) \
1653 ADD_INVALID (list, g_strdup_printf ("Stack underflow at 0x%04x (%d items instead of %d)", ip_offset, cur_stack, (num))); \
1654 } while (0)
1656 #define CHECK_STACK_OVERFLOW() \
1657 do { \
1658 if (cur_stack >= max_stack) \
1659 ADD_INVALID (list, g_strdup_printf ("Maxstack exceeded at 0x%04x", ip_offset)); \
1660 } while (0)
1663 static int
1664 in_any_block (MonoMethodHeader *header, guint offset)
1666 int i;
1667 MonoExceptionClause *clause;
1669 for (i = 0; i < header->num_clauses; ++i) {
1670 clause = &header->clauses [i];
1671 if (MONO_OFFSET_IN_CLAUSE (clause, offset))
1672 return 1;
1673 if (MONO_OFFSET_IN_HANDLER (clause, offset))
1674 return 1;
1675 if (MONO_OFFSET_IN_FILTER (clause, offset))
1676 return 1;
1678 return 0;
1682 * in_any_exception_block:
1684 * Returns TRUE is @offset is part of any exception clause (filter, handler, catch, finally or fault).
1686 static gboolean
1687 in_any_exception_block (MonoMethodHeader *header, guint offset)
1689 int i;
1690 MonoExceptionClause *clause;
1692 for (i = 0; i < header->num_clauses; ++i) {
1693 clause = &header->clauses [i];
1694 if (MONO_OFFSET_IN_HANDLER (clause, offset))
1695 return TRUE;
1696 if (MONO_OFFSET_IN_FILTER (clause, offset))
1697 return TRUE;
1699 return FALSE;
1703 * is_valid_branch_instruction:
1705 * Verify if it's valid to perform a branch from @offset to @target.
1706 * This should be used with br and brtrue/false.
1707 * It returns 0 if valid, 1 for unverifiable and 2 for invalid.
1708 * The major diferent from other similiar functions is that branching into a
1709 * finally/fault block is invalid instead of just unverifiable.
1711 static int
1712 is_valid_branch_instruction (MonoMethodHeader *header, guint offset, guint target)
1714 int i;
1715 MonoExceptionClause *clause;
1717 for (i = 0; i < header->num_clauses; ++i) {
1718 clause = &header->clauses [i];
1719 /*branching into a finally block is invalid*/
1720 if ((clause->flags == MONO_EXCEPTION_CLAUSE_FINALLY || clause->flags == MONO_EXCEPTION_CLAUSE_FAULT) &&
1721 !MONO_OFFSET_IN_HANDLER (clause, offset) &&
1722 MONO_OFFSET_IN_HANDLER (clause, target))
1723 return 2;
1725 if (clause->try_offset != target && (MONO_OFFSET_IN_CLAUSE (clause, offset) ^ MONO_OFFSET_IN_CLAUSE (clause, target)))
1726 return 1;
1727 if (MONO_OFFSET_IN_HANDLER (clause, offset) ^ MONO_OFFSET_IN_HANDLER (clause, target))
1728 return 1;
1729 if (MONO_OFFSET_IN_FILTER (clause, offset) ^ MONO_OFFSET_IN_FILTER (clause, target))
1730 return 1;
1732 return 0;
1736 * is_valid_cmp_branch_instruction:
1738 * Verify if it's valid to perform a branch from @offset to @target.
1739 * This should be used with binary comparison branching instruction, like beq, bge and similars.
1740 * It returns 0 if valid, 1 for unverifiable and 2 for invalid.
1742 * The major diferences from other similar functions are that most errors lead to invalid
1743 * code and only branching out of finally, filter or fault clauses is unverifiable.
1745 static int
1746 is_valid_cmp_branch_instruction (MonoMethodHeader *header, guint offset, guint target)
1748 int i;
1749 MonoExceptionClause *clause;
1751 for (i = 0; i < header->num_clauses; ++i) {
1752 clause = &header->clauses [i];
1753 /*branching out of a handler or finally*/
1754 if (clause->flags != MONO_EXCEPTION_CLAUSE_NONE &&
1755 MONO_OFFSET_IN_HANDLER (clause, offset) &&
1756 !MONO_OFFSET_IN_HANDLER (clause, target))
1757 return 1;
1759 if (clause->try_offset != target && (MONO_OFFSET_IN_CLAUSE (clause, offset) ^ MONO_OFFSET_IN_CLAUSE (clause, target)))
1760 return 2;
1761 if (MONO_OFFSET_IN_HANDLER (clause, offset) ^ MONO_OFFSET_IN_HANDLER (clause, target))
1762 return 2;
1763 if (MONO_OFFSET_IN_FILTER (clause, offset) ^ MONO_OFFSET_IN_FILTER (clause, target))
1764 return 2;
1766 return 0;
1770 * A leave can't escape a finally block
1772 static int
1773 is_correct_leave (MonoMethodHeader *header, guint offset, guint target)
1775 int i;
1776 MonoExceptionClause *clause;
1778 for (i = 0; i < header->num_clauses; ++i) {
1779 clause = &header->clauses [i];
1780 if (clause->flags == MONO_EXCEPTION_CLAUSE_FINALLY && MONO_OFFSET_IN_HANDLER (clause, offset) && !MONO_OFFSET_IN_HANDLER (clause, target))
1781 return 0;
1782 if (MONO_OFFSET_IN_FILTER (clause, offset))
1783 return 0;
1785 return 1;
1789 * A rethrow can't happen outside of a catch handler.
1791 static int
1792 is_correct_rethrow (MonoMethodHeader *header, guint offset)
1794 int i;
1795 MonoExceptionClause *clause;
1797 for (i = 0; i < header->num_clauses; ++i) {
1798 clause = &header->clauses [i];
1799 if (MONO_OFFSET_IN_HANDLER (clause, offset))
1800 return 1;
1801 if (MONO_OFFSET_IN_FILTER (clause, offset))
1802 return 1;
1804 return 0;
1808 * An endfinally can't happen outside of a finally/fault handler.
1810 static int
1811 is_correct_endfinally (MonoMethodHeader *header, guint offset)
1813 int i;
1814 MonoExceptionClause *clause;
1816 for (i = 0; i < header->num_clauses; ++i) {
1817 clause = &header->clauses [i];
1818 if (MONO_OFFSET_IN_HANDLER (clause, offset) && (clause->flags == MONO_EXCEPTION_CLAUSE_FAULT || clause->flags == MONO_EXCEPTION_CLAUSE_FINALLY))
1819 return 1;
1821 return 0;
1826 * An endfilter can only happens inside a filter clause.
1827 * In non-strict mode filter is allowed inside the handler clause too
1829 static MonoExceptionClause *
1830 is_correct_endfilter (VerifyContext *ctx, guint offset)
1832 int i;
1833 MonoExceptionClause *clause;
1835 for (i = 0; i < ctx->header->num_clauses; ++i) {
1836 clause = &ctx->header->clauses [i];
1837 if (clause->flags != MONO_EXCEPTION_CLAUSE_FILTER)
1838 continue;
1839 if (MONO_OFFSET_IN_FILTER (clause, offset))
1840 return clause;
1841 if (!IS_STRICT_MODE (ctx) && MONO_OFFSET_IN_HANDLER (clause, offset))
1842 return clause;
1844 return NULL;
1849 * Non-strict endfilter can happens inside a try block or any handler block
1851 static int
1852 is_unverifiable_endfilter (VerifyContext *ctx, guint offset)
1854 int i;
1855 MonoExceptionClause *clause;
1857 for (i = 0; i < ctx->header->num_clauses; ++i) {
1858 clause = &ctx->header->clauses [i];
1859 if (MONO_OFFSET_IN_CLAUSE (clause, offset))
1860 return 1;
1862 return 0;
1865 static gboolean
1866 is_valid_bool_arg (ILStackDesc *arg)
1868 if (stack_slot_is_managed_pointer (arg) || stack_slot_is_boxed_value (arg) || stack_slot_is_null_literal (arg))
1869 return TRUE;
1872 switch (stack_slot_get_underlying_type (arg)) {
1873 case TYPE_I4:
1874 case TYPE_I8:
1875 case TYPE_NATIVE_INT:
1876 case TYPE_PTR:
1877 return TRUE;
1878 case TYPE_COMPLEX:
1879 g_assert (arg->type);
1880 switch (arg->type->type) {
1881 case MONO_TYPE_CLASS:
1882 case MONO_TYPE_STRING:
1883 case MONO_TYPE_OBJECT:
1884 case MONO_TYPE_SZARRAY:
1885 case MONO_TYPE_ARRAY:
1886 case MONO_TYPE_FNPTR:
1887 case MONO_TYPE_PTR:
1888 return TRUE;
1889 case MONO_TYPE_GENERICINST:
1890 /*We need to check if the container class
1891 * of the generic type is a valuetype, iow:
1892 * is it a "class Foo<T>" or a "struct Foo<T>"?
1894 return !arg->type->data.generic_class->container_class->valuetype;
1896 default:
1897 return FALSE;
1902 /*Type manipulation helper*/
1904 /*Returns the byref version of the supplied MonoType*/
1905 static MonoType*
1906 mono_type_get_type_byref (MonoType *type)
1908 if (type->byref)
1909 return type;
1910 return &mono_class_from_mono_type (type)->this_arg;
1914 /*Returns the byval version of the supplied MonoType*/
1915 static MonoType*
1916 mono_type_get_type_byval (MonoType *type)
1918 if (!type->byref)
1919 return type;
1920 return &mono_class_from_mono_type (type)->byval_arg;
1923 static MonoType*
1924 mono_type_from_stack_slot (ILStackDesc *slot)
1926 if (stack_slot_is_managed_pointer (slot))
1927 return mono_type_get_type_byref (slot->type);
1928 return slot->type;
1931 /*Stack manipulation code*/
1933 static void
1934 stack_init (VerifyContext *ctx, ILCodeDesc *state)
1936 if (state->flags & IL_CODE_FLAG_STACK_INITED)
1937 return;
1938 state->size = 0;
1939 state->flags |= IL_CODE_FLAG_STACK_INITED;
1940 if (!state->stack)
1941 state->stack = g_new0 (ILStackDesc, ctx->max_stack);
1944 static void
1945 stack_copy (ILCodeDesc *to, ILCodeDesc *from)
1947 to->size = from->size;
1948 memcpy (to->stack, from->stack, sizeof (ILStackDesc) * from->size);
1951 static void
1952 copy_stack_value (ILStackDesc *to, ILStackDesc *from)
1954 to->stype = from->stype;
1955 to->type = from->type;
1956 to->method = from->method;
1959 static int
1960 check_underflow (VerifyContext *ctx, int size)
1962 if (ctx->eval.size < size) {
1963 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Stack underflow, required %d, but have %d at 0x%04x", size, ctx->eval.size, ctx->ip_offset));
1964 return 0;
1966 return 1;
1969 static int
1970 check_overflow (VerifyContext *ctx)
1972 if (ctx->eval.size >= ctx->max_stack) {
1973 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Method doesn't have stack-depth %d at 0x%04x", ctx->eval.size + 1, ctx->ip_offset));
1974 return 0;
1976 return 1;
1979 /*This reject out PTR, FNPTR and TYPEDBYREF*/
1980 static gboolean
1981 check_unmanaged_pointer (VerifyContext *ctx, ILStackDesc *value)
1983 if (stack_slot_get_type (value) == TYPE_PTR) {
1984 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Unmanaged pointer is not a verifiable type at 0x%04x", ctx->ip_offset));
1985 return 0;
1987 return 1;
1990 /*TODO verify if MONO_TYPE_TYPEDBYREF is not allowed here as well.*/
1991 static gboolean
1992 check_unverifiable_type (VerifyContext *ctx, MonoType *type)
1994 if (type->type == MONO_TYPE_PTR || type->type == MONO_TYPE_FNPTR) {
1995 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Unmanaged pointer is not a verifiable type at 0x%04x", ctx->ip_offset));
1996 return 0;
1998 return 1;
2002 static ILStackDesc *
2003 stack_push (VerifyContext *ctx)
2005 return & ctx->eval.stack [ctx->eval.size++];
2008 static ILStackDesc *
2009 stack_push_val (VerifyContext *ctx, int stype, MonoType *type)
2011 ILStackDesc *top = stack_push (ctx);
2012 top->stype = stype;
2013 top->type = type;
2014 return top;
2017 static ILStackDesc *
2018 stack_pop (VerifyContext *ctx)
2020 ILStackDesc *ret = ctx->eval.stack + --ctx->eval.size;
2021 if ((ret->stype & UNINIT_THIS_MASK) == UNINIT_THIS_MASK)
2022 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Found use of uninitialized 'this ptr' ref at 0x%04x", ctx->ip_offset));
2023 return ret;
2026 /* This function allows to safely pop an unititialized this ptr from
2027 * the eval stack without marking the method as unverifiable.
2029 static ILStackDesc *
2030 stack_pop_safe (VerifyContext *ctx)
2032 return ctx->eval.stack + --ctx->eval.size;
2035 static ILStackDesc *
2036 stack_push_stack_val (VerifyContext *ctx, ILStackDesc *value)
2038 ILStackDesc *top = stack_push (ctx);
2039 copy_stack_value (top, value);
2040 return top;
2043 /* Returns the MonoType associated with the token, or NULL if it is invalid.
2045 * A boxable type can be either a reference or value type, but cannot be a byref type or an unmanaged pointer
2046 * */
2047 static MonoType*
2048 get_boxable_mono_type (VerifyContext* ctx, int token, const char *opcode)
2050 MonoType *type;
2053 if (!(type = verifier_load_type (ctx, token, opcode)))
2054 return NULL;
2056 if (type->byref && type->type != MONO_TYPE_TYPEDBYREF) {
2057 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid use of byref type for %s at 0x%04x", opcode, ctx->ip_offset));
2058 return NULL;
2061 if (type->type == MONO_TYPE_VOID) {
2062 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid use of void type for %s at 0x%04x", opcode, ctx->ip_offset));
2063 return NULL;
2066 if (type->type == MONO_TYPE_TYPEDBYREF)
2067 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid use of typedbyref for %s at 0x%04x", opcode, ctx->ip_offset));
2069 check_unverifiable_type (ctx, type);
2070 return type;
2074 /*operation result tables */
2076 static const unsigned char bin_op_table [TYPE_MAX][TYPE_MAX] = {
2077 {TYPE_I4, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV},
2078 {TYPE_INV, TYPE_I8, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
2079 {TYPE_NATIVE_INT, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV},
2080 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_R8, TYPE_INV, TYPE_INV},
2081 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
2082 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
2085 static const unsigned char add_table [TYPE_MAX][TYPE_MAX] = {
2086 {TYPE_I4, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV},
2087 {TYPE_INV, TYPE_I8, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
2088 {TYPE_NATIVE_INT, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV},
2089 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_R8, TYPE_INV, TYPE_INV},
2090 {TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV, TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV, TYPE_INV, TYPE_INV},
2091 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
2094 static const unsigned char sub_table [TYPE_MAX][TYPE_MAX] = {
2095 {TYPE_I4, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV},
2096 {TYPE_INV, TYPE_I8, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
2097 {TYPE_NATIVE_INT, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV},
2098 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_R8, TYPE_INV, TYPE_INV},
2099 {TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV, TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV, TYPE_NATIVE_INT | NON_VERIFIABLE_RESULT, TYPE_INV},
2100 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
2103 static const unsigned char int_bin_op_table [TYPE_MAX][TYPE_MAX] = {
2104 {TYPE_I4, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV},
2105 {TYPE_INV, TYPE_I8, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
2106 {TYPE_NATIVE_INT, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV},
2107 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
2108 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
2109 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
2112 static const unsigned char shift_op_table [TYPE_MAX][TYPE_MAX] = {
2113 {TYPE_I4, TYPE_INV, TYPE_I4, TYPE_INV, TYPE_INV, TYPE_INV},
2114 {TYPE_I8, TYPE_INV, TYPE_I8, TYPE_INV, TYPE_INV, TYPE_INV},
2115 {TYPE_NATIVE_INT, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV},
2116 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
2117 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
2118 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
2121 static const unsigned char cmp_br_op [TYPE_MAX][TYPE_MAX] = {
2122 {TYPE_I4, TYPE_INV, TYPE_I4, TYPE_INV, TYPE_INV, TYPE_INV},
2123 {TYPE_INV, TYPE_I4, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
2124 {TYPE_I4, TYPE_INV, TYPE_I4, TYPE_INV, TYPE_INV, TYPE_INV},
2125 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_I4, TYPE_INV, TYPE_INV},
2126 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_I4, TYPE_INV},
2127 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
2130 static const unsigned char cmp_br_eq_op [TYPE_MAX][TYPE_MAX] = {
2131 {TYPE_I4, TYPE_INV, TYPE_I4, TYPE_INV, TYPE_INV, TYPE_INV},
2132 {TYPE_INV, TYPE_I4, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
2133 {TYPE_I4, TYPE_INV, TYPE_I4, TYPE_INV, TYPE_I4 | NON_VERIFIABLE_RESULT, TYPE_INV},
2134 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_I4, TYPE_INV, TYPE_INV},
2135 {TYPE_INV, TYPE_INV, TYPE_I4 | NON_VERIFIABLE_RESULT, TYPE_INV, TYPE_I4, TYPE_INV},
2136 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_I4},
2139 static const unsigned char add_ovf_un_table [TYPE_MAX][TYPE_MAX] = {
2140 {TYPE_I4, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV},
2141 {TYPE_INV, TYPE_I8, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
2142 {TYPE_NATIVE_INT, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV},
2143 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
2144 {TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV, TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV, TYPE_INV, TYPE_INV},
2145 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
2148 static const unsigned char sub_ovf_un_table [TYPE_MAX][TYPE_MAX] = {
2149 {TYPE_I4, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV},
2150 {TYPE_INV, TYPE_I8, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
2151 {TYPE_NATIVE_INT, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV},
2152 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
2153 {TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV, TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV, TYPE_NATIVE_INT | NON_VERIFIABLE_RESULT, TYPE_INV},
2154 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
2157 static const unsigned char bin_ovf_table [TYPE_MAX][TYPE_MAX] = {
2158 {TYPE_I4, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV},
2159 {TYPE_INV, TYPE_I8, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
2160 {TYPE_NATIVE_INT, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV},
2161 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
2162 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
2163 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
2166 #ifdef MONO_VERIFIER_DEBUG
2168 /*debug helpers */
2169 static void
2170 dump_stack_value (ILStackDesc *value)
2172 printf ("[(%x)(%x)", value->type->type, value->stype);
2174 if (stack_slot_is_this_pointer (value))
2175 printf ("[this] ");
2177 if (stack_slot_is_boxed_value (value))
2178 printf ("[boxed] ");
2180 if (stack_slot_is_null_literal (value))
2181 printf ("[null] ");
2183 if (stack_slot_is_managed_mutability_pointer (value))
2184 printf ("Controled Mutability MP: ");
2186 if (stack_slot_is_managed_pointer (value))
2187 printf ("Managed Pointer to: ");
2189 switch (stack_slot_get_underlying_type (value)) {
2190 case TYPE_INV:
2191 printf ("invalid type]");
2192 return;
2193 case TYPE_I4:
2194 printf ("int32]");
2195 return;
2196 case TYPE_I8:
2197 printf ("int64]");
2198 return;
2199 case TYPE_NATIVE_INT:
2200 printf ("native int]");
2201 return;
2202 case TYPE_R8:
2203 printf ("float64]");
2204 return;
2205 case TYPE_PTR:
2206 printf ("unmanaged pointer]");
2207 return;
2208 case TYPE_COMPLEX:
2209 switch (value->type->type) {
2210 case MONO_TYPE_CLASS:
2211 case MONO_TYPE_VALUETYPE:
2212 printf ("complex] (%s)", value->type->data.klass->name);
2213 return;
2214 case MONO_TYPE_STRING:
2215 printf ("complex] (string)");
2216 return;
2217 case MONO_TYPE_OBJECT:
2218 printf ("complex] (object)");
2219 return;
2220 case MONO_TYPE_SZARRAY:
2221 printf ("complex] (%s [])", value->type->data.klass->name);
2222 return;
2223 case MONO_TYPE_ARRAY:
2224 printf ("complex] (%s [%d %d %d])",
2225 value->type->data.array->eklass->name,
2226 value->type->data.array->rank,
2227 value->type->data.array->numsizes,
2228 value->type->data.array->numlobounds);
2229 return;
2230 case MONO_TYPE_GENERICINST:
2231 printf ("complex] (inst of %s )", value->type->data.generic_class->container_class->name);
2232 return;
2233 case MONO_TYPE_VAR:
2234 printf ("complex] (type generic param !%d - %s) ", value->type->data.generic_param->num, mono_generic_param_info (value->type->data.generic_param)->name);
2235 return;
2236 case MONO_TYPE_MVAR:
2237 printf ("complex] (method generic param !!%d - %s) ", value->type->data.generic_param->num, mono_generic_param_info (value->type->data.generic_param)->name);
2238 return;
2239 default: {
2240 //should be a boxed value
2241 char * name = mono_type_full_name (value->type);
2242 printf ("complex] %s", name);
2243 g_free (name);
2244 return;
2247 default:
2248 printf ("unknown stack %x type]\n", value->stype);
2249 g_assert_not_reached ();
2253 static void
2254 dump_stack_state (ILCodeDesc *state)
2256 int i;
2258 printf ("(%d) ", state->size);
2259 for (i = 0; i < state->size; ++i)
2260 dump_stack_value (state->stack + i);
2261 printf ("\n");
2263 #endif
2265 /*Returns TRUE if candidate array type can be assigned to target.
2266 *Both parameters MUST be of type MONO_TYPE_ARRAY (target->type == MONO_TYPE_ARRAY)
2268 static gboolean
2269 is_array_type_compatible (MonoType *target, MonoType *candidate)
2271 MonoArrayType *left = target->data.array;
2272 MonoArrayType *right = candidate->data.array;
2274 g_assert (target->type == MONO_TYPE_ARRAY);
2275 g_assert (candidate->type == MONO_TYPE_ARRAY);
2277 if (left->rank != right->rank)
2278 return FALSE;
2280 return mono_class_is_assignable_from (left->eklass, right->eklass);
2283 static int
2284 get_stack_type (MonoType *type)
2286 int mask = 0;
2287 int type_kind = type->type;
2288 if (type->byref)
2289 mask = POINTER_MASK;
2290 /*TODO handle CMMP_MASK */
2292 handle_enum:
2293 switch (type_kind) {
2294 case MONO_TYPE_I1:
2295 case MONO_TYPE_U1:
2296 case MONO_TYPE_BOOLEAN:
2297 case MONO_TYPE_I2:
2298 case MONO_TYPE_U2:
2299 case MONO_TYPE_CHAR:
2300 case MONO_TYPE_I4:
2301 case MONO_TYPE_U4:
2302 return TYPE_I4 | mask;
2304 case MONO_TYPE_I:
2305 case MONO_TYPE_U:
2306 return TYPE_NATIVE_INT | mask;
2308 /* FIXME: the spec says that you cannot have a pointer to method pointer, do we need to check this here? */
2309 case MONO_TYPE_FNPTR:
2310 case MONO_TYPE_PTR:
2311 case MONO_TYPE_TYPEDBYREF:
2312 return TYPE_PTR | mask;
2314 case MONO_TYPE_VAR:
2315 case MONO_TYPE_MVAR:
2317 case MONO_TYPE_CLASS:
2318 case MONO_TYPE_STRING:
2319 case MONO_TYPE_OBJECT:
2320 case MONO_TYPE_SZARRAY:
2321 case MONO_TYPE_ARRAY:
2322 return TYPE_COMPLEX | mask;
2324 case MONO_TYPE_GENERICINST:
2325 if (mono_type_is_enum_type (type)) {
2326 type = mono_type_get_underlying_type_any (type);
2327 type_kind = type->type;
2328 goto handle_enum;
2329 } else {
2330 return TYPE_COMPLEX | mask;
2333 case MONO_TYPE_I8:
2334 case MONO_TYPE_U8:
2335 return TYPE_I8 | mask;
2337 case MONO_TYPE_R4:
2338 case MONO_TYPE_R8:
2339 return TYPE_R8 | mask;
2341 case MONO_TYPE_VALUETYPE:
2342 if (mono_type_is_enum_type (type)) {
2343 type = mono_type_get_underlying_type_any (type);
2344 type_kind = type->type;
2345 goto handle_enum;
2346 } else {
2347 return TYPE_COMPLEX | mask;
2350 default:
2351 VERIFIER_DEBUG ( printf ("unknown type %02x in eval stack type\n", type->type); );
2352 g_assert_not_reached ();
2353 return 0;
2357 /* convert MonoType to ILStackDesc format (stype) */
2358 static gboolean
2359 set_stack_value (VerifyContext *ctx, ILStackDesc *stack, MonoType *type, int take_addr)
2361 int mask = 0;
2362 int type_kind = type->type;
2364 if (type->byref || take_addr)
2365 mask = POINTER_MASK;
2366 /* TODO handle CMMP_MASK */
2368 handle_enum:
2369 stack->type = type;
2371 switch (type_kind) {
2372 case MONO_TYPE_I1:
2373 case MONO_TYPE_U1:
2374 case MONO_TYPE_BOOLEAN:
2375 case MONO_TYPE_I2:
2376 case MONO_TYPE_U2:
2377 case MONO_TYPE_CHAR:
2378 case MONO_TYPE_I4:
2379 case MONO_TYPE_U4:
2380 stack->stype = TYPE_I4 | mask;
2381 break;
2382 case MONO_TYPE_I:
2383 case MONO_TYPE_U:
2384 stack->stype = TYPE_NATIVE_INT | mask;
2385 break;
2387 /*FIXME: Do we need to check if it's a pointer to the method pointer? The spec says it' illegal to have that.*/
2388 case MONO_TYPE_FNPTR:
2389 case MONO_TYPE_PTR:
2390 case MONO_TYPE_TYPEDBYREF:
2391 stack->stype = TYPE_PTR | mask;
2392 break;
2394 case MONO_TYPE_CLASS:
2395 case MONO_TYPE_STRING:
2396 case MONO_TYPE_OBJECT:
2397 case MONO_TYPE_SZARRAY:
2398 case MONO_TYPE_ARRAY:
2400 case MONO_TYPE_VAR:
2401 case MONO_TYPE_MVAR:
2402 stack->stype = TYPE_COMPLEX | mask;
2403 break;
2405 case MONO_TYPE_GENERICINST:
2406 if (mono_type_is_enum_type (type)) {
2407 type = mono_type_get_underlying_type_any (type);
2408 type_kind = type->type;
2409 goto handle_enum;
2410 } else {
2411 stack->stype = TYPE_COMPLEX | mask;
2412 break;
2415 case MONO_TYPE_I8:
2416 case MONO_TYPE_U8:
2417 stack->stype = TYPE_I8 | mask;
2418 break;
2419 case MONO_TYPE_R4:
2420 case MONO_TYPE_R8:
2421 stack->stype = TYPE_R8 | mask;
2422 break;
2423 case MONO_TYPE_VALUETYPE:
2424 if (mono_type_is_enum_type (type)) {
2425 type = mono_type_get_underlying_type_any (type);
2426 type_kind = type->type;
2427 goto handle_enum;
2428 } else {
2429 stack->stype = TYPE_COMPLEX | mask;
2430 break;
2432 default:
2433 VERIFIER_DEBUG ( printf ("unknown type 0x%02x in eval stack type\n", type->type); );
2434 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Illegal value set on stack 0x%02x at %d", type->type, ctx->ip_offset));
2435 return FALSE;
2437 return TRUE;
2441 * init_stack_with_value_at_exception_boundary:
2443 * Initialize the stack and push a given type.
2444 * The instruction is marked as been on the exception boundary.
2446 static void
2447 init_stack_with_value_at_exception_boundary (VerifyContext *ctx, ILCodeDesc *code, MonoClass *klass)
2449 MonoType *type = mono_class_inflate_generic_type (&klass->byval_arg, ctx->generic_context);
2450 stack_init (ctx, code);
2451 set_stack_value (ctx, code->stack, type, FALSE);
2452 ctx->exception_types = g_slist_prepend (ctx->exception_types, type);
2453 code->size = 1;
2454 code->flags |= IL_CODE_FLAG_WAS_TARGET;
2455 if (mono_type_is_generic_argument (type))
2456 code->stack->stype |= BOXED_MASK;
2459 /*Verify if type 'candidate' can be stored in type 'target'.
2461 * If strict, check for the underlying type and not the verification stack types
2463 static gboolean
2464 verify_type_compatibility_full (VerifyContext *ctx, MonoType *target, MonoType *candidate, gboolean strict)
2466 #define IS_ONE_OF3(T, A, B, C) (T == A || T == B || T == C)
2467 #define IS_ONE_OF2(T, A, B) (T == A || T == B)
2469 MonoType *original_candidate = candidate;
2470 VERIFIER_DEBUG ( printf ("checking type compatibility %s x %s strict %d\n", mono_type_full_name (target), mono_type_full_name (candidate), strict); );
2472 /*only one is byref */
2473 if (candidate->byref ^ target->byref) {
2474 /* converting from native int to byref*/
2475 if (get_stack_type (candidate) == TYPE_NATIVE_INT && target->byref) {
2476 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("using byref native int at 0x%04x", ctx->ip_offset));
2477 return TRUE;
2479 return FALSE;
2481 strict |= target->byref;
2482 /*From now on we don't care about byref anymore, so it's ok to discard it here*/
2483 candidate = mono_type_get_underlying_type_any (candidate);
2485 handle_enum:
2486 switch (target->type) {
2487 case MONO_TYPE_VOID:
2488 return candidate->type == MONO_TYPE_VOID;
2489 case MONO_TYPE_I1:
2490 case MONO_TYPE_U1:
2491 case MONO_TYPE_BOOLEAN:
2492 if (strict)
2493 return IS_ONE_OF3 (candidate->type, MONO_TYPE_I1, MONO_TYPE_U1, MONO_TYPE_BOOLEAN);
2494 case MONO_TYPE_I2:
2495 case MONO_TYPE_U2:
2496 case MONO_TYPE_CHAR:
2497 if (strict)
2498 return IS_ONE_OF3 (candidate->type, MONO_TYPE_I2, MONO_TYPE_U2, MONO_TYPE_CHAR);
2499 case MONO_TYPE_I4:
2500 case MONO_TYPE_U4: {
2501 gboolean is_native_int = IS_ONE_OF2 (candidate->type, MONO_TYPE_I, MONO_TYPE_U);
2502 gboolean is_int4 = IS_ONE_OF2 (candidate->type, MONO_TYPE_I4, MONO_TYPE_U4);
2503 if (strict)
2504 return is_native_int || is_int4;
2505 return is_native_int || get_stack_type (candidate) == TYPE_I4;
2508 case MONO_TYPE_I8:
2509 case MONO_TYPE_U8:
2510 return IS_ONE_OF2 (candidate->type, MONO_TYPE_I8, MONO_TYPE_U8);
2512 case MONO_TYPE_R4:
2513 case MONO_TYPE_R8:
2514 if (strict)
2515 return candidate->type == target->type;
2516 return IS_ONE_OF2 (candidate->type, MONO_TYPE_R4, MONO_TYPE_R8);
2518 case MONO_TYPE_I:
2519 case MONO_TYPE_U: {
2520 gboolean is_native_int = IS_ONE_OF2 (candidate->type, MONO_TYPE_I, MONO_TYPE_U);
2521 gboolean is_int4 = IS_ONE_OF2 (candidate->type, MONO_TYPE_I4, MONO_TYPE_U4);
2522 if (strict)
2523 return is_native_int || is_int4;
2524 return is_native_int || get_stack_type (candidate) == TYPE_I4;
2527 case MONO_TYPE_PTR:
2528 if (candidate->type != MONO_TYPE_PTR)
2529 return FALSE;
2530 /* check the underlying type */
2531 return verify_type_compatibility_full (ctx, target->data.type, candidate->data.type, TRUE);
2533 case MONO_TYPE_FNPTR: {
2534 MonoMethodSignature *left, *right;
2535 if (candidate->type != MONO_TYPE_FNPTR)
2536 return FALSE;
2538 left = mono_type_get_signature (target);
2539 right = mono_type_get_signature (candidate);
2540 return mono_metadata_signature_equal (left, right) && left->call_convention == right->call_convention;
2543 case MONO_TYPE_GENERICINST: {
2544 MonoClass *target_klass;
2545 MonoClass *candidate_klass;
2546 if (mono_type_is_enum_type (target)) {
2547 target = mono_type_get_underlying_type_any (target);
2548 goto handle_enum;
2550 target_klass = mono_class_from_mono_type (target);
2551 candidate_klass = mono_class_from_mono_type (candidate);
2552 if (mono_class_is_nullable (target_klass)) {
2553 if (!mono_class_is_nullable (candidate_klass))
2554 return FALSE;
2555 return target_klass == candidate_klass;
2558 return mono_class_is_assignable_from (target_klass, candidate_klass);
2561 case MONO_TYPE_STRING:
2562 return candidate->type == MONO_TYPE_STRING;
2564 case MONO_TYPE_CLASS:
2566 * VAR / MVAR compatibility must be checked by verify_stack_type_compatibility
2567 * to take boxing status into account.
2569 if (mono_type_is_generic_argument (original_candidate))
2570 return FALSE;
2571 /* If candidate is an enum it should return true for System.Enum and supertypes.
2572 * That's why here we use the original type and not the underlying type.
2574 return mono_class_is_assignable_from (target->data.klass, mono_class_from_mono_type (original_candidate));
2576 case MONO_TYPE_OBJECT:
2577 return MONO_TYPE_IS_REFERENCE (candidate);
2579 case MONO_TYPE_SZARRAY: {
2580 MonoClass *left;
2581 MonoClass *right;
2582 if (candidate->type != MONO_TYPE_SZARRAY)
2583 return FALSE;
2585 left = mono_class_from_mono_type (target)->element_class;
2586 right = mono_class_from_mono_type (candidate)->element_class;
2587 return mono_class_is_assignable_from (left, right);
2590 case MONO_TYPE_ARRAY:
2591 if (candidate->type != MONO_TYPE_ARRAY)
2592 return FALSE;
2593 return is_array_type_compatible (target, candidate);
2595 case MONO_TYPE_TYPEDBYREF:
2596 return candidate->type == MONO_TYPE_TYPEDBYREF;
2598 case MONO_TYPE_VALUETYPE: {
2599 MonoClass *target_klass = mono_class_from_mono_type (target);
2600 MonoClass *candidate_klass = mono_class_from_mono_type (candidate);
2602 if (target_klass == candidate_klass)
2603 return TRUE;
2604 if (mono_type_is_enum_type (target)) {
2605 target = mono_type_get_underlying_type_any (target);
2606 goto handle_enum;
2608 return FALSE;
2611 case MONO_TYPE_VAR:
2612 if (candidate->type != MONO_TYPE_VAR)
2613 return FALSE;
2614 return mono_type_get_generic_param_num (candidate) == mono_type_get_generic_param_num (target);
2616 case MONO_TYPE_MVAR:
2617 if (candidate->type != MONO_TYPE_MVAR)
2618 return FALSE;
2619 return mono_type_get_generic_param_num (candidate) == mono_type_get_generic_param_num (target);
2621 default:
2622 VERIFIER_DEBUG ( printf ("unknown store type %d\n", target->type); );
2623 g_assert_not_reached ();
2624 return FALSE;
2626 return 1;
2627 #undef IS_ONE_OF3
2628 #undef IS_ONE_OF2
2631 static gboolean
2632 verify_type_compatibility (VerifyContext *ctx, MonoType *target, MonoType *candidate)
2634 return verify_type_compatibility_full (ctx, target, candidate, FALSE);
2638 * Returns the generic param bound to the context been verified.
2641 static MonoGenericParam*
2642 get_generic_param (VerifyContext *ctx, MonoType *param)
2644 guint16 param_num = mono_type_get_generic_param_num (param);
2645 if (param->type == MONO_TYPE_VAR) {
2646 if (!ctx->generic_context->class_inst || ctx->generic_context->class_inst->type_argc <= param_num) {
2647 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid generic type argument %d", param_num));
2648 return NULL;
2650 return ctx->generic_context->class_inst->type_argv [param_num]->data.generic_param;
2653 /*param must be a MVAR */
2654 if (!ctx->generic_context->method_inst || ctx->generic_context->method_inst->type_argc <= param_num) {
2655 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid generic method argument %d", param_num));
2656 return NULL;
2658 return ctx->generic_context->method_inst->type_argv [param_num]->data.generic_param;
2662 * is_compatible_boxed_valuetype:
2664 * Returns TRUE if @candidate / @stack is a valid boxed valuetype.
2666 * @type The source type. It it tested to be of the proper type.
2667 * @candidate type of the boxed valuetype.
2668 * @stack stack slot of the boxed valuetype, separate from @candidade since one could be changed before calling this function
2669 * @strict if TRUE candidate must be boxed compatible to the target type
2672 static gboolean
2673 is_compatible_boxed_valuetype (VerifyContext *ctx, MonoType *type, MonoType *candidate, ILStackDesc *stack, gboolean strict)
2675 if (!stack_slot_is_boxed_value (stack))
2676 return FALSE;
2677 if (type->byref || candidate->byref)
2678 return FALSE;
2680 if (mono_type_is_generic_argument (candidate)) {
2681 MonoGenericParam *param = get_generic_param (ctx, candidate);
2682 MonoClass **class;
2683 for (class = mono_generic_param_info (param)->constraints; class && *class; ++class) {
2684 if (verify_type_compatibility_full (ctx, type, mono_type_get_type_byval (& (*class)->byval_arg), FALSE))
2685 return TRUE;
2689 if (mono_type_is_generic_argument (type))
2690 return FALSE;
2692 if (!strict)
2693 return TRUE;
2695 return MONO_TYPE_IS_REFERENCE (type) && mono_class_is_assignable_from (mono_class_from_mono_type (type), mono_class_from_mono_type (candidate));
2698 static int
2699 verify_stack_type_compatibility_full (VerifyContext *ctx, MonoType *type, ILStackDesc *stack, gboolean drop_byref, gboolean valuetype_must_be_boxed)
2701 MonoType *candidate = mono_type_from_stack_slot (stack);
2702 if (MONO_TYPE_IS_REFERENCE (type) && !type->byref && stack_slot_is_null_literal (stack))
2703 return TRUE;
2705 if (is_compatible_boxed_valuetype (ctx, type, candidate, stack, TRUE))
2706 return TRUE;
2708 if (valuetype_must_be_boxed && !stack_slot_is_boxed_value (stack) && !MONO_TYPE_IS_REFERENCE (candidate))
2709 return FALSE;
2711 if (!valuetype_must_be_boxed && stack_slot_is_boxed_value (stack))
2712 return FALSE;
2714 if (drop_byref)
2715 return verify_type_compatibility_full (ctx, type, mono_type_get_type_byval (candidate), FALSE);
2717 return verify_type_compatibility_full (ctx, type, candidate, FALSE);
2720 static int
2721 verify_stack_type_compatibility (VerifyContext *ctx, MonoType *type, ILStackDesc *stack)
2723 return verify_stack_type_compatibility_full (ctx, type, stack, FALSE, FALSE);
2726 static gboolean
2727 mono_delegate_type_equal (MonoType *target, MonoType *candidate)
2729 if (candidate->byref ^ target->byref)
2730 return FALSE;
2732 switch (target->type) {
2733 case MONO_TYPE_VOID:
2734 case MONO_TYPE_I1:
2735 case MONO_TYPE_U1:
2736 case MONO_TYPE_BOOLEAN:
2737 case MONO_TYPE_I2:
2738 case MONO_TYPE_U2:
2739 case MONO_TYPE_CHAR:
2740 case MONO_TYPE_I4:
2741 case MONO_TYPE_U4:
2742 case MONO_TYPE_I8:
2743 case MONO_TYPE_U8:
2744 case MONO_TYPE_R4:
2745 case MONO_TYPE_R8:
2746 case MONO_TYPE_I:
2747 case MONO_TYPE_U:
2748 case MONO_TYPE_STRING:
2749 case MONO_TYPE_TYPEDBYREF:
2750 return candidate->type == target->type;
2752 case MONO_TYPE_PTR:
2753 return mono_delegate_type_equal (target->data.type, candidate->data.type);
2755 case MONO_TYPE_FNPTR:
2756 if (candidate->type != MONO_TYPE_FNPTR)
2757 return FALSE;
2758 return mono_delegate_signature_equal (mono_type_get_signature (target), mono_type_get_signature (candidate), FALSE);
2760 case MONO_TYPE_GENERICINST: {
2761 MonoClass *target_klass;
2762 MonoClass *candidate_klass;
2763 target_klass = mono_class_from_mono_type (target);
2764 candidate_klass = mono_class_from_mono_type (candidate);
2765 /*FIXME handle nullables and enum*/
2766 return mono_class_is_assignable_from (target_klass, candidate_klass);
2768 case MONO_TYPE_OBJECT:
2769 return MONO_TYPE_IS_REFERENCE (candidate);
2771 case MONO_TYPE_CLASS:
2772 return mono_class_is_assignable_from(target->data.klass, mono_class_from_mono_type (candidate));
2774 case MONO_TYPE_SZARRAY:
2775 if (candidate->type != MONO_TYPE_SZARRAY)
2776 return FALSE;
2777 return mono_class_is_assignable_from (mono_class_from_mono_type (target)->element_class, mono_class_from_mono_type (candidate)->element_class);
2779 case MONO_TYPE_ARRAY:
2780 if (candidate->type != MONO_TYPE_ARRAY)
2781 return FALSE;
2782 return is_array_type_compatible (target, candidate);
2784 case MONO_TYPE_VALUETYPE:
2785 /*FIXME handle nullables and enum*/
2786 return mono_class_from_mono_type (candidate) == mono_class_from_mono_type (target);
2788 case MONO_TYPE_VAR:
2789 return candidate->type == MONO_TYPE_VAR && mono_type_get_generic_param_num (target) == mono_type_get_generic_param_num (candidate);
2790 return FALSE;
2792 case MONO_TYPE_MVAR:
2793 return candidate->type == MONO_TYPE_MVAR && mono_type_get_generic_param_num (target) == mono_type_get_generic_param_num (candidate);
2794 return FALSE;
2796 default:
2797 VERIFIER_DEBUG ( printf ("Unknown type %d. Implement me!\n", target->type); );
2798 g_assert_not_reached ();
2799 return FALSE;
2803 static gboolean
2804 mono_delegate_param_equal (MonoType *delegate, MonoType *method)
2806 if (mono_metadata_type_equal_full (delegate, method, TRUE))
2807 return TRUE;
2809 return mono_delegate_type_equal (method, delegate);
2812 static gboolean
2813 mono_delegate_ret_equal (MonoType *delegate, MonoType *method)
2815 if (mono_metadata_type_equal_full (delegate, method, TRUE))
2816 return TRUE;
2818 return mono_delegate_type_equal (delegate, method);
2822 * mono_delegate_signature_equal:
2824 * Compare two signatures in the way expected by delegates.
2826 * This function only exists due to the fact that it should ignore the 'has_this' part of the signature.
2828 * FIXME can this function be eliminated and proper metadata functionality be used?
2830 static gboolean
2831 mono_delegate_signature_equal (MonoMethodSignature *delegate_sig, MonoMethodSignature *method_sig, gboolean is_static_ldftn)
2833 int i;
2834 int method_offset = is_static_ldftn ? 1 : 0;
2836 if (delegate_sig->param_count + method_offset != method_sig->param_count)
2837 return FALSE;
2839 if (delegate_sig->call_convention != method_sig->call_convention)
2840 return FALSE;
2842 for (i = 0; i < delegate_sig->param_count; i++) {
2843 MonoType *p1 = delegate_sig->params [i];
2844 MonoType *p2 = method_sig->params [i + method_offset];
2846 if (!mono_delegate_param_equal (p1, p2))
2847 return FALSE;
2850 if (!mono_delegate_ret_equal (delegate_sig->ret, method_sig->ret))
2851 return FALSE;
2853 return TRUE;
2857 * verify_ldftn_delegate:
2859 * Verify properties of ldftn based delegates.
2861 static void
2862 verify_ldftn_delegate (VerifyContext *ctx, MonoClass *delegate, ILStackDesc *value, ILStackDesc *funptr)
2864 MonoMethod *method = funptr->method;
2866 /*ldftn non-final virtuals only allowed if method is not static,
2867 * the object is a this arg (comes from a ldarg.0), and there is no starg.0.
2868 * This rules doesn't apply if the object on stack is a boxed valuetype.
2870 if ((method->flags & METHOD_ATTRIBUTE_VIRTUAL) && !(method->flags & METHOD_ATTRIBUTE_FINAL) && !(method->klass->flags & TYPE_ATTRIBUTE_SEALED) && !stack_slot_is_boxed_value (value)) {
2871 /*A stdarg 0 must not happen, we fail here only in fail fast mode to avoid double error reports*/
2872 if (IS_FAIL_FAST_MODE (ctx) && ctx->has_this_store)
2873 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid ldftn with virtual function in method with stdarg 0 at 0x%04x", ctx->ip_offset));
2875 /*current method must not be static*/
2876 if (ctx->method->flags & METHOD_ATTRIBUTE_STATIC)
2877 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid ldftn with virtual function at 0x%04x", ctx->ip_offset));
2879 /*value is the this pointer, loaded using ldarg.0 */
2880 if (!stack_slot_is_this_pointer (value))
2881 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));
2883 ctx->code [ctx->ip_offset].flags |= IL_CODE_LDFTN_DELEGATE_NONFINAL_VIRTUAL;
2888 * verify_delegate_compatibility:
2890 * Verify delegate creation sequence.
2893 static void
2894 verify_delegate_compatibility (VerifyContext *ctx, MonoClass *delegate, ILStackDesc *value, ILStackDesc *funptr)
2896 #define IS_VALID_OPCODE(offset, opcode) (ip [ip_offset - offset] == opcode && (ctx->code [ip_offset - offset].flags & IL_CODE_FLAG_SEEN))
2897 #define IS_LOAD_FUN_PTR(kind) (IS_VALID_OPCODE (6, CEE_PREFIX1) && ip [ip_offset - 5] == kind)
2899 MonoMethod *invoke, *method;
2900 const guint8 *ip = ctx->header->code;
2901 guint32 ip_offset = ctx->ip_offset;
2902 gboolean is_static_ldftn = FALSE, is_first_arg_bound = FALSE;
2904 if (stack_slot_get_type (funptr) != TYPE_PTR || !funptr->method) {
2905 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid function pointer parameter for delegate constructor at 0x%04x", ctx->ip_offset));
2906 return;
2909 invoke = mono_get_delegate_invoke (delegate);
2910 method = funptr->method;
2912 is_static_ldftn = (ip_offset > 5 && IS_LOAD_FUN_PTR (CEE_LDFTN)) && method->flags & METHOD_ATTRIBUTE_STATIC;
2914 if (is_static_ldftn)
2915 is_first_arg_bound = mono_method_signature (invoke)->param_count + 1 == mono_method_signature (method)->param_count;
2917 if (!mono_delegate_signature_equal (mono_method_signature (invoke), mono_method_signature (method), is_first_arg_bound)) {
2918 char *fun_sig = mono_signature_get_desc (mono_method_signature (method), FALSE);
2919 char *invoke_sig = mono_signature_get_desc (mono_method_signature (invoke), FALSE);
2920 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));
2921 g_free (fun_sig);
2922 g_free (invoke_sig);
2926 * Delegate code sequences:
2927 * [-6] ldftn token
2928 * newobj ...
2931 * [-7] dup
2932 * [-6] ldvirtftn token
2933 * newobj ...
2935 * ldftn sequence:*/
2936 if (ip_offset > 5 && IS_LOAD_FUN_PTR (CEE_LDFTN)) {
2937 verify_ldftn_delegate (ctx, delegate, value, funptr);
2938 } else if (ip_offset > 6 && IS_VALID_OPCODE (7, CEE_DUP) && IS_LOAD_FUN_PTR (CEE_LDVIRTFTN)) {
2939 ctx->code [ip_offset - 6].flags |= IL_CODE_DELEGATE_SEQUENCE;
2940 }else {
2941 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid code sequence for delegate creation at 0x%04x", ctx->ip_offset));
2943 ctx->code [ip_offset].flags |= IL_CODE_DELEGATE_SEQUENCE;
2945 //general tests
2946 if (is_first_arg_bound) {
2947 if (!verify_stack_type_compatibility_full (ctx, mono_method_signature (method)->params [0], value, FALSE, TRUE))
2948 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("This object not compatible with function pointer for delegate creation at 0x%04x", ctx->ip_offset));
2949 } else {
2950 if (!verify_stack_type_compatibility_full (ctx, &method->klass->byval_arg, value, FALSE, TRUE) && !stack_slot_is_null_literal (value))
2951 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("This object not compatible with function pointer for delegate creation at 0x%04x", ctx->ip_offset));
2954 if (stack_slot_get_type (value) != TYPE_COMPLEX)
2955 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid first parameter for delegate creation at 0x%04x", ctx->ip_offset));
2957 #undef IS_VALID_OPCODE
2958 #undef IS_LOAD_FUN_PTR
2961 /* implement the opcode checks*/
2962 static void
2963 push_arg (VerifyContext *ctx, unsigned int arg, int take_addr)
2965 ILStackDesc *top;
2967 if (arg >= ctx->max_args) {
2968 if (take_addr)
2969 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Method doesn't have argument %d", arg + 1));
2970 else {
2971 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Method doesn't have argument %d", arg + 1));
2972 if (check_overflow (ctx)) //FIXME: what sane value could we ever push?
2973 stack_push_val (ctx, TYPE_I4, &mono_defaults.int32_class->byval_arg);
2975 } else if (check_overflow (ctx)) {
2976 /*We must let the value be pushed, otherwise we would get an underflow error*/
2977 check_unverifiable_type (ctx, ctx->params [arg]);
2978 if (ctx->params [arg]->byref && take_addr)
2979 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("ByRef of ByRef at 0x%04x", ctx->ip_offset));
2980 top = stack_push (ctx);
2981 if (!set_stack_value (ctx, top, ctx->params [arg], take_addr))
2982 return;
2984 if (arg == 0 && !(ctx->method->flags & METHOD_ATTRIBUTE_STATIC)) {
2985 if (take_addr)
2986 ctx->has_this_store = TRUE;
2987 else
2988 top->stype |= THIS_POINTER_MASK;
2989 if (mono_method_is_constructor (ctx->method) && !ctx->super_ctor_called && !ctx->method->klass->valuetype)
2990 top->stype |= UNINIT_THIS_MASK;
2995 static void
2996 push_local (VerifyContext *ctx, guint32 arg, int take_addr)
2998 if (arg >= ctx->num_locals) {
2999 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Method doesn't have local %d", arg + 1));
3000 } else if (check_overflow (ctx)) {
3001 /*We must let the value be pushed, otherwise we would get an underflow error*/
3002 check_unverifiable_type (ctx, ctx->locals [arg]);
3003 if (ctx->locals [arg]->byref && take_addr)
3004 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("ByRef of ByRef at 0x%04x", ctx->ip_offset));
3006 set_stack_value (ctx, stack_push (ctx), ctx->locals [arg], take_addr);
3010 static void
3011 store_arg (VerifyContext *ctx, guint32 arg)
3013 ILStackDesc *value;
3015 if (arg >= ctx->max_args) {
3016 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Method doesn't have argument %d at 0x%04x", arg + 1, ctx->ip_offset));
3017 if (check_underflow (ctx, 1))
3018 stack_pop (ctx);
3019 return;
3022 if (check_underflow (ctx, 1)) {
3023 value = stack_pop (ctx);
3024 if (!verify_stack_type_compatibility (ctx, ctx->params [arg], value)) {
3025 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Incompatible type %s in argument store at 0x%04x", stack_slot_get_name (value), ctx->ip_offset));
3028 if (arg == 0 && !(ctx->method->flags & METHOD_ATTRIBUTE_STATIC))
3029 ctx->has_this_store = 1;
3032 static void
3033 store_local (VerifyContext *ctx, guint32 arg)
3035 ILStackDesc *value;
3036 if (arg >= ctx->num_locals) {
3037 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Method doesn't have local var %d at 0x%04x", arg + 1, ctx->ip_offset));
3038 return;
3041 /*TODO verify definite assigment */
3042 if (check_underflow (ctx, 1)) {
3043 value = stack_pop(ctx);
3044 if (!verify_stack_type_compatibility (ctx, ctx->locals [arg], value)) {
3045 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Incompatible type [%s], type [%s] was expected in local store at 0x%04x",
3046 stack_slot_get_name (value),
3047 mono_type_get_stack_name (ctx->locals [arg]),
3048 ctx->ip_offset));
3053 /*FIXME add and sub needs special care here*/
3054 static void
3055 do_binop (VerifyContext *ctx, unsigned int opcode, const unsigned char table [TYPE_MAX][TYPE_MAX])
3057 ILStackDesc *a, *b, *top;
3058 int idxa, idxb, complexMerge = 0;
3059 unsigned char res;
3061 if (!check_underflow (ctx, 2))
3062 return;
3063 b = stack_pop (ctx);
3064 a = stack_pop (ctx);
3066 idxa = stack_slot_get_underlying_type (a);
3067 if (stack_slot_is_managed_pointer (a)) {
3068 idxa = TYPE_PTR;
3069 complexMerge = 1;
3072 idxb = stack_slot_get_underlying_type (b);
3073 if (stack_slot_is_managed_pointer (b)) {
3074 idxb = TYPE_PTR;
3075 complexMerge = 2;
3078 --idxa;
3079 --idxb;
3080 res = table [idxa][idxb];
3082 VERIFIER_DEBUG ( printf ("binop res %d\n", res); );
3083 VERIFIER_DEBUG ( printf ("idxa %d idxb %d\n", idxa, idxb); );
3085 top = stack_push (ctx);
3086 if (res == TYPE_INV) {
3087 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)));
3088 copy_stack_value (top, a);
3089 return;
3092 if (res & NON_VERIFIABLE_RESULT) {
3093 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)));
3095 res = res & ~NON_VERIFIABLE_RESULT;
3098 if (complexMerge && res == TYPE_PTR) {
3099 if (complexMerge == 1)
3100 copy_stack_value (top, a);
3101 else if (complexMerge == 2)
3102 copy_stack_value (top, b);
3104 * There is no need to merge the type of two pointers.
3105 * The only valid operation is subtraction, that returns a native
3106 * int as result and can be used with any 2 pointer kinds.
3107 * This is valid acording to Patition III 1.1.4
3109 } else
3110 top->stype = res;
3115 static void
3116 do_boolean_branch_op (VerifyContext *ctx, int delta)
3118 int target = ctx->ip_offset + delta;
3119 ILStackDesc *top;
3121 VERIFIER_DEBUG ( printf ("boolean branch offset %d delta %d target %d\n", ctx->ip_offset, delta, target); );
3123 if (target < 0 || target >= ctx->code_size) {
3124 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Boolean branch target out of code at 0x%04x", ctx->ip_offset));
3125 return;
3128 switch (is_valid_branch_instruction (ctx->header, ctx->ip_offset, target)) {
3129 case 1:
3130 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Branch target escapes out of exception block at 0x%04x", ctx->ip_offset));
3131 break;
3132 case 2:
3133 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Branch target escapes out of exception block at 0x%04x", ctx->ip_offset));
3134 return;
3137 ctx->target = target;
3139 if (!check_underflow (ctx, 1))
3140 return;
3142 top = stack_pop (ctx);
3143 if (!is_valid_bool_arg (top))
3144 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));
3146 check_unmanaged_pointer (ctx, top);
3149 static gboolean
3150 stack_slot_is_complex_type_not_reference_type (ILStackDesc *slot)
3152 return stack_slot_get_type (slot) == TYPE_COMPLEX && !MONO_TYPE_IS_REFERENCE (slot->type) && !stack_slot_is_boxed_value (slot);
3155 static void
3156 do_branch_op (VerifyContext *ctx, signed int delta, const unsigned char table [TYPE_MAX][TYPE_MAX])
3158 ILStackDesc *a, *b;
3159 int idxa, idxb;
3160 unsigned char res;
3161 int target = ctx->ip_offset + delta;
3163 VERIFIER_DEBUG ( printf ("branch offset %d delta %d target %d\n", ctx->ip_offset, delta, target); );
3165 if (target < 0 || target >= ctx->code_size) {
3166 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Branch target out of code at 0x%04x", ctx->ip_offset));
3167 return;
3170 switch (is_valid_cmp_branch_instruction (ctx->header, ctx->ip_offset, target)) {
3171 case 1: /*FIXME use constants and not magic numbers.*/
3172 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Branch target escapes out of exception block at 0x%04x", ctx->ip_offset));
3173 break;
3174 case 2:
3175 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Branch target escapes out of exception block at 0x%04x", ctx->ip_offset));
3176 return;
3179 ctx->target = target;
3181 if (!check_underflow (ctx, 2))
3182 return;
3184 b = stack_pop (ctx);
3185 a = stack_pop (ctx);
3187 idxa = stack_slot_get_underlying_type (a);
3188 if (stack_slot_is_managed_pointer (a))
3189 idxa = TYPE_PTR;
3191 idxb = stack_slot_get_underlying_type (b);
3192 if (stack_slot_is_managed_pointer (b))
3193 idxb = TYPE_PTR;
3195 if (stack_slot_is_complex_type_not_reference_type (a) || stack_slot_is_complex_type_not_reference_type (b)) {
3196 res = TYPE_INV;
3197 } else {
3198 --idxa;
3199 --idxb;
3200 res = table [idxa][idxb];
3203 VERIFIER_DEBUG ( printf ("branch res %d\n", res); );
3204 VERIFIER_DEBUG ( printf ("idxa %d idxb %d\n", idxa, idxb); );
3206 if (res == TYPE_INV) {
3207 CODE_NOT_VERIFIABLE (ctx,
3208 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));
3209 } else if (res & NON_VERIFIABLE_RESULT) {
3210 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));
3211 res = res & ~NON_VERIFIABLE_RESULT;
3215 static void
3216 do_cmp_op (VerifyContext *ctx, const unsigned char table [TYPE_MAX][TYPE_MAX], guint32 opcode)
3218 ILStackDesc *a, *b;
3219 int idxa, idxb;
3220 unsigned char res;
3222 if (!check_underflow (ctx, 2))
3223 return;
3224 b = stack_pop (ctx);
3225 a = stack_pop (ctx);
3227 if (opcode == CEE_CGT_UN) {
3228 if (stack_slot_get_type (a) == TYPE_COMPLEX && stack_slot_get_type (b) == TYPE_COMPLEX) {
3229 stack_push_val (ctx, TYPE_I4, &mono_defaults.int32_class->byval_arg);
3230 return;
3234 idxa = stack_slot_get_underlying_type (a);
3235 if (stack_slot_is_managed_pointer (a))
3236 idxa = TYPE_PTR;
3238 idxb = stack_slot_get_underlying_type (b);
3239 if (stack_slot_is_managed_pointer (b))
3240 idxb = TYPE_PTR;
3242 if (stack_slot_is_complex_type_not_reference_type (a) || stack_slot_is_complex_type_not_reference_type (b)) {
3243 res = TYPE_INV;
3244 } else {
3245 --idxa;
3246 --idxb;
3247 res = table [idxa][idxb];
3250 if(res == TYPE_INV) {
3251 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));
3252 } else if (res & NON_VERIFIABLE_RESULT) {
3253 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));
3254 res = res & ~NON_VERIFIABLE_RESULT;
3256 stack_push_val (ctx, TYPE_I4, &mono_defaults.int32_class->byval_arg);
3259 static void
3260 do_ret (VerifyContext *ctx)
3262 MonoType *ret = ctx->signature->ret;
3263 VERIFIER_DEBUG ( printf ("checking ret\n"); );
3264 if (ret->type != MONO_TYPE_VOID) {
3265 ILStackDesc *top;
3266 if (!check_underflow (ctx, 1))
3267 return;
3269 top = stack_pop(ctx);
3271 if (!verify_stack_type_compatibility (ctx, ctx->signature->ret, top)) {
3272 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Incompatible return value on stack with method signature ret at 0x%04x", ctx->ip_offset));
3273 return;
3276 if (ret->byref || ret->type == MONO_TYPE_TYPEDBYREF || mono_type_is_value_type (ret, "System", "ArgIterator") || mono_type_is_value_type (ret, "System", "RuntimeArgumentHandle"))
3277 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Method returns byref, TypedReference, ArgIterator or RuntimeArgumentHandle at 0x%04x", ctx->ip_offset));
3280 if (ctx->eval.size > 0) {
3281 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Stack not empty (%d) after ret at 0x%04x", ctx->eval.size, ctx->ip_offset));
3283 if (in_any_block (ctx->header, ctx->ip_offset))
3284 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("ret cannot escape exception blocks at 0x%04x", ctx->ip_offset));
3288 * 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.
3289 * This is illegal but mono_get_method_full decoded it.
3290 * TODO handle calling .ctor outside one or calling the .ctor for other class but super
3292 static void
3293 do_invoke_method (VerifyContext *ctx, int method_token, gboolean virtual)
3295 int param_count, i;
3296 MonoMethodSignature *sig;
3297 ILStackDesc *value;
3298 MonoMethod *method;
3299 gboolean virt_check_this = FALSE;
3300 gboolean constrained = ctx->prefix_set & PREFIX_CONSTRAINED;
3302 if (!(method = verifier_load_method (ctx, method_token, virtual ? "callvirt" : "call")))
3303 return;
3305 if (virtual) {
3306 CLEAR_PREFIX (ctx, PREFIX_CONSTRAINED);
3308 if (method->klass->valuetype) // && !constrained ???
3309 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use callvirtual with valuetype method at 0x%04x", ctx->ip_offset));
3311 if ((method->flags & METHOD_ATTRIBUTE_STATIC))
3312 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use callvirtual with static method at 0x%04x", ctx->ip_offset));
3314 } else {
3315 if (method->flags & METHOD_ATTRIBUTE_ABSTRACT)
3316 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use call with an abstract method at 0x%04x", ctx->ip_offset));
3318 if ((method->flags & METHOD_ATTRIBUTE_VIRTUAL) && !(method->flags & METHOD_ATTRIBUTE_FINAL)) {
3319 virt_check_this = TRUE;
3320 ctx->code [ctx->ip_offset].flags |= IL_CODE_CALL_NONFINAL_VIRTUAL;
3324 if (!(sig = mono_method_get_signature_full (method, ctx->image, method_token, ctx->generic_context)))
3325 sig = mono_method_get_signature (method, ctx->image, method_token);
3327 param_count = sig->param_count + sig->hasthis;
3328 if (!check_underflow (ctx, param_count))
3329 return;
3331 for (i = sig->param_count - 1; i >= 0; --i) {
3332 VERIFIER_DEBUG ( printf ("verifying argument %d\n", i); );
3333 value = stack_pop (ctx);
3334 if (!verify_stack_type_compatibility (ctx, sig->params[i], value)) {
3335 char *stack_name = stack_slot_full_name (value);
3336 char *sig_name = mono_type_full_name (sig->params [i]);
3337 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));
3338 g_free (stack_name);
3339 g_free (sig_name);
3342 if (stack_slot_is_managed_mutability_pointer (value))
3343 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));
3345 if ((ctx->prefix_set & PREFIX_TAIL) && stack_slot_is_managed_pointer (value)) {
3346 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));
3347 return;
3351 if (sig->hasthis) {
3352 MonoType *type = &method->klass->byval_arg;
3353 ILStackDesc copy;
3355 if (mono_method_is_constructor (method) && !method->klass->valuetype) {
3356 if (!mono_method_is_constructor (ctx->method))
3357 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot call a constructor outside one at 0x%04x", ctx->ip_offset));
3358 if (method->klass != ctx->method->klass->parent && method->klass != ctx->method->klass)
3359 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));
3361 ctx->super_ctor_called = TRUE;
3362 value = stack_pop_safe (ctx);
3363 if ((value->stype & THIS_POINTER_MASK) != THIS_POINTER_MASK)
3364 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid 'this ptr' argument for constructor at 0x%04x", ctx->ip_offset));
3365 } else {
3366 value = stack_pop (ctx);
3369 copy_stack_value (&copy, value);
3370 //TODO we should extract this to a 'drop_byref_argument' and use everywhere
3371 //Other parts of the code suffer from the same issue of
3372 copy.type = mono_type_get_type_byval (copy.type);
3373 copy.stype &= ~POINTER_MASK;
3375 if (virt_check_this && !stack_slot_is_this_pointer (value) && !(method->klass->valuetype || stack_slot_is_boxed_value (value)))
3376 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot call a non-final virtual method from an objet diferent thant the this pointer at 0x%04x", ctx->ip_offset));
3378 if (constrained && virtual) {
3379 if (!stack_slot_is_managed_pointer (value))
3380 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Object is not a managed pointer for a constrained call at 0x%04x", ctx->ip_offset));
3381 if (!mono_metadata_type_equal_full (mono_type_get_type_byval (value->type), ctx->constrained_type, TRUE))
3382 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Object not compatible with constrained type at 0x%04x", ctx->ip_offset));
3383 copy.stype |= BOXED_MASK;
3384 } else {
3385 if (stack_slot_is_managed_pointer (value) && !mono_class_from_mono_type (value->type)->valuetype)
3386 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));
3388 if (!virtual && mono_class_from_mono_type (value->type)->valuetype && !method->klass->valuetype && !stack_slot_is_boxed_value (value))
3389 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot call a valuetype baseclass at 0x%04x", ctx->ip_offset));
3391 if (virtual && mono_class_from_mono_type (value->type)->valuetype && !stack_slot_is_boxed_value (value))
3392 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use a valuetype with callvirt at 0x%04x", ctx->ip_offset));
3394 if (method->klass->valuetype && (stack_slot_is_boxed_value (value) || !stack_slot_is_managed_pointer (value)))
3395 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));
3397 if (!verify_stack_type_compatibility (ctx, type, &copy))
3398 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Incompatible this argument on stack with method signature at 0x%04x", ctx->ip_offset));
3400 if (!IS_SKIP_VISIBILITY (ctx) && !mono_method_can_access_method_full (ctx->method, method, mono_class_from_mono_type (value->type))) {
3401 char *name = mono_method_full_name (method, TRUE);
3402 CODE_NOT_VERIFIABLE2 (ctx, g_strdup_printf ("Method %s is not accessible at 0x%04x", name, ctx->ip_offset), MONO_EXCEPTION_METHOD_ACCESS);
3403 g_free (name);
3406 } else if (!IS_SKIP_VISIBILITY (ctx) && !mono_method_can_access_method_full (ctx->method, method, NULL)) {
3407 char *name = mono_method_full_name (method, TRUE);
3408 CODE_NOT_VERIFIABLE2 (ctx, g_strdup_printf ("Method %s is not accessible at 0x%04x", name, ctx->ip_offset), MONO_EXCEPTION_METHOD_ACCESS);
3409 g_free (name);
3412 if (sig->ret->type != MONO_TYPE_VOID) {
3413 if (check_overflow (ctx)) {
3414 value = stack_push (ctx);
3415 set_stack_value (ctx, value, sig->ret, FALSE);
3416 if ((ctx->prefix_set & PREFIX_READONLY) && method->klass->rank && !strcmp (method->name, "Address")) {
3417 ctx->prefix_set &= ~PREFIX_READONLY;
3418 value->stype |= CMMP_MASK;
3423 if ((ctx->prefix_set & PREFIX_TAIL)) {
3424 if (!mono_delegate_ret_equal (mono_method_signature (ctx->method)->ret, sig->ret))
3425 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Tail call with incompatible return type at 0x%04x", ctx->ip_offset));
3426 if (ctx->header->code [ctx->ip_offset + 5] != CEE_RET)
3427 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Tail call not followed by ret at 0x%04x", ctx->ip_offset));
3432 static void
3433 do_push_static_field (VerifyContext *ctx, int token, gboolean take_addr)
3435 MonoClassField *field;
3436 MonoClass *klass;
3437 if (!take_addr)
3438 CLEAR_PREFIX (ctx, PREFIX_VOLATILE);
3440 if (!(field = verifier_load_field (ctx, token, &klass, take_addr ? "ldsflda" : "ldsfld")))
3441 return;
3443 if (!(field->type->attrs & FIELD_ATTRIBUTE_STATIC)) {
3444 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Cannot load non static field at 0x%04x", ctx->ip_offset));
3445 return;
3447 /*taking the address of initonly field only works from the static constructor */
3448 if (take_addr && (field->type->attrs & FIELD_ATTRIBUTE_INIT_ONLY) &&
3449 !(field->parent == ctx->method->klass && (ctx->method->flags & (METHOD_ATTRIBUTE_SPECIAL_NAME | METHOD_ATTRIBUTE_STATIC)) && !strcmp (".cctor", ctx->method->name)))
3450 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot take the address of a init-only field at 0x%04x", ctx->ip_offset));
3452 if (!IS_SKIP_VISIBILITY (ctx) && !mono_method_can_access_field_full (ctx->method, field, NULL))
3453 CODE_NOT_VERIFIABLE2 (ctx, g_strdup_printf ("Type at stack is not accessible at 0x%04x", ctx->ip_offset), MONO_EXCEPTION_FIELD_ACCESS);
3455 set_stack_value (ctx, stack_push (ctx), field->type, take_addr);
3458 static void
3459 do_store_static_field (VerifyContext *ctx, int token) {
3460 MonoClassField *field;
3461 MonoClass *klass;
3462 ILStackDesc *value;
3463 CLEAR_PREFIX (ctx, PREFIX_VOLATILE);
3465 if (!check_underflow (ctx, 1))
3466 return;
3468 value = stack_pop (ctx);
3470 if (!(field = verifier_load_field (ctx, token, &klass, "stsfld")))
3471 return;
3473 if (!(field->type->attrs & FIELD_ATTRIBUTE_STATIC)) {
3474 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Cannot store non static field at 0x%04x", ctx->ip_offset));
3475 return;
3478 if (field->type->type == MONO_TYPE_TYPEDBYREF) {
3479 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Typedbyref field is an unverfiable type in store static field at 0x%04x", ctx->ip_offset));
3480 return;
3483 if (!IS_SKIP_VISIBILITY (ctx) && !mono_method_can_access_field_full (ctx->method, field, NULL))
3484 CODE_NOT_VERIFIABLE2 (ctx, g_strdup_printf ("Type at stack is not accessible at 0x%04x", ctx->ip_offset), MONO_EXCEPTION_FIELD_ACCESS);
3486 if (!verify_stack_type_compatibility (ctx, field->type, value))
3487 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Incompatible type %s in static field store at 0x%04x", stack_slot_get_name (value), ctx->ip_offset));
3490 static gboolean
3491 check_is_valid_type_for_field_ops (VerifyContext *ctx, int token, ILStackDesc *obj, MonoClassField **ret_field, const char *opcode)
3493 MonoClassField *field;
3494 MonoClass *klass;
3495 gboolean is_pointer;
3497 /*must be a reference type, a managed pointer, an unamanaged pointer, or a valuetype*/
3498 if (!(field = verifier_load_field (ctx, token, &klass, opcode)))
3499 return FALSE;
3501 *ret_field = field;
3502 //the value on stack is going to be used as a pointer
3503 is_pointer = stack_slot_get_type (obj) == TYPE_PTR || (stack_slot_get_type (obj) == TYPE_NATIVE_INT && !get_stack_type (&field->parent->byval_arg));
3505 if (field->type->type == MONO_TYPE_TYPEDBYREF) {
3506 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Typedbyref field is an unverfiable type at 0x%04x", ctx->ip_offset));
3507 return FALSE;
3509 g_assert (obj->type);
3511 /*The value on the stack must be a subclass of the defining type of the field*/
3512 /* we need to check if we can load the field from the stack value*/
3513 if (is_pointer) {
3514 if (stack_slot_get_underlying_type (obj) == TYPE_NATIVE_INT)
3515 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Native int is not a verifiable type to reference a field at 0x%04x", ctx->ip_offset));
3517 if (!IS_SKIP_VISIBILITY (ctx) && !mono_method_can_access_field_full (ctx->method, field, NULL))
3518 CODE_NOT_VERIFIABLE2 (ctx, g_strdup_printf ("Type at stack is not accessible at 0x%04x", ctx->ip_offset), MONO_EXCEPTION_FIELD_ACCESS);
3519 } else {
3520 if (!field->parent->valuetype && stack_slot_is_managed_pointer (obj))
3521 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));
3523 /*a value type can be loaded from a value or a managed pointer, but not a boxed object*/
3524 if (field->parent->valuetype && stack_slot_is_boxed_value (obj))
3525 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));
3527 if (!stack_slot_is_null_literal (obj) && !verify_stack_type_compatibility_full (ctx, &field->parent->byval_arg, obj, TRUE, FALSE))
3528 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Type at stack is not compatible to reference the field at 0x%04x", ctx->ip_offset));
3530 if (!IS_SKIP_VISIBILITY (ctx) && !mono_method_can_access_field_full (ctx->method, field, mono_class_from_mono_type (obj->type)))
3531 CODE_NOT_VERIFIABLE2 (ctx, g_strdup_printf ("Type at stack is not accessible at 0x%04x", ctx->ip_offset), MONO_EXCEPTION_FIELD_ACCESS);
3534 check_unmanaged_pointer (ctx, obj);
3535 return TRUE;
3538 static void
3539 do_push_field (VerifyContext *ctx, int token, gboolean take_addr)
3541 ILStackDesc *obj;
3542 MonoClassField *field;
3544 if (!take_addr)
3545 CLEAR_PREFIX (ctx, PREFIX_UNALIGNED | PREFIX_VOLATILE);
3547 if (!check_underflow (ctx, 1))
3548 return;
3549 obj = stack_pop_safe (ctx);
3551 if (!check_is_valid_type_for_field_ops (ctx, token, obj, &field, take_addr ? "ldflda" : "ldfld"))
3552 return;
3554 if (take_addr && field->parent->valuetype && !stack_slot_is_managed_pointer (obj))
3555 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot take the address of a temporary value-type at 0x%04x", ctx->ip_offset));
3557 if (take_addr && (field->type->attrs & FIELD_ATTRIBUTE_INIT_ONLY) &&
3558 !(field->parent == ctx->method->klass && mono_method_is_constructor (ctx->method)))
3559 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot take the address of a init-only field at 0x%04x", ctx->ip_offset));
3561 set_stack_value (ctx, stack_push (ctx), field->type, take_addr);
3564 static void
3565 do_store_field (VerifyContext *ctx, int token)
3567 ILStackDesc *value, *obj;
3568 MonoClassField *field;
3569 CLEAR_PREFIX (ctx, PREFIX_UNALIGNED | PREFIX_VOLATILE);
3571 if (!check_underflow (ctx, 2))
3572 return;
3574 value = stack_pop (ctx);
3575 obj = stack_pop_safe (ctx);
3577 if (!check_is_valid_type_for_field_ops (ctx, token, obj, &field, "stfld"))
3578 return;
3580 if (!verify_stack_type_compatibility (ctx, field->type, value))
3581 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Incompatible type %s in field store at 0x%04x", stack_slot_get_name (value), ctx->ip_offset));
3584 /*TODO proper handle for Nullable<T>*/
3585 static void
3586 do_box_value (VerifyContext *ctx, int klass_token)
3588 ILStackDesc *value;
3589 MonoType *type = get_boxable_mono_type (ctx, klass_token, "box");
3590 MonoClass *klass;
3592 if (!type)
3593 return;
3595 if (!check_underflow (ctx, 1))
3596 return;
3598 value = stack_pop (ctx);
3599 /*box is a nop for reference types*/
3601 if (stack_slot_get_underlying_type (value) == TYPE_COMPLEX && MONO_TYPE_IS_REFERENCE (value->type) && MONO_TYPE_IS_REFERENCE (type)) {
3602 stack_push_stack_val (ctx, value)->stype |= BOXED_MASK;
3603 return;
3607 if (!verify_stack_type_compatibility (ctx, type, value))
3608 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid type at stack for boxing operation at 0x%04x", ctx->ip_offset));
3610 klass = mono_class_from_mono_type (type);
3611 if (mono_class_is_nullable (klass))
3612 type = &mono_class_get_nullable_param (klass)->byval_arg;
3613 stack_push_val (ctx, TYPE_COMPLEX | BOXED_MASK, type);
3616 static void
3617 do_unbox_value (VerifyContext *ctx, int klass_token)
3619 ILStackDesc *value;
3620 MonoType *type = get_boxable_mono_type (ctx, klass_token, "unbox");
3622 if (!type)
3623 return;
3625 if (!check_underflow (ctx, 1))
3626 return;
3628 if (!mono_class_from_mono_type (type)->valuetype)
3629 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid reference type for unbox at 0x%04x", ctx->ip_offset));
3631 value = stack_pop (ctx);
3633 /*Value should be: a boxed valuetype or a reference type*/
3634 if (!(stack_slot_get_type (value) == TYPE_COMPLEX &&
3635 (stack_slot_is_boxed_value (value) || !mono_class_from_mono_type (value->type)->valuetype)))
3636 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));
3638 set_stack_value (ctx, value = stack_push (ctx), mono_type_get_type_byref (type), FALSE);
3639 value->stype |= CMMP_MASK;
3642 static void
3643 do_unbox_any (VerifyContext *ctx, int klass_token)
3645 ILStackDesc *value;
3646 MonoType *type = get_boxable_mono_type (ctx, klass_token, "unbox.any");
3648 if (!type)
3649 return;
3651 if (!check_underflow (ctx, 1))
3652 return;
3654 value = stack_pop (ctx);
3656 /*Value should be: a boxed valuetype or a reference type*/
3657 if (!(stack_slot_get_type (value) == TYPE_COMPLEX &&
3658 (stack_slot_is_boxed_value (value) || !mono_class_from_mono_type (value->type)->valuetype)))
3659 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));
3661 set_stack_value (ctx, stack_push (ctx), type, FALSE);
3664 static void
3665 do_unary_math_op (VerifyContext *ctx, int op)
3667 ILStackDesc *value;
3668 if (!check_underflow (ctx, 1))
3669 return;
3670 value = stack_pop (ctx);
3671 switch (stack_slot_get_type (value)) {
3672 case TYPE_I4:
3673 case TYPE_I8:
3674 case TYPE_NATIVE_INT:
3675 break;
3676 case TYPE_R8:
3677 if (op == CEE_NEG)
3678 break;
3679 case TYPE_COMPLEX: /*only enums are ok*/
3680 if (mono_type_is_enum_type (value->type))
3681 break;
3682 default:
3683 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid type at stack for unary not at 0x%04x", ctx->ip_offset));
3685 stack_push_stack_val (ctx, value);
3688 static void
3689 do_conversion (VerifyContext *ctx, int kind)
3691 ILStackDesc *value;
3692 if (!check_underflow (ctx, 1))
3693 return;
3694 value = stack_pop (ctx);
3696 switch (stack_slot_get_type (value)) {
3697 case TYPE_I4:
3698 case TYPE_I8:
3699 case TYPE_NATIVE_INT:
3700 case TYPE_R8:
3701 break;
3702 default:
3703 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));
3706 switch (kind) {
3707 case TYPE_I4:
3708 stack_push_val (ctx, TYPE_I4, &mono_defaults.int32_class->byval_arg);
3709 break;
3710 case TYPE_I8:
3711 stack_push_val (ctx,TYPE_I8, &mono_defaults.int64_class->byval_arg);
3712 break;
3713 case TYPE_R8:
3714 stack_push_val (ctx, TYPE_R8, &mono_defaults.double_class->byval_arg);
3715 break;
3716 case TYPE_NATIVE_INT:
3717 stack_push_val (ctx, TYPE_NATIVE_INT, &mono_defaults.int_class->byval_arg);
3718 break;
3719 default:
3720 g_error ("unknown type %02x in conversion", kind);
3725 static void
3726 do_load_token (VerifyContext *ctx, int token)
3728 gpointer handle;
3729 MonoClass *handle_class;
3730 if (!check_overflow (ctx))
3731 return;
3732 handle = mono_ldtoken (ctx->image, token, &handle_class, ctx->generic_context);
3733 if (!handle) {
3734 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid token 0x%x for ldtoken at 0x%04x", token, ctx->ip_offset));
3735 return;
3737 if (handle_class == mono_defaults.typehandle_class) {
3738 mono_type_is_valid_in_context (ctx, (MonoType*)handle);
3739 } else if (handle_class == mono_defaults.methodhandle_class) {
3740 mono_method_is_valid_in_context (ctx, (MonoMethod*)handle);
3741 } else if (handle_class == mono_defaults.fieldhandle_class) {
3742 mono_type_is_valid_in_context (ctx, &((MonoClassField*)handle)->parent->byval_arg);
3743 } else {
3744 ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid ldtoken type %x at 0x%04x", token, ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE);
3746 stack_push_val (ctx, TYPE_COMPLEX, mono_class_get_type (handle_class));
3749 static void
3750 do_ldobj_value (VerifyContext *ctx, int token)
3752 ILStackDesc *value;
3753 MonoType *type = get_boxable_mono_type (ctx, token, "ldobj");
3754 CLEAR_PREFIX (ctx, PREFIX_UNALIGNED | PREFIX_VOLATILE);
3756 if (!type)
3757 return;
3759 if (!check_underflow (ctx, 1))
3760 return;
3762 value = stack_pop (ctx);
3763 if (!stack_slot_is_managed_pointer (value)
3764 && stack_slot_get_type (value) != TYPE_NATIVE_INT
3765 && !(stack_slot_get_type (value) == TYPE_PTR && value->type->type != MONO_TYPE_FNPTR)) {
3766 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid argument %s to ldobj at 0x%04x", stack_slot_get_name (value), ctx->ip_offset));
3767 return;
3770 if (stack_slot_get_type (value) == TYPE_NATIVE_INT)
3771 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Using native pointer to ldobj at 0x%04x", ctx->ip_offset));
3773 /*We have a byval on the stack, but the comparison must be strict. */
3774 if (!verify_type_compatibility_full (ctx, type, mono_type_get_type_byval (value->type), TRUE))
3775 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid type at stack for ldojb operation at 0x%04x", ctx->ip_offset));
3777 set_stack_value (ctx, stack_push (ctx), type, FALSE);
3780 static void
3781 do_stobj (VerifyContext *ctx, int token)
3783 ILStackDesc *dest, *src;
3784 MonoType *type = get_boxable_mono_type (ctx, token, "stobj");
3785 CLEAR_PREFIX (ctx, PREFIX_UNALIGNED | PREFIX_VOLATILE);
3787 if (!type)
3788 return;
3790 if (!check_underflow (ctx, 2))
3791 return;
3793 src = stack_pop (ctx);
3794 dest = stack_pop (ctx);
3796 if (stack_slot_is_managed_mutability_pointer (dest))
3797 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use a readonly pointer with stobj at 0x%04x", ctx->ip_offset));
3799 if (!stack_slot_is_managed_pointer (dest))
3800 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid destination of stobj operation at 0x%04x", ctx->ip_offset));
3802 if (stack_slot_is_boxed_value (src) && !MONO_TYPE_IS_REFERENCE (src->type) && !MONO_TYPE_IS_REFERENCE (type))
3803 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));
3805 if (!verify_stack_type_compatibility (ctx, type, src))
3806 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Token and source types of stobj don't match at 0x%04x", ctx->ip_offset));
3808 if (!verify_type_compatibility (ctx, mono_type_get_type_byval (dest->type), type))
3809 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Destination and token types of stobj don't match at 0x%04x", ctx->ip_offset));
3812 static void
3813 do_cpobj (VerifyContext *ctx, int token)
3815 ILStackDesc *dest, *src;
3816 MonoType *type = get_boxable_mono_type (ctx, token, "cpobj");
3817 if (!type)
3818 return;
3820 if (!check_underflow (ctx, 2))
3821 return;
3823 src = stack_pop (ctx);
3824 dest = stack_pop (ctx);
3826 if (!stack_slot_is_managed_pointer (src))
3827 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid source of cpobj operation at 0x%04x", ctx->ip_offset));
3829 if (!stack_slot_is_managed_pointer (dest))
3830 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid destination of cpobj operation at 0x%04x", ctx->ip_offset));
3832 if (stack_slot_is_managed_mutability_pointer (dest))
3833 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use a readonly pointer with cpobj at 0x%04x", ctx->ip_offset));
3835 if (!verify_type_compatibility (ctx, type, mono_type_get_type_byval (src->type)))
3836 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Token and source types of cpobj don't match at 0x%04x", ctx->ip_offset));
3838 if (!verify_type_compatibility (ctx, mono_type_get_type_byval (dest->type), type))
3839 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Destination and token types of cpobj don't match at 0x%04x", ctx->ip_offset));
3842 static void
3843 do_initobj (VerifyContext *ctx, int token)
3845 ILStackDesc *obj;
3846 MonoType *stack, *type = get_boxable_mono_type (ctx, token, "initobj");
3847 if (!type)
3848 return;
3850 if (!check_underflow (ctx, 1))
3851 return;
3853 obj = stack_pop (ctx);
3855 if (!stack_slot_is_managed_pointer (obj))
3856 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid object address for initobj at 0x%04x", ctx->ip_offset));
3858 if (stack_slot_is_managed_mutability_pointer (obj))
3859 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use a readonly pointer with initobj at 0x%04x", ctx->ip_offset));
3861 stack = mono_type_get_type_byval (obj->type);
3862 if (MONO_TYPE_IS_REFERENCE (stack)) {
3863 if (!verify_type_compatibility (ctx, stack, type))
3864 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Type token of initobj not compatible with value on stack at 0x%04x", ctx->ip_offset));
3865 else if (IS_STRICT_MODE (ctx) && !mono_metadata_type_equal (type, stack))
3866 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Type token of initobj not compatible with value on stack at 0x%04x", ctx->ip_offset));
3867 } else if (!verify_type_compatibility (ctx, stack, type)) {
3868 char *expected_name = mono_type_full_name (type);
3869 char *stack_name = mono_type_full_name (stack);
3871 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));
3872 g_free (expected_name);
3873 g_free (stack_name);
3877 static void
3878 do_newobj (VerifyContext *ctx, int token)
3880 ILStackDesc *value;
3881 int i;
3882 MonoMethodSignature *sig;
3883 MonoMethod *method;
3884 gboolean is_delegate = FALSE;
3886 if (!(method = verifier_load_method (ctx, token, "newobj")))
3887 return;
3889 if (!mono_method_is_constructor (method)) {
3890 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Method from token 0x%08x not a constructor at 0x%04x", token, ctx->ip_offset));
3891 return;
3894 if (method->klass->flags & (TYPE_ATTRIBUTE_ABSTRACT | TYPE_ATTRIBUTE_INTERFACE))
3895 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Trying to instantiate an abstract or interface type at 0x%04x", ctx->ip_offset));
3897 if (!mono_method_can_access_method_full (ctx->method, method, NULL)) {
3898 char *from = mono_method_full_name (ctx->method, TRUE);
3899 char *to = mono_method_full_name (method, TRUE);
3900 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);
3901 g_free (from);
3902 g_free (to);
3905 //FIXME use mono_method_get_signature_full
3906 sig = mono_method_signature (method);
3907 if (!check_underflow (ctx, sig->param_count))
3908 return;
3910 is_delegate = method->klass->parent == mono_defaults.multicastdelegate_class;
3912 if (is_delegate) {
3913 ILStackDesc *funptr;
3914 //first arg is object, second arg is fun ptr
3915 if (sig->param_count != 2) {
3916 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid delegate constructor at 0x%04x", ctx->ip_offset));
3917 return;
3919 funptr = stack_pop (ctx);
3920 value = stack_pop (ctx);
3921 verify_delegate_compatibility (ctx, method->klass, value, funptr);
3922 } else {
3923 for (i = sig->param_count - 1; i >= 0; --i) {
3924 VERIFIER_DEBUG ( printf ("verifying constructor argument %d\n", i); );
3925 value = stack_pop (ctx);
3926 if (!verify_stack_type_compatibility (ctx, sig->params [i], value)) {
3927 char *stack_name = stack_slot_full_name (value);
3928 char *sig_name = mono_type_full_name (sig->params [i]);
3929 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));
3930 g_free (stack_name);
3931 g_free (sig_name);
3934 if (stack_slot_is_managed_mutability_pointer (value))
3935 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use a readonly pointer as argument of newobj at 0x%04x", ctx->ip_offset));
3939 if (check_overflow (ctx))
3940 set_stack_value (ctx, stack_push (ctx), &method->klass->byval_arg, FALSE);
3943 static void
3944 do_cast (VerifyContext *ctx, int token, const char *opcode) {
3945 ILStackDesc *value;
3946 MonoType *type;
3947 gboolean is_boxed;
3948 gboolean do_box;
3950 if (!check_underflow (ctx, 1))
3951 return;
3953 if (!(type = verifier_load_type (ctx, token, opcode)))
3954 return;
3956 if (type->byref) {
3957 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid %s type at 0x%04x", opcode, ctx->ip_offset));
3958 return;
3961 value = stack_pop (ctx);
3962 is_boxed = stack_slot_is_boxed_value (value);
3964 if (stack_slot_is_managed_pointer (value))
3965 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid value for %s at 0x%04x", opcode, ctx->ip_offset));
3966 else if (mono_class_from_mono_type (value->type)->valuetype && !is_boxed)
3967 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Value cannot be a valuetype for %s at 0x%04x", opcode, ctx->ip_offset));
3969 switch (value->type->type) {
3970 case MONO_TYPE_FNPTR:
3971 case MONO_TYPE_PTR:
3972 case MONO_TYPE_TYPEDBYREF:
3973 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid value for %s at 0x%04x", opcode, ctx->ip_offset));
3976 do_box = is_boxed || mono_type_is_generic_argument(type) || mono_class_from_mono_type (type)->valuetype;
3977 stack_push_val (ctx, TYPE_COMPLEX | (do_box ? BOXED_MASK : 0), type);
3980 static MonoType *
3981 mono_type_from_opcode (int opcode) {
3982 switch (opcode) {
3983 case CEE_LDIND_I1:
3984 case CEE_LDIND_U1:
3985 case CEE_STIND_I1:
3986 case CEE_LDELEM_I1:
3987 case CEE_LDELEM_U1:
3988 case CEE_STELEM_I1:
3989 return &mono_defaults.sbyte_class->byval_arg;
3991 case CEE_LDIND_I2:
3992 case CEE_LDIND_U2:
3993 case CEE_STIND_I2:
3994 case CEE_LDELEM_I2:
3995 case CEE_LDELEM_U2:
3996 case CEE_STELEM_I2:
3997 return &mono_defaults.int16_class->byval_arg;
3999 case CEE_LDIND_I4:
4000 case CEE_LDIND_U4:
4001 case CEE_STIND_I4:
4002 case CEE_LDELEM_I4:
4003 case CEE_LDELEM_U4:
4004 case CEE_STELEM_I4:
4005 return &mono_defaults.int32_class->byval_arg;
4007 case CEE_LDIND_I8:
4008 case CEE_STIND_I8:
4009 case CEE_LDELEM_I8:
4010 case CEE_STELEM_I8:
4011 return &mono_defaults.int64_class->byval_arg;
4013 case CEE_LDIND_R4:
4014 case CEE_STIND_R4:
4015 case CEE_LDELEM_R4:
4016 case CEE_STELEM_R4:
4017 return &mono_defaults.single_class->byval_arg;
4019 case CEE_LDIND_R8:
4020 case CEE_STIND_R8:
4021 case CEE_LDELEM_R8:
4022 case CEE_STELEM_R8:
4023 return &mono_defaults.double_class->byval_arg;
4025 case CEE_LDIND_I:
4026 case CEE_STIND_I:
4027 case CEE_LDELEM_I:
4028 case CEE_STELEM_I:
4029 return &mono_defaults.int_class->byval_arg;
4031 case CEE_LDIND_REF:
4032 case CEE_STIND_REF:
4033 case CEE_LDELEM_REF:
4034 case CEE_STELEM_REF:
4035 return &mono_defaults.object_class->byval_arg;
4037 default:
4038 g_error ("unknown opcode %02x in mono_type_from_opcode ", opcode);
4039 return NULL;
4043 static void
4044 do_load_indirect (VerifyContext *ctx, int opcode)
4046 ILStackDesc *value;
4047 CLEAR_PREFIX (ctx, PREFIX_UNALIGNED | PREFIX_VOLATILE);
4049 if (!check_underflow (ctx, 1))
4050 return;
4052 value = stack_pop (ctx);
4053 if (!stack_slot_is_managed_pointer (value)) {
4054 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Load indirect not using a manager pointer at 0x%04x", ctx->ip_offset));
4055 set_stack_value (ctx, stack_push (ctx), mono_type_from_opcode (opcode), FALSE);
4056 return;
4059 if (opcode == CEE_LDIND_REF) {
4060 if (stack_slot_get_underlying_type (value) != TYPE_COMPLEX || mono_class_from_mono_type (value->type)->valuetype)
4061 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid type at stack for ldind_ref expected object byref operation at 0x%04x", ctx->ip_offset));
4062 set_stack_value (ctx, stack_push (ctx), mono_type_get_type_byval (value->type), FALSE);
4063 } else {
4064 if (!verify_type_compatibility_full (ctx, mono_type_from_opcode (opcode), mono_type_get_type_byval (value->type), TRUE))
4065 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid type at stack for ldind 0x%x operation at 0x%04x", opcode, ctx->ip_offset));
4066 set_stack_value (ctx, stack_push (ctx), mono_type_from_opcode (opcode), FALSE);
4070 static void
4071 do_store_indirect (VerifyContext *ctx, int opcode)
4073 ILStackDesc *addr, *val;
4074 CLEAR_PREFIX (ctx, PREFIX_UNALIGNED | PREFIX_VOLATILE);
4076 if (!check_underflow (ctx, 2))
4077 return;
4079 val = stack_pop (ctx);
4080 addr = stack_pop (ctx);
4082 check_unmanaged_pointer (ctx, addr);
4084 if (!stack_slot_is_managed_pointer (addr) && stack_slot_get_type (addr) != TYPE_PTR) {
4085 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid non-pointer argument to stind at 0x%04x", ctx->ip_offset));
4086 return;
4089 if (stack_slot_is_managed_mutability_pointer (addr)) {
4090 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use a readonly pointer with stind at 0x%04x", ctx->ip_offset));
4091 return;
4094 if (!verify_type_compatibility_full (ctx, mono_type_from_opcode (opcode), mono_type_get_type_byval (addr->type), TRUE))
4095 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid addr type at stack for stind 0x%x operation at 0x%04x", opcode, ctx->ip_offset));
4097 if (!verify_stack_type_compatibility (ctx, mono_type_from_opcode (opcode), val))
4098 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid value type at stack for stind 0x%x operation at 0x%04x", opcode, ctx->ip_offset));
4101 static void
4102 do_newarr (VerifyContext *ctx, int token)
4104 ILStackDesc *value;
4105 MonoType *type = get_boxable_mono_type (ctx, token, "newarr");
4107 if (!type)
4108 return;
4110 if (!check_underflow (ctx, 1))
4111 return;
4113 value = stack_pop (ctx);
4114 if (stack_slot_get_type (value) != TYPE_I4 && stack_slot_get_type (value) != TYPE_NATIVE_INT)
4115 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));
4117 set_stack_value (ctx, stack_push (ctx), mono_class_get_type (mono_array_class_get (mono_class_from_mono_type (type), 1)), FALSE);
4120 /*FIXME handle arrays that are not 0-indexed*/
4121 static void
4122 do_ldlen (VerifyContext *ctx)
4124 ILStackDesc *value;
4126 if (!check_underflow (ctx, 1))
4127 return;
4129 value = stack_pop (ctx);
4131 if (stack_slot_get_type (value) != TYPE_COMPLEX || value->type->type != MONO_TYPE_SZARRAY)
4132 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type for ldlen at 0x%04x", ctx->ip_offset));
4134 stack_push_val (ctx, TYPE_NATIVE_INT, &mono_defaults.int_class->byval_arg);
4137 /*FIXME handle arrays that are not 0-indexed*/
4138 /*FIXME handle readonly prefix and CMMP*/
4139 static void
4140 do_ldelema (VerifyContext *ctx, int klass_token)
4142 ILStackDesc *index, *array, *res;
4143 MonoType *type = get_boxable_mono_type (ctx, klass_token, "ldelema");
4144 gboolean valid;
4146 if (!type)
4147 return;
4149 if (!check_underflow (ctx, 2))
4150 return;
4152 index = stack_pop (ctx);
4153 array = stack_pop (ctx);
4155 if (stack_slot_get_type (index) != TYPE_I4 && stack_slot_get_type (index) != TYPE_NATIVE_INT)
4156 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));
4158 if (!stack_slot_is_null_literal (array)) {
4159 if (stack_slot_get_type (array) != TYPE_COMPLEX || array->type->type != MONO_TYPE_SZARRAY)
4160 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type(%s) for ldelema at 0x%04x", stack_slot_get_name (array), ctx->ip_offset));
4161 else {
4162 if (get_stack_type (type) == TYPE_I4 || get_stack_type (type) == TYPE_NATIVE_INT) {
4163 valid = verify_type_compatibility_full (ctx, type, &array->type->data.klass->byval_arg, TRUE);
4164 } else {
4165 valid = mono_metadata_type_equal (type, &array->type->data.klass->byval_arg);
4167 if (!valid)
4168 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type on stack for ldelema at 0x%04x", ctx->ip_offset));
4172 res = stack_push (ctx);
4173 set_stack_value (ctx, res, type, TRUE);
4174 if (ctx->prefix_set & PREFIX_READONLY) {
4175 ctx->prefix_set &= ~PREFIX_READONLY;
4176 res->stype |= CMMP_MASK;
4181 * FIXME handle arrays that are not 0-indexed
4182 * FIXME handle readonly prefix and CMMP
4184 static void
4185 do_ldelem (VerifyContext *ctx, int opcode, int token)
4187 #define IS_ONE_OF2(T, A, B) (T == A || T == B)
4188 ILStackDesc *index, *array;
4189 MonoType *type;
4190 if (!check_underflow (ctx, 2))
4191 return;
4193 if (opcode == CEE_LDELEM_ANY) {
4194 if (!(type = verifier_load_type (ctx, token, "ldelem.any"))) {
4195 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Type (0x%08x) not found at 0x%04x", token, ctx->ip_offset));
4196 return;
4198 } else {
4199 type = mono_type_from_opcode (opcode);
4202 index = stack_pop (ctx);
4203 array = stack_pop (ctx);
4205 if (stack_slot_get_type (index) != TYPE_I4 && stack_slot_get_type (index) != TYPE_NATIVE_INT)
4206 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));
4208 if (!stack_slot_is_null_literal (array)) {
4209 if (stack_slot_get_type (array) != TYPE_COMPLEX || array->type->type != MONO_TYPE_SZARRAY)
4210 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));
4211 else {
4212 if (opcode == CEE_LDELEM_REF) {
4213 if (array->type->data.klass->valuetype)
4214 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type is not a reference type for ldelem.ref 0x%04x", ctx->ip_offset));
4215 type = &array->type->data.klass->byval_arg;
4216 } else {
4217 MonoType *candidate = &array->type->data.klass->byval_arg;
4218 if (IS_STRICT_MODE (ctx)) {
4219 MonoType *underlying_type = mono_type_get_underlying_type_any (type);
4220 MonoType *underlying_candidate = mono_type_get_underlying_type_any (candidate);
4221 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)) ||
4222 (IS_ONE_OF2 (underlying_candidate->type, MONO_TYPE_I4, MONO_TYPE_U4) && IS_ONE_OF2 (underlying_type->type, MONO_TYPE_I, MONO_TYPE_U)))
4223 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type on stack for ldelem.X at 0x%04x", ctx->ip_offset));
4225 if (!verify_type_compatibility_full (ctx, type, candidate, TRUE))
4226 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type on stack for ldelem.X at 0x%04x", ctx->ip_offset));
4231 set_stack_value (ctx, stack_push (ctx), type, FALSE);
4232 #undef IS_ONE_OF2
4236 * FIXME handle arrays that are not 0-indexed
4238 static void
4239 do_stelem (VerifyContext *ctx, int opcode, int token)
4241 ILStackDesc *index, *array, *value;
4242 MonoType *type;
4243 if (!check_underflow (ctx, 3))
4244 return;
4246 if (opcode == CEE_STELEM_ANY) {
4247 if (!(type = verifier_load_type (ctx, token, "stelem.any"))) {
4248 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Type (0x%08x) not found at 0x%04x", token, ctx->ip_offset));
4249 return;
4251 } else {
4252 type = mono_type_from_opcode (opcode);
4255 value = stack_pop (ctx);
4256 index = stack_pop (ctx);
4257 array = stack_pop (ctx);
4259 if (stack_slot_get_type (index) != TYPE_I4 && stack_slot_get_type (index) != TYPE_NATIVE_INT)
4260 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));
4262 if (!stack_slot_is_null_literal (array)) {
4263 if (stack_slot_get_type (array) != TYPE_COMPLEX || array->type->type != MONO_TYPE_SZARRAY) {
4264 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));
4265 } else {
4266 if (opcode == CEE_STELEM_REF) {
4267 if (array->type->data.klass->valuetype)
4268 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type is not a reference type for stelem.ref 0x%04x", ctx->ip_offset));
4269 } else if (!verify_type_compatibility_full (ctx, &array->type->data.klass->byval_arg, type, TRUE)) {
4270 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type on stack for stdelem.X at 0x%04x", ctx->ip_offset));
4274 if (opcode == CEE_STELEM_REF) {
4275 if (!stack_slot_is_boxed_value (value) && mono_class_from_mono_type (value->type)->valuetype)
4276 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid value is not a reference type for stelem.ref 0x%04x", ctx->ip_offset));
4277 } else if (opcode != CEE_STELEM_REF) {
4278 if (!verify_stack_type_compatibility (ctx, type, value))
4279 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid value on stack for stdelem.X at 0x%04x", ctx->ip_offset));
4281 if (stack_slot_is_boxed_value (value) && !MONO_TYPE_IS_REFERENCE (value->type) && !MONO_TYPE_IS_REFERENCE (type))
4282 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));
4287 static void
4288 do_throw (VerifyContext *ctx)
4290 ILStackDesc *exception;
4291 if (!check_underflow (ctx, 1))
4292 return;
4293 exception = stack_pop (ctx);
4295 if (!stack_slot_is_null_literal (exception) && !(stack_slot_get_type (exception) == TYPE_COMPLEX && !mono_class_from_mono_type (exception->type)->valuetype))
4296 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid type on stack for throw, expected reference type at 0x%04x", ctx->ip_offset));
4298 if (mono_type_is_generic_argument (exception->type) && !stack_slot_is_boxed_value (exception)) {
4299 char *name = mono_type_full_name (exception->type);
4300 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));
4301 g_free (name);
4303 /*The stack is left empty after a throw*/
4304 ctx->eval.size = 0;
4308 static void
4309 do_endfilter (VerifyContext *ctx)
4311 MonoExceptionClause *clause;
4313 if (IS_STRICT_MODE (ctx)) {
4314 if (ctx->eval.size != 1)
4315 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Stack size must have one item for endfilter at 0x%04x", ctx->ip_offset));
4317 if (ctx->eval.size >= 1 && stack_slot_get_type (stack_pop (ctx)) != TYPE_I4)
4318 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Stack item type is not an int32 for endfilter at 0x%04x", ctx->ip_offset));
4321 if ((clause = is_correct_endfilter (ctx, ctx->ip_offset))) {
4322 if (IS_STRICT_MODE (ctx)) {
4323 if (ctx->ip_offset != clause->handler_offset - 2)
4324 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("endfilter is not the last instruction of the filter clause at 0x%04x", ctx->ip_offset));
4325 } else {
4326 if ((ctx->ip_offset != clause->handler_offset - 2) && !MONO_OFFSET_IN_HANDLER (clause, ctx->ip_offset))
4327 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("endfilter is not the last instruction of the filter clause at 0x%04x", ctx->ip_offset));
4329 } else {
4330 if (IS_STRICT_MODE (ctx) && !is_unverifiable_endfilter (ctx, ctx->ip_offset))
4331 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("endfilter outside filter clause at 0x%04x", ctx->ip_offset));
4332 else
4333 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("endfilter outside filter clause at 0x%04x", ctx->ip_offset));
4336 ctx->eval.size = 0;
4339 static void
4340 do_leave (VerifyContext *ctx, int delta)
4342 int target = ((gint32)ctx->ip_offset) + delta;
4343 if (target >= ctx->code_size || target < 0)
4344 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Branch target out of code at 0x%04x", ctx->ip_offset));
4346 if (!is_correct_leave (ctx->header, ctx->ip_offset, target))
4347 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Leave not allowed in finally block at 0x%04x", ctx->ip_offset));
4348 ctx->eval.size = 0;
4352 * do_static_branch:
4354 * Verify br and br.s opcodes.
4356 static void
4357 do_static_branch (VerifyContext *ctx, int delta)
4359 int target = ctx->ip_offset + delta;
4360 if (target < 0 || target >= ctx->code_size) {
4361 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("branch target out of code at 0x%04x", ctx->ip_offset));
4362 return;
4365 switch (is_valid_branch_instruction (ctx->header, ctx->ip_offset, target)) {
4366 case 1:
4367 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Branch target escapes out of exception block at 0x%04x", ctx->ip_offset));
4368 break;
4369 case 2:
4370 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Branch target escapes out of exception block at 0x%04x", ctx->ip_offset));
4371 break;
4374 ctx->target = target;
4377 static void
4378 do_switch (VerifyContext *ctx, int count, const unsigned char *data)
4380 int i, base = ctx->ip_offset + 5 + count * 4;
4381 ILStackDesc *value;
4383 if (!check_underflow (ctx, 1))
4384 return;
4386 value = stack_pop (ctx);
4388 if (stack_slot_get_type (value) != TYPE_I4 && stack_slot_get_type (value) != TYPE_NATIVE_INT)
4389 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid argument to switch at 0x%04x", ctx->ip_offset));
4391 for (i = 0; i < count; ++i) {
4392 int target = base + read32 (data + i * 4);
4394 if (target < 0 || target >= ctx->code_size) {
4395 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Switch target %x out of code at 0x%04x", i, ctx->ip_offset));
4396 return;
4399 switch (is_valid_branch_instruction (ctx->header, ctx->ip_offset, target)) {
4400 case 1:
4401 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Switch target %x escapes out of exception block at 0x%04x", i, ctx->ip_offset));
4402 break;
4403 case 2:
4404 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Switch target %x escapes out of exception block at 0x%04x", i, ctx->ip_offset));
4405 return;
4407 merge_stacks (ctx, &ctx->eval, &ctx->code [target], FALSE, TRUE);
4411 static void
4412 do_load_function_ptr (VerifyContext *ctx, guint32 token, gboolean virtual)
4414 ILStackDesc *top;
4415 MonoMethod *method;
4417 if (virtual && !check_underflow (ctx, 1))
4418 return;
4420 if (!virtual && !check_overflow (ctx))
4421 return;
4423 if (!IS_METHOD_DEF_OR_REF_OR_SPEC (token) || !token_bounds_check (ctx->image, token)) {
4424 ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid token %x for ldftn at 0x%04x", token, ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE);
4425 return;
4428 if (!(method = verifier_load_method (ctx, token, virtual ? "ldvirtfrn" : "ldftn")))
4429 return;
4431 if (mono_method_is_constructor (method))
4432 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use ldftn with a constructor at 0x%04x", ctx->ip_offset));
4434 if (virtual) {
4435 ILStackDesc *top = stack_pop (ctx);
4437 if (stack_slot_get_type (top) != TYPE_COMPLEX || top->type->type == MONO_TYPE_VALUETYPE)
4438 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid argument to ldvirtftn at 0x%04x", ctx->ip_offset));
4440 if (method->flags & METHOD_ATTRIBUTE_STATIC)
4441 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use ldvirtftn with a constructor at 0x%04x", ctx->ip_offset));
4443 if (!verify_stack_type_compatibility (ctx, &method->klass->byval_arg, top))
4444 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Unexpected object for ldvirtftn at 0x%04x", ctx->ip_offset));
4447 if (!mono_method_can_access_method_full (ctx->method, method, NULL))
4448 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);
4450 top = stack_push_val(ctx, TYPE_PTR, mono_type_create_fnptr_from_mono_method (ctx, method));
4451 top->method = method;
4454 static void
4455 do_sizeof (VerifyContext *ctx, int token)
4457 MonoType *type;
4459 if (!IS_TYPE_DEF_OR_REF_OR_SPEC (token) || !token_bounds_check (ctx->image, token)) {
4460 ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid type token %x at 0x%04x", token, ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE);
4461 return;
4464 if (!(type = verifier_load_type (ctx, token, "sizeof")))
4465 return;
4467 if (type->byref && type->type != MONO_TYPE_TYPEDBYREF) {
4468 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid use of byref type at 0x%04x", ctx->ip_offset));
4469 return;
4472 if (type->type == MONO_TYPE_VOID) {
4473 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid use of void type at 0x%04x", ctx->ip_offset));
4474 return;
4477 if (check_overflow (ctx))
4478 set_stack_value (ctx, stack_push (ctx), &mono_defaults.uint32_class->byval_arg, FALSE);
4481 /* Stack top can be of any type, the runtime doesn't care and treat everything as an int. */
4482 static void
4483 do_localloc (VerifyContext *ctx)
4485 ILStackDesc *top;
4487 if (ctx->eval.size != 1) {
4488 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Stack must have only size item in localloc at 0x%04x", ctx->ip_offset));
4489 return;
4492 if (in_any_exception_block (ctx->header, ctx->ip_offset)) {
4493 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Stack must have only size item in localloc at 0x%04x", ctx->ip_offset));
4494 return;
4497 /*TODO verify top type*/
4498 top = stack_pop (ctx);
4500 set_stack_value (ctx, stack_push (ctx), &mono_defaults.int_class->byval_arg, FALSE);
4501 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Instruction localloc in never verifiable at 0x%04x", ctx->ip_offset));
4504 static void
4505 do_ldstr (VerifyContext *ctx, guint32 token)
4507 if (mono_metadata_token_code (token) != MONO_TOKEN_STRING) {
4508 ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid string token %x at 0x%04x", token, ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE);
4509 return;
4512 if (!ctx->image->dynamic && mono_metadata_token_index (token) >= ctx->image->heap_us.size) {
4513 ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid string index %x at 0x%04x", token, ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE);
4514 return;
4517 if (check_overflow (ctx))
4518 stack_push_val (ctx, TYPE_COMPLEX, &mono_defaults.string_class->byval_arg);
4521 static void
4522 do_refanyval (VerifyContext *ctx, int token)
4524 ILStackDesc *top;
4525 MonoType *type;
4526 if (!check_underflow (ctx, 1))
4527 return;
4529 if (!(type = get_boxable_mono_type (ctx, token, "refanyval")))
4530 return;
4532 top = stack_pop (ctx);
4534 if (top->stype != TYPE_PTR || top->type->type != MONO_TYPE_TYPEDBYREF)
4535 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));
4537 set_stack_value (ctx, stack_push (ctx), type, TRUE);
4540 static void
4541 do_refanytype (VerifyContext *ctx)
4543 ILStackDesc *top;
4545 if (!check_underflow (ctx, 1))
4546 return;
4548 top = stack_pop (ctx);
4550 if (top->stype != TYPE_PTR || top->type->type != MONO_TYPE_TYPEDBYREF)
4551 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));
4553 set_stack_value (ctx, stack_push (ctx), &mono_defaults.typehandle_class->byval_arg, FALSE);
4557 static void
4558 do_mkrefany (VerifyContext *ctx, int token)
4560 ILStackDesc *top;
4561 MonoType *type;
4562 if (!check_underflow (ctx, 1))
4563 return;
4565 if (!(type = get_boxable_mono_type (ctx, token, "refanyval")))
4566 return;
4568 top = stack_pop (ctx);
4570 if (stack_slot_is_managed_mutability_pointer (top))
4571 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use a readonly pointer with mkrefany at 0x%04x", ctx->ip_offset));
4573 if (!stack_slot_is_managed_pointer (top)) {
4574 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));
4575 }else {
4576 MonoType *stack_type = mono_type_get_type_byval (top->type);
4577 if (MONO_TYPE_IS_REFERENCE (type) && !mono_metadata_type_equal (type, stack_type))
4578 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Type not compatible for mkrefany at 0x%04x", ctx->ip_offset));
4580 if (!MONO_TYPE_IS_REFERENCE (type) && !verify_type_compatibility_full (ctx, type, stack_type, TRUE))
4581 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Type not compatible for mkrefany at 0x%04x", ctx->ip_offset));
4584 set_stack_value (ctx, stack_push (ctx), &mono_defaults.typed_reference_class->byval_arg, FALSE);
4587 static void
4588 do_ckfinite (VerifyContext *ctx)
4590 ILStackDesc *top;
4591 if (!check_underflow (ctx, 1))
4592 return;
4594 top = stack_pop (ctx);
4596 if (stack_slot_get_underlying_type (top) != TYPE_R8)
4597 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));
4598 stack_push_stack_val (ctx, top);
4601 * merge_stacks:
4602 * Merge the stacks and perform compat checks. The merge check if types of @from are mergeable with type of @to
4604 * @from holds new values for a given control path
4605 * @to holds the current values of a given control path
4607 * TODO we can eliminate the from argument as all callers pass &ctx->eval
4609 static void
4610 merge_stacks (VerifyContext *ctx, ILCodeDesc *from, ILCodeDesc *to, gboolean start, gboolean external)
4612 int i, j, k;
4613 stack_init (ctx, to);
4615 if (start) {
4616 if (to->flags == IL_CODE_FLAG_NOT_PROCESSED)
4617 from->size = 0;
4618 else
4619 stack_copy (&ctx->eval, to);
4620 goto end_verify;
4621 } else if (!(to->flags & IL_CODE_STACK_MERGED)) {
4622 stack_copy (to, &ctx->eval);
4623 goto end_verify;
4625 VERIFIER_DEBUG ( printf ("performing stack merge %d x %d\n", from->size, to->size); );
4627 if (from->size != to->size) {
4628 VERIFIER_DEBUG ( printf ("different stack sizes %d x %d at 0x%04x\n", from->size, to->size, ctx->ip_offset); );
4629 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));
4630 goto end_verify;
4633 //FIXME we need to preserve CMMP attributes
4634 //FIXME we must take null literals into consideration.
4635 for (i = 0; i < from->size; ++i) {
4636 ILStackDesc *new_slot = from->stack + i;
4637 ILStackDesc *old_slot = to->stack + i;
4638 MonoType *new_type = mono_type_from_stack_slot (new_slot);
4639 MonoType *old_type = mono_type_from_stack_slot (old_slot);
4640 MonoClass *old_class = mono_class_from_mono_type (old_type);
4641 MonoClass *new_class = mono_class_from_mono_type (new_type);
4642 MonoClass *match_class = NULL;
4644 // S := T then U = S (new value is compatible with current value, keep current)
4645 if (verify_stack_type_compatibility (ctx, old_type, new_slot)) {
4646 copy_stack_value (new_slot, old_slot);
4647 continue;
4650 // T := S then U = T (old value is compatible with current value, use new)
4651 if (verify_stack_type_compatibility (ctx, new_type, old_slot)) {
4652 copy_stack_value (old_slot, new_slot);
4653 continue;
4656 if (mono_type_is_generic_argument (old_type) || mono_type_is_generic_argument (new_type)) {
4657 char *old_name = stack_slot_full_name (old_slot);
4658 char *new_name = stack_slot_full_name (new_slot);
4659 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));
4660 g_free (old_name);
4661 g_free (new_name);
4662 goto end_verify;
4665 //both are reference types, use closest common super type
4666 if (!mono_class_from_mono_type (old_type)->valuetype
4667 && !mono_class_from_mono_type (new_type)->valuetype
4668 && !stack_slot_is_managed_pointer (old_slot)
4669 && !stack_slot_is_managed_pointer (new_slot)) {
4671 for (j = MIN (old_class->idepth, new_class->idepth) - 1; j > 0; --j) {
4672 if (mono_metadata_type_equal (&old_class->supertypes [j]->byval_arg, &new_class->supertypes [j]->byval_arg)) {
4673 match_class = old_class->supertypes [j];
4674 goto match_found;
4678 mono_class_setup_interfaces (old_class);
4679 for (j = 0; j < old_class->interface_count; ++j) {
4680 for (k = 0; k < new_class->interface_count; ++k) {
4681 if (mono_metadata_type_equal (&old_class->interfaces [j]->byval_arg, &new_class->interfaces [k]->byval_arg)) {
4682 match_class = old_class->interfaces [j];
4683 goto match_found;
4688 //No decent super type found, use object
4689 match_class = mono_defaults.object_class;
4690 goto match_found;
4691 } 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)) {
4692 match_class = mono_defaults.object_class;
4693 goto match_found;
4697 char *old_name = stack_slot_full_name (old_slot);
4698 char *new_name = stack_slot_full_name (new_slot);
4699 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));
4700 g_free (old_name);
4701 g_free (new_name);
4703 set_stack_value (ctx, old_slot, &new_class->byval_arg, stack_slot_is_managed_pointer (old_slot));
4704 goto end_verify;
4706 match_found:
4707 g_assert (match_class);
4708 set_stack_value (ctx, old_slot, &match_class->byval_arg, stack_slot_is_managed_pointer (old_slot));
4709 set_stack_value (ctx, new_slot, &match_class->byval_arg, stack_slot_is_managed_pointer (old_slot));
4710 continue;
4713 end_verify:
4714 if (external)
4715 to->flags |= IL_CODE_FLAG_WAS_TARGET;
4716 to->flags |= IL_CODE_STACK_MERGED;
4719 #define HANDLER_START(clause) ((clause)->flags == MONO_EXCEPTION_CLAUSE_FILTER ? (clause)->data.filter_offset : clause->handler_offset)
4720 #define IS_CATCH_OR_FILTER(clause) ((clause)->flags == MONO_EXCEPTION_CLAUSE_FILTER || (clause)->flags == MONO_EXCEPTION_CLAUSE_NONE)
4723 * is_clause_in_range :
4725 * Returns TRUE if either the protected block or the handler of @clause is in the @start - @end range.
4727 static gboolean
4728 is_clause_in_range (MonoExceptionClause *clause, guint32 start, guint32 end)
4730 if (clause->try_offset >= start && clause->try_offset < end)
4731 return TRUE;
4732 if (HANDLER_START (clause) >= start && HANDLER_START (clause) < end)
4733 return TRUE;
4734 return FALSE;
4738 * is_clause_inside_range :
4740 * Returns TRUE if @clause lies completely inside the @start - @end range.
4742 static gboolean
4743 is_clause_inside_range (MonoExceptionClause *clause, guint32 start, guint32 end)
4745 if (clause->try_offset < start || (clause->try_offset + clause->try_len) > end)
4746 return FALSE;
4747 if (HANDLER_START (clause) < start || (clause->handler_offset + clause->handler_len) > end)
4748 return FALSE;
4749 return TRUE;
4753 * is_clause_nested :
4755 * Returns TRUE if @nested is nested in @clause.
4757 static gboolean
4758 is_clause_nested (MonoExceptionClause *clause, MonoExceptionClause *nested)
4760 if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER && is_clause_inside_range (nested, clause->data.filter_offset, clause->handler_offset))
4761 return TRUE;
4762 return is_clause_inside_range (nested, clause->try_offset, clause->try_offset + clause->try_len) ||
4763 is_clause_inside_range (nested, clause->handler_offset, clause->handler_offset + clause->handler_len);
4766 /* Test the relationship between 2 exception clauses. Follow P.1 12.4.2.7 of ECMA
4767 * the each pair of exception must have the following properties:
4768 * - one is fully nested on another (the outer must not be a filter clause) (the nested one must come earlier)
4769 * - completely disjoin (none of the 3 regions of each entry overlap with the other 3)
4770 * - mutual protection (protected block is EXACT the same, handlers are disjoin and all handler are catch or all handler are filter)
4772 static void
4773 verify_clause_relationship (VerifyContext *ctx, MonoExceptionClause *clause, MonoExceptionClause *to_test)
4775 /*clause is nested*/
4776 if (to_test->flags == MONO_EXCEPTION_CLAUSE_FILTER && is_clause_inside_range (clause, to_test->data.filter_offset, to_test->handler_offset)) {
4777 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Exception clause inside filter"));
4778 return;
4781 /*wrong nesting order.*/
4782 if (is_clause_nested (clause, to_test)) {
4783 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Nested exception clause appears after enclosing clause"));
4784 return;
4787 /*mutual protection*/
4788 if (clause->try_offset == to_test->try_offset && clause->try_len == to_test->try_len) {
4789 /*handlers are not disjoint*/
4790 if (is_clause_in_range (to_test, HANDLER_START (clause), clause->handler_offset + clause->handler_len)) {
4791 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Exception handlers overlap"));
4792 return;
4794 /* handlers are not catch or filter */
4795 if (!IS_CATCH_OR_FILTER (clause) || !IS_CATCH_OR_FILTER (to_test)) {
4796 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Exception clauses with shared protected block are neither catch or filter"));
4797 return;
4799 /*OK*/
4800 return;
4803 /*not completelly disjoint*/
4804 if ((is_clause_in_range (to_test, clause->try_offset, clause->try_offset + clause->try_len) ||
4805 is_clause_in_range (to_test, HANDLER_START (clause), clause->handler_offset + clause->handler_len)) && !is_clause_nested (to_test, clause))
4806 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Exception clauses overlap"));
4809 #define code_bounds_check(size) \
4810 if (ip + size > end) {\
4811 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Code overrun starting with 0x%x at 0x%04x", *ip, ctx.ip_offset)); \
4812 break; \
4816 * FIXME: need to distinguish between valid and verifiable.
4817 * Need to keep track of types on the stack.
4818 * Verify types for opcodes.
4820 GSList*
4821 mono_method_verify (MonoMethod *method, int level)
4823 const unsigned char *ip;
4824 const unsigned char *end;
4825 int i, n, need_merge = 0, start = 0;
4826 guint token, ip_offset = 0, prefix = 0;
4827 MonoGenericContext *generic_context = NULL;
4828 MonoImage *image;
4829 VerifyContext ctx;
4830 GSList *tmp;
4831 VERIFIER_DEBUG ( printf ("Verify IL for method %s %s %s\n", method->klass->name_space, method->klass->name, method->name); );
4833 if (method->iflags & (METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL | METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
4834 (method->flags & (METHOD_ATTRIBUTE_PINVOKE_IMPL | METHOD_ATTRIBUTE_ABSTRACT))) {
4835 return NULL;
4838 memset (&ctx, 0, sizeof (VerifyContext));
4840 //FIXME use mono_method_get_signature_full
4841 ctx.signature = mono_method_signature (method);
4842 if (!ctx.signature) {
4843 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Could not decode method signature"));
4844 return ctx.list;
4846 ctx.header = mono_method_get_header (method);
4847 if (!ctx.header) {
4848 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Could not decode method header"));
4849 return ctx.list;
4851 ctx.method = method;
4852 ip = ctx.header->code;
4853 end = ip + ctx.header->code_size;
4854 ctx.image = image = method->klass->image;
4857 ctx.max_args = ctx.signature->param_count + ctx.signature->hasthis;
4858 ctx.max_stack = ctx.header->max_stack;
4859 ctx.verifiable = ctx.valid = 1;
4860 ctx.level = level;
4862 ctx.code = g_new (ILCodeDesc, ctx.header->code_size);
4863 ctx.code_size = ctx.header->code_size;
4865 memset(ctx.code, 0, sizeof (ILCodeDesc) * ctx.header->code_size);
4868 ctx.num_locals = ctx.header->num_locals;
4869 ctx.locals = g_memdup (ctx.header->locals, sizeof (MonoType*) * ctx.header->num_locals);
4871 if (ctx.num_locals > 0 && !ctx.header->init_locals)
4872 CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Method with locals variable but without init locals set"));
4874 ctx.params = g_new (MonoType*, ctx.max_args);
4875 if (ctx.signature->hasthis)
4876 ctx.params [0] = method->klass->valuetype ? &method->klass->this_arg : &method->klass->byval_arg;
4877 memcpy (ctx.params + ctx.signature->hasthis, ctx.signature->params, sizeof (MonoType *) * ctx.signature->param_count);
4879 if (ctx.signature->is_inflated)
4880 ctx.generic_context = generic_context = mono_method_get_context (method);
4882 if (!generic_context && (method->klass->generic_container || method->is_generic)) {
4883 if (method->is_generic)
4884 ctx.generic_context = generic_context = &(mono_method_get_generic_container (method)->context);
4885 else
4886 ctx.generic_context = generic_context = &method->klass->generic_container->context;
4889 for (i = 0; i < ctx.num_locals; ++i)
4890 ctx.locals [i] = mono_class_inflate_generic_type (ctx.locals [i], ctx.generic_context);
4891 for (i = 0; i < ctx.max_args; ++i)
4892 ctx.params [i] = mono_class_inflate_generic_type (ctx.params [i], ctx.generic_context);
4893 stack_init (&ctx, &ctx.eval);
4895 for (i = 0; i < ctx.num_locals; ++i) {
4896 if (!mono_type_is_valid_in_context (&ctx, ctx.locals [i])) {
4897 /*TODO use the last error message to provide better feedback. */
4898 ADD_VERIFY_ERROR2 (&ctx, g_strdup_printf ("Invalid local variable %d", i), MONO_EXCEPTION_BAD_IMAGE);
4899 break;
4903 for (i = 0; i < ctx.max_args; ++i) {
4904 if (!mono_type_is_valid_in_context (&ctx, ctx.params [i])) {
4905 /*TODO use the last error message to provide better feedback. */
4906 ADD_VERIFY_ERROR2 (&ctx, g_strdup_printf ("Invalid parameter %d", i), MONO_EXCEPTION_BAD_IMAGE);
4907 break;
4911 if (!ctx.valid)
4912 goto cleanup;
4914 for (i = 0; i < ctx.header->num_clauses && ctx.valid; ++i) {
4915 MonoExceptionClause *clause = ctx.header->clauses + i;
4916 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); );
4918 if (clause->try_offset > ctx.code_size || clause->try_offset + clause->try_len > ctx.code_size)
4919 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("try clause out of bounds at 0x%04x", clause->try_offset));
4921 if (clause->try_len <= 0)
4922 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("try clause len <= 0 at 0x%04x", clause->try_offset));
4924 if (clause->handler_offset > ctx.code_size || clause->handler_offset + clause->handler_len > ctx.code_size)
4925 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("handler clause out of bounds at 0x%04x", clause->try_offset));
4927 if (clause->handler_len <= 0)
4928 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("try clause len <= 0 at 0x%04x", clause->try_offset));
4930 if (clause->try_offset < clause->handler_offset && clause->try_offset + clause->try_len > HANDLER_START (clause))
4931 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("try block (at 0x%04x) includes handler block (at 0x%04x)", clause->try_offset, clause->handler_offset));
4933 for (n = i + 1; n < ctx.header->num_clauses && ctx.valid; ++n)
4934 verify_clause_relationship (&ctx, clause, ctx.header->clauses + n);
4936 if (!ctx.valid)
4937 break;
4939 ctx.code [clause->try_offset].flags |= IL_CODE_FLAG_WAS_TARGET;
4940 if (clause->try_offset + clause->try_len < ctx.code_size)
4941 ctx.code [clause->try_offset + clause->try_len].flags |= IL_CODE_FLAG_WAS_TARGET;
4942 if (clause->handler_offset + clause->handler_len < ctx.code_size)
4943 ctx.code [clause->handler_offset + clause->handler_len].flags |= IL_CODE_FLAG_WAS_TARGET;
4945 if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE) {
4946 init_stack_with_value_at_exception_boundary (&ctx, ctx.code + clause->handler_offset, clause->data.catch_class);
4948 else if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
4949 init_stack_with_value_at_exception_boundary (&ctx, ctx.code + clause->data.filter_offset, mono_defaults.exception_class);
4950 init_stack_with_value_at_exception_boundary (&ctx, ctx.code + clause->handler_offset, mono_defaults.exception_class);
4954 while (ip < end && ctx.valid) {
4955 ctx.ip_offset = ip_offset = ip - ctx.header->code;
4957 /*We need to check against fallthrou in and out of protected blocks.
4958 * For fallout we check the once a protected block ends, if the start flag is not set.
4959 * Likewise for fallthru in, we check if ip is the start of a protected block and start is not set
4960 * TODO convert these checks to be done using flags and not this loop
4962 for (i = 0; i < ctx.header->num_clauses && ctx.valid; ++i) {
4963 MonoExceptionClause *clause = ctx.header->clauses + i;
4965 if ((clause->try_offset + clause->try_len == ip_offset) && start == 0) {
4966 CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("fallthru off try block at 0x%04x", ip_offset));
4967 start = 1;
4970 if ((clause->handler_offset + clause->handler_len == ip_offset) && start == 0) {
4971 if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER)
4972 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("fallout of handler block at 0x%04x", ip_offset));
4973 else
4974 CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("fallout of handler block at 0x%04x", ip_offset));
4975 start = 1;
4978 if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER && clause->handler_offset == ip_offset && start == 0) {
4979 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("fallout of filter block at 0x%04x", ip_offset));
4980 start = 1;
4983 if (clause->handler_offset == ip_offset && start == 0) {
4984 CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("fallthru handler block at 0x%04x", ip_offset));
4985 start = 1;
4988 if (clause->try_offset == ip_offset && ctx.eval.size > 0 && start == 0) {
4989 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Try to enter try block with a non-empty stack at 0x%04x", ip_offset));
4990 start = 1;
4994 if (!ctx.valid)
4995 break;
4997 if (need_merge) {
4998 VERIFIER_DEBUG ( printf ("extra merge needed! 0x%04x \n", ctx.target); );
4999 merge_stacks (&ctx, &ctx.eval, &ctx.code [ctx.target], FALSE, TRUE);
5000 need_merge = 0;
5002 merge_stacks (&ctx, &ctx.eval, &ctx.code[ip_offset], start, FALSE);
5003 start = 0;
5005 /*TODO we can fast detect a forward branch or exception block targeting code after prefix, we should fail fast*/
5006 #ifdef MONO_VERIFIER_DEBUG
5008 char *discode;
5009 discode = mono_disasm_code_one (NULL, method, ip, NULL);
5010 discode [strlen (discode) - 1] = 0; /* no \n */
5011 g_print ("[%d] %-29s (%d)\n", ip_offset, discode, ctx.eval.size);
5012 g_free (discode);
5014 dump_stack_state (&ctx.code [ip_offset]);
5015 dump_stack_state (&ctx.eval);
5016 #endif
5018 switch (*ip) {
5019 case CEE_NOP:
5020 case CEE_BREAK:
5021 ++ip;
5022 break;
5024 case CEE_LDARG_0:
5025 case CEE_LDARG_1:
5026 case CEE_LDARG_2:
5027 case CEE_LDARG_3:
5028 push_arg (&ctx, *ip - CEE_LDARG_0, FALSE);
5029 ++ip;
5030 break;
5032 case CEE_LDARG_S:
5033 case CEE_LDARGA_S:
5034 code_bounds_check (2);
5035 push_arg (&ctx, ip [1], *ip == CEE_LDARGA_S);
5036 ip += 2;
5037 break;
5039 case CEE_ADD_OVF_UN:
5040 do_binop (&ctx, *ip, add_ovf_un_table);
5041 ++ip;
5042 break;
5044 case CEE_SUB_OVF_UN:
5045 do_binop (&ctx, *ip, sub_ovf_un_table);
5046 ++ip;
5047 break;
5049 case CEE_ADD_OVF:
5050 case CEE_SUB_OVF:
5051 case CEE_MUL_OVF:
5052 case CEE_MUL_OVF_UN:
5053 do_binop (&ctx, *ip, bin_ovf_table);
5054 ++ip;
5055 break;
5057 case CEE_ADD:
5058 do_binop (&ctx, *ip, add_table);
5059 ++ip;
5060 break;
5062 case CEE_SUB:
5063 do_binop (&ctx, *ip, sub_table);
5064 ++ip;
5065 break;
5067 case CEE_MUL:
5068 case CEE_DIV:
5069 case CEE_REM:
5070 do_binop (&ctx, *ip, bin_op_table);
5071 ++ip;
5072 break;
5074 case CEE_AND:
5075 case CEE_DIV_UN:
5076 case CEE_OR:
5077 case CEE_REM_UN:
5078 case CEE_XOR:
5079 do_binop (&ctx, *ip, int_bin_op_table);
5080 ++ip;
5081 break;
5083 case CEE_SHL:
5084 case CEE_SHR:
5085 case CEE_SHR_UN:
5086 do_binop (&ctx, *ip, shift_op_table);
5087 ++ip;
5088 break;
5090 case CEE_POP:
5091 if (!check_underflow (&ctx, 1))
5092 break;
5093 stack_pop_safe (&ctx);
5094 ++ip;
5095 break;
5097 case CEE_RET:
5098 do_ret (&ctx);
5099 ++ip;
5100 start = 1;
5101 break;
5103 case CEE_LDLOC_0:
5104 case CEE_LDLOC_1:
5105 case CEE_LDLOC_2:
5106 case CEE_LDLOC_3:
5107 /*TODO support definite assignment verification? */
5108 push_local (&ctx, *ip - CEE_LDLOC_0, FALSE);
5109 ++ip;
5110 break;
5112 case CEE_STLOC_0:
5113 case CEE_STLOC_1:
5114 case CEE_STLOC_2:
5115 case CEE_STLOC_3:
5116 store_local (&ctx, *ip - CEE_STLOC_0);
5117 ++ip;
5118 break;
5120 case CEE_STLOC_S:
5121 code_bounds_check (2);
5122 store_local (&ctx, ip [1]);
5123 ip += 2;
5124 break;
5126 case CEE_STARG_S:
5127 code_bounds_check (2);
5128 store_arg (&ctx, ip [1]);
5129 ip += 2;
5130 break;
5132 case CEE_LDC_I4_M1:
5133 case CEE_LDC_I4_0:
5134 case CEE_LDC_I4_1:
5135 case CEE_LDC_I4_2:
5136 case CEE_LDC_I4_3:
5137 case CEE_LDC_I4_4:
5138 case CEE_LDC_I4_5:
5139 case CEE_LDC_I4_6:
5140 case CEE_LDC_I4_7:
5141 case CEE_LDC_I4_8:
5142 if (check_overflow (&ctx))
5143 stack_push_val (&ctx, TYPE_I4, &mono_defaults.int32_class->byval_arg);
5144 ++ip;
5145 break;
5147 case CEE_LDC_I4_S:
5148 code_bounds_check (2);
5149 if (check_overflow (&ctx))
5150 stack_push_val (&ctx, TYPE_I4, &mono_defaults.int32_class->byval_arg);
5151 ip += 2;
5152 break;
5154 case CEE_LDC_I4:
5155 code_bounds_check (5);
5156 if (check_overflow (&ctx))
5157 stack_push_val (&ctx,TYPE_I4, &mono_defaults.int32_class->byval_arg);
5158 ip += 5;
5159 break;
5161 case CEE_LDC_I8:
5162 code_bounds_check (9);
5163 if (check_overflow (&ctx))
5164 stack_push_val (&ctx,TYPE_I8, &mono_defaults.int64_class->byval_arg);
5165 ip += 9;
5166 break;
5168 case CEE_LDC_R4:
5169 code_bounds_check (5);
5170 if (check_overflow (&ctx))
5171 stack_push_val (&ctx, TYPE_R8, &mono_defaults.double_class->byval_arg);
5172 ip += 5;
5173 break;
5175 case CEE_LDC_R8:
5176 code_bounds_check (9);
5177 if (check_overflow (&ctx))
5178 stack_push_val (&ctx, TYPE_R8, &mono_defaults.double_class->byval_arg);
5179 ip += 9;
5180 break;
5182 case CEE_LDNULL:
5183 if (check_overflow (&ctx))
5184 stack_push_val (&ctx, TYPE_COMPLEX | NULL_LITERAL_MASK, &mono_defaults.object_class->byval_arg);
5185 ++ip;
5186 break;
5188 case CEE_BEQ_S:
5189 case CEE_BNE_UN_S:
5190 code_bounds_check (2);
5191 do_branch_op (&ctx, (signed char)ip [1] + 2, cmp_br_eq_op);
5192 ip += 2;
5193 need_merge = 1;
5194 break;
5196 case CEE_BGE_S:
5197 case CEE_BGT_S:
5198 case CEE_BLE_S:
5199 case CEE_BLT_S:
5200 case CEE_BGE_UN_S:
5201 case CEE_BGT_UN_S:
5202 case CEE_BLE_UN_S:
5203 case CEE_BLT_UN_S:
5204 code_bounds_check (2);
5205 do_branch_op (&ctx, (signed char)ip [1] + 2, cmp_br_op);
5206 ip += 2;
5207 need_merge = 1;
5208 break;
5210 case CEE_BEQ:
5211 case CEE_BNE_UN:
5212 code_bounds_check (5);
5213 do_branch_op (&ctx, (gint32)read32 (ip + 1) + 5, cmp_br_eq_op);
5214 ip += 5;
5215 need_merge = 1;
5216 break;
5218 case CEE_BGE:
5219 case CEE_BGT:
5220 case CEE_BLE:
5221 case CEE_BLT:
5222 case CEE_BGE_UN:
5223 case CEE_BGT_UN:
5224 case CEE_BLE_UN:
5225 case CEE_BLT_UN:
5226 code_bounds_check (5);
5227 do_branch_op (&ctx, (gint32)read32 (ip + 1) + 5, cmp_br_op);
5228 ip += 5;
5229 need_merge = 1;
5230 break;
5232 case CEE_LDLOC_S:
5233 case CEE_LDLOCA_S:
5234 code_bounds_check (2);
5235 push_local (&ctx, ip[1], *ip == CEE_LDLOCA_S);
5236 ip += 2;
5237 break;
5239 /* FIXME: warn/error instead? */
5240 case CEE_UNUSED99:
5241 ++ip;
5242 break;
5244 case CEE_DUP: {
5245 ILStackDesc * top;
5246 if (!check_underflow (&ctx, 1))
5247 break;
5248 if (!check_overflow (&ctx))
5249 break;
5250 top = stack_pop_safe (&ctx);
5251 copy_stack_value (stack_push (&ctx), top);
5252 copy_stack_value (stack_push (&ctx), top);
5253 ++ip;
5254 break;
5257 case CEE_JMP:
5258 code_bounds_check (5);
5259 if (ctx.eval.size)
5260 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Eval stack must be empty in jmp at 0x%04x", ip_offset));
5261 token = read32 (ip + 1);
5262 if (in_any_block (ctx.header, ip_offset))
5263 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("jmp cannot escape exception blocks at 0x%04x", ip_offset));
5265 CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Intruction jmp is not verifiable at 0x%04x", ctx.ip_offset));
5267 * FIXME: check signature, retval, arguments etc.
5269 ip += 5;
5270 break;
5271 case CEE_CALL:
5272 case CEE_CALLVIRT:
5273 code_bounds_check (5);
5274 do_invoke_method (&ctx, read32 (ip + 1), *ip == CEE_CALLVIRT);
5275 ip += 5;
5276 break;
5278 case CEE_CALLI:
5279 code_bounds_check (5);
5280 token = read32 (ip + 1);
5282 * FIXME: check signature, retval, arguments etc.
5283 * FIXME: check requirements for tail call
5285 CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Intruction calli is not verifiable at 0x%04x", ctx.ip_offset));
5286 ip += 5;
5287 break;
5288 case CEE_BR_S:
5289 code_bounds_check (2);
5290 do_static_branch (&ctx, (signed char)ip [1] + 2);
5291 need_merge = 1;
5292 ip += 2;
5293 start = 1;
5294 break;
5296 case CEE_BRFALSE_S:
5297 case CEE_BRTRUE_S:
5298 code_bounds_check (2);
5299 do_boolean_branch_op (&ctx, (signed char)ip [1] + 2);
5300 ip += 2;
5301 need_merge = 1;
5302 break;
5304 case CEE_BR:
5305 code_bounds_check (5);
5306 do_static_branch (&ctx, (gint32)read32 (ip + 1) + 5);
5307 need_merge = 1;
5308 ip += 5;
5309 start = 1;
5310 break;
5312 case CEE_BRFALSE:
5313 case CEE_BRTRUE:
5314 code_bounds_check (5);
5315 do_boolean_branch_op (&ctx, (gint32)read32 (ip + 1) + 5);
5316 ip += 5;
5317 need_merge = 1;
5318 break;
5320 case CEE_SWITCH:
5321 code_bounds_check (5);
5322 n = read32 (ip + 1);
5323 code_bounds_check (5 + sizeof (guint32) * n);
5325 do_switch (&ctx, n, (ip + 5));
5326 start = 1;
5327 ip += 5 + sizeof (guint32) * n;
5328 break;
5330 case CEE_LDIND_I1:
5331 case CEE_LDIND_U1:
5332 case CEE_LDIND_I2:
5333 case CEE_LDIND_U2:
5334 case CEE_LDIND_I4:
5335 case CEE_LDIND_U4:
5336 case CEE_LDIND_I8:
5337 case CEE_LDIND_I:
5338 case CEE_LDIND_R4:
5339 case CEE_LDIND_R8:
5340 case CEE_LDIND_REF:
5341 do_load_indirect (&ctx, *ip);
5342 ++ip;
5343 break;
5345 case CEE_STIND_REF:
5346 case CEE_STIND_I1:
5347 case CEE_STIND_I2:
5348 case CEE_STIND_I4:
5349 case CEE_STIND_I8:
5350 case CEE_STIND_R4:
5351 case CEE_STIND_R8:
5352 case CEE_STIND_I:
5353 do_store_indirect (&ctx, *ip);
5354 ++ip;
5355 break;
5357 case CEE_NOT:
5358 case CEE_NEG:
5359 do_unary_math_op (&ctx, *ip);
5360 ++ip;
5361 break;
5363 case CEE_CONV_I1:
5364 case CEE_CONV_I2:
5365 case CEE_CONV_I4:
5366 case CEE_CONV_U1:
5367 case CEE_CONV_U2:
5368 case CEE_CONV_U4:
5369 do_conversion (&ctx, TYPE_I4);
5370 ++ip;
5371 break;
5373 case CEE_CONV_I8:
5374 case CEE_CONV_U8:
5375 do_conversion (&ctx, TYPE_I8);
5376 ++ip;
5377 break;
5379 case CEE_CONV_R4:
5380 case CEE_CONV_R8:
5381 case CEE_CONV_R_UN:
5382 do_conversion (&ctx, TYPE_R8);
5383 ++ip;
5384 break;
5386 case CEE_CONV_I:
5387 case CEE_CONV_U:
5388 do_conversion (&ctx, TYPE_NATIVE_INT);
5389 ++ip;
5390 break;
5392 case CEE_CPOBJ:
5393 code_bounds_check (5);
5394 do_cpobj (&ctx, read32 (ip + 1));
5395 ip += 5;
5396 break;
5398 case CEE_LDOBJ:
5399 code_bounds_check (5);
5400 do_ldobj_value (&ctx, read32 (ip + 1));
5401 ip += 5;
5402 break;
5404 case CEE_LDSTR:
5405 code_bounds_check (5);
5406 do_ldstr (&ctx, read32 (ip + 1));
5407 ip += 5;
5408 break;
5410 case CEE_NEWOBJ:
5411 code_bounds_check (5);
5412 do_newobj (&ctx, read32 (ip + 1));
5413 ip += 5;
5414 break;
5416 case CEE_CASTCLASS:
5417 case CEE_ISINST:
5418 code_bounds_check (5);
5419 do_cast (&ctx, read32 (ip + 1), *ip == CEE_CASTCLASS ? "castclass" : "isinst");
5420 ip += 5;
5421 break;
5423 case CEE_UNUSED58:
5424 case CEE_UNUSED1:
5425 ++ip; /* warn, error ? */
5426 break;
5428 case CEE_UNBOX:
5429 code_bounds_check (5);
5430 do_unbox_value (&ctx, read32 (ip + 1));
5431 ip += 5;
5432 break;
5434 case CEE_THROW:
5435 do_throw (&ctx);
5436 start = 1;
5437 ++ip;
5438 break;
5440 case CEE_LDFLD:
5441 case CEE_LDFLDA:
5442 code_bounds_check (5);
5443 do_push_field (&ctx, read32 (ip + 1), *ip == CEE_LDFLDA);
5444 ip += 5;
5445 break;
5447 case CEE_LDSFLD:
5448 case CEE_LDSFLDA:
5449 code_bounds_check (5);
5450 do_push_static_field (&ctx, read32 (ip + 1), *ip == CEE_LDSFLDA);
5451 ip += 5;
5452 break;
5454 case CEE_STFLD:
5455 code_bounds_check (5);
5456 do_store_field (&ctx, read32 (ip + 1));
5457 ip += 5;
5458 break;
5460 case CEE_STSFLD:
5461 code_bounds_check (5);
5462 do_store_static_field (&ctx, read32 (ip + 1));
5463 ip += 5;
5464 break;
5466 case CEE_STOBJ:
5467 code_bounds_check (5);
5468 do_stobj (&ctx, read32 (ip + 1));
5469 ip += 5;
5470 break;
5472 case CEE_CONV_OVF_I1_UN:
5473 case CEE_CONV_OVF_I2_UN:
5474 case CEE_CONV_OVF_I4_UN:
5475 case CEE_CONV_OVF_U1_UN:
5476 case CEE_CONV_OVF_U2_UN:
5477 case CEE_CONV_OVF_U4_UN:
5478 do_conversion (&ctx, TYPE_I4);
5479 ++ip;
5480 break;
5482 case CEE_CONV_OVF_I8_UN:
5483 case CEE_CONV_OVF_U8_UN:
5484 do_conversion (&ctx, TYPE_I8);
5485 ++ip;
5486 break;
5488 case CEE_CONV_OVF_I_UN:
5489 case CEE_CONV_OVF_U_UN:
5490 do_conversion (&ctx, TYPE_NATIVE_INT);
5491 ++ip;
5492 break;
5494 case CEE_BOX:
5495 code_bounds_check (5);
5496 do_box_value (&ctx, read32 (ip + 1));
5497 ip += 5;
5498 break;
5500 case CEE_NEWARR:
5501 code_bounds_check (5);
5502 do_newarr (&ctx, read32 (ip + 1));
5503 ip += 5;
5504 break;
5506 case CEE_LDLEN:
5507 do_ldlen (&ctx);
5508 ++ip;
5509 break;
5511 case CEE_LDELEMA:
5512 code_bounds_check (5);
5513 do_ldelema (&ctx, read32 (ip + 1));
5514 ip += 5;
5515 break;
5517 case CEE_LDELEM_I1:
5518 case CEE_LDELEM_U1:
5519 case CEE_LDELEM_I2:
5520 case CEE_LDELEM_U2:
5521 case CEE_LDELEM_I4:
5522 case CEE_LDELEM_U4:
5523 case CEE_LDELEM_I8:
5524 case CEE_LDELEM_I:
5525 case CEE_LDELEM_R4:
5526 case CEE_LDELEM_R8:
5527 case CEE_LDELEM_REF:
5528 do_ldelem (&ctx, *ip, 0);
5529 ++ip;
5530 break;
5532 case CEE_STELEM_I:
5533 case CEE_STELEM_I1:
5534 case CEE_STELEM_I2:
5535 case CEE_STELEM_I4:
5536 case CEE_STELEM_I8:
5537 case CEE_STELEM_R4:
5538 case CEE_STELEM_R8:
5539 case CEE_STELEM_REF:
5540 do_stelem (&ctx, *ip, 0);
5541 ++ip;
5542 break;
5544 case CEE_LDELEM_ANY:
5545 code_bounds_check (5);
5546 do_ldelem (&ctx, *ip, read32 (ip + 1));
5547 ip += 5;
5548 break;
5550 case CEE_STELEM_ANY:
5551 code_bounds_check (5);
5552 do_stelem (&ctx, *ip, read32 (ip + 1));
5553 ip += 5;
5554 break;
5556 case CEE_UNBOX_ANY:
5557 code_bounds_check (5);
5558 do_unbox_any (&ctx, read32 (ip + 1));
5559 ip += 5;
5560 break;
5562 case CEE_CONV_OVF_I1:
5563 case CEE_CONV_OVF_U1:
5564 case CEE_CONV_OVF_I2:
5565 case CEE_CONV_OVF_U2:
5566 case CEE_CONV_OVF_I4:
5567 case CEE_CONV_OVF_U4:
5568 do_conversion (&ctx, TYPE_I4);
5569 ++ip;
5570 break;
5572 case CEE_CONV_OVF_I8:
5573 case CEE_CONV_OVF_U8:
5574 do_conversion (&ctx, TYPE_I8);
5575 ++ip;
5576 break;
5578 case CEE_CONV_OVF_I:
5579 case CEE_CONV_OVF_U:
5580 do_conversion (&ctx, TYPE_NATIVE_INT);
5581 ++ip;
5582 break;
5584 case CEE_REFANYVAL:
5585 code_bounds_check (5);
5586 do_refanyval (&ctx, read32 (ip + 1));
5587 ip += 5;
5588 break;
5590 case CEE_CKFINITE:
5591 do_ckfinite (&ctx);
5592 ++ip;
5593 break;
5595 case CEE_MKREFANY:
5596 code_bounds_check (5);
5597 do_mkrefany (&ctx, read32 (ip + 1));
5598 ip += 5;
5599 break;
5601 case CEE_LDTOKEN:
5602 code_bounds_check (5);
5603 do_load_token (&ctx, read32 (ip + 1));
5604 ip += 5;
5605 break;
5607 case CEE_ENDFINALLY:
5608 if (!is_correct_endfinally (ctx.header, ip_offset))
5609 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("endfinally must be used inside a finally/fault handler at 0x%04x", ctx.ip_offset));
5610 ctx.eval.size = 0;
5611 start = 1;
5612 ++ip;
5613 break;
5615 case CEE_LEAVE:
5616 code_bounds_check (5);
5617 do_leave (&ctx, read32 (ip + 1) + 5);
5618 ip += 5;
5619 start = 1;
5620 break;
5622 case CEE_LEAVE_S:
5623 code_bounds_check (2);
5624 do_leave (&ctx, (signed char)ip [1] + 2);
5625 ip += 2;
5626 start = 1;
5627 break;
5629 case CEE_PREFIX1:
5630 code_bounds_check (2);
5631 ++ip;
5632 switch (*ip) {
5633 case CEE_STLOC:
5634 code_bounds_check (3);
5635 store_local (&ctx, read16 (ip + 1));
5636 ip += 3;
5637 break;
5639 case CEE_CEQ:
5640 do_cmp_op (&ctx, cmp_br_eq_op, *ip);
5641 ++ip;
5642 break;
5644 case CEE_CGT:
5645 case CEE_CGT_UN:
5646 case CEE_CLT:
5647 case CEE_CLT_UN:
5648 do_cmp_op (&ctx, cmp_br_op, *ip);
5649 ++ip;
5650 break;
5652 case CEE_STARG:
5653 code_bounds_check (3);
5654 store_arg (&ctx, read16 (ip + 1) );
5655 ip += 3;
5656 break;
5659 case CEE_ARGLIST:
5660 check_overflow (&ctx);
5661 if (ctx.signature->call_convention != MONO_CALL_VARARG)
5662 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Cannot use arglist on method without VARGARG calling convention at 0x%04x", ctx.ip_offset));
5663 set_stack_value (&ctx, stack_push (&ctx), &mono_defaults.argumenthandle_class->byval_arg, FALSE);
5664 ++ip;
5665 break;
5667 case CEE_LDFTN:
5668 code_bounds_check (5);
5669 do_load_function_ptr (&ctx, read32 (ip + 1), FALSE);
5670 ip += 5;
5671 break;
5673 case CEE_LDVIRTFTN:
5674 code_bounds_check (5);
5675 do_load_function_ptr (&ctx, read32 (ip + 1), TRUE);
5676 ip += 5;
5677 break;
5679 case CEE_UNUSED56:
5680 ++ip;
5681 break;
5683 case CEE_LDARG:
5684 case CEE_LDARGA:
5685 code_bounds_check (3);
5686 push_arg (&ctx, read16 (ip + 1), *ip == CEE_LDARGA);
5687 ip += 3;
5688 break;
5690 case CEE_LDLOC:
5691 case CEE_LDLOCA:
5692 code_bounds_check (3);
5693 push_local (&ctx, read16 (ip + 1), *ip == CEE_LDLOCA);
5694 ip += 3;
5695 break;
5697 case CEE_LOCALLOC:
5698 do_localloc (&ctx);
5699 ++ip;
5700 break;
5702 case CEE_UNUSED57:
5703 ++ip;
5704 break;
5705 case CEE_ENDFILTER:
5706 do_endfilter (&ctx);
5707 start = 1;
5708 ++ip;
5709 break;
5710 case CEE_UNALIGNED_:
5711 code_bounds_check (2);
5712 prefix |= PREFIX_UNALIGNED;
5713 ip += 2;
5714 break;
5715 case CEE_VOLATILE_:
5716 prefix |= PREFIX_VOLATILE;
5717 ++ip;
5718 break;
5719 case CEE_TAIL_:
5720 prefix |= PREFIX_TAIL;
5721 ++ip;
5722 if (ip < end && (*ip != CEE_CALL && *ip != CEE_CALLI && *ip != CEE_CALLVIRT))
5723 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("tail prefix must be used only with call opcodes at 0x%04x", ip_offset));
5724 break;
5726 case CEE_INITOBJ:
5727 code_bounds_check (5);
5728 do_initobj (&ctx, read32 (ip + 1));
5729 ip += 5;
5730 break;
5732 case CEE_CONSTRAINED_:
5733 code_bounds_check (5);
5734 ctx.constrained_type = get_boxable_mono_type (&ctx, read32 (ip + 1), "constrained.");
5735 prefix |= PREFIX_CONSTRAINED;
5736 ip += 5;
5737 break;
5739 case CEE_READONLY_:
5740 prefix |= PREFIX_READONLY;
5741 ip++;
5742 break;
5744 case CEE_CPBLK:
5745 CLEAR_PREFIX (&ctx, PREFIX_UNALIGNED | PREFIX_VOLATILE);
5746 if (!check_underflow (&ctx, 3))
5747 break;
5748 CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Instruction cpblk is not verifiable at 0x%04x", ctx.ip_offset));
5749 ip++;
5750 break;
5752 case CEE_INITBLK:
5753 CLEAR_PREFIX (&ctx, PREFIX_UNALIGNED | PREFIX_VOLATILE);
5754 if (!check_underflow (&ctx, 3))
5755 break;
5756 CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Instruction initblk is not verifiable at 0x%04x", ctx.ip_offset));
5757 ip++;
5758 break;
5760 case CEE_NO_:
5761 ip += 2;
5762 break;
5763 case CEE_RETHROW:
5764 if (!is_correct_rethrow (ctx.header, ip_offset))
5765 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("rethrow must be used inside a catch handler at 0x%04x", ctx.ip_offset));
5766 ctx.eval.size = 0;
5767 start = 1;
5768 ++ip;
5769 break;
5770 case CEE_UNUSED:
5771 ++ip;
5772 break;
5774 case CEE_SIZEOF:
5775 code_bounds_check (5);
5776 do_sizeof (&ctx, read32 (ip + 1));
5777 ip += 5;
5778 break;
5780 case CEE_REFANYTYPE:
5781 do_refanytype (&ctx);
5782 ++ip;
5783 break;
5785 default:
5786 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid instruction FE %x at 0x%04x", *ip, ctx.ip_offset));
5787 ++ip;
5789 break;
5791 default:
5792 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid instruction %x at 0x%04x", *ip, ctx.ip_offset));
5793 ++ip;
5796 /*TODO we can fast detect a forward branch or exception block targeting code after prefix, we should fail fast*/
5797 if (prefix) {
5798 if (!ctx.prefix_set) //first prefix
5799 ctx.code [ctx.ip_offset].flags |= IL_CODE_FLAG_SEEN;
5800 ctx.prefix_set |= prefix;
5801 ctx.has_flags = TRUE;
5802 prefix = 0;
5803 } else {
5804 if (!ctx.has_flags)
5805 ctx.code [ctx.ip_offset].flags |= IL_CODE_FLAG_SEEN;
5807 if (ctx.prefix_set & PREFIX_CONSTRAINED)
5808 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid instruction after constrained prefix at 0x%04x", ctx.ip_offset));
5809 if (ctx.prefix_set & PREFIX_READONLY)
5810 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid instruction after readonly prefix at 0x%04x", ctx.ip_offset));
5811 if (ctx.prefix_set & PREFIX_VOLATILE)
5812 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid instruction after volatile prefix at 0x%04x", ctx.ip_offset));
5813 if (ctx.prefix_set & PREFIX_UNALIGNED)
5814 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid instruction after unaligned prefix at 0x%04x", ctx.ip_offset));
5815 ctx.prefix_set = prefix = 0;
5816 ctx.has_flags = FALSE;
5820 * if ip != end we overflowed: mark as error.
5822 if ((ip != end || !start) && ctx.verifiable && !ctx.list) {
5823 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Run ahead of method code at 0x%04x", ip_offset));
5826 /*We should guard against the last decoded opcode, otherwise we might add errors that doesn't make sense.*/
5827 for (i = 0; i < ctx.code_size && i < ip_offset; ++i) {
5828 if (ctx.code [i].flags & IL_CODE_FLAG_WAS_TARGET) {
5829 if (!(ctx.code [i].flags & IL_CODE_FLAG_SEEN))
5830 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Branch or exception block target middle of intruction at 0x%04x", i));
5832 if (ctx.code [i].flags & IL_CODE_DELEGATE_SEQUENCE)
5833 CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Branch to delegate code sequence at 0x%04x", i));
5835 if ((ctx.code [i].flags & IL_CODE_LDFTN_DELEGATE_NONFINAL_VIRTUAL) && ctx.has_this_store)
5836 CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Invalid ldftn with virtual function in method with stdarg 0 at 0x%04x", i));
5838 if ((ctx.code [i].flags & IL_CODE_CALL_NONFINAL_VIRTUAL) && ctx.has_this_store)
5839 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));
5842 if (mono_method_is_constructor (ctx.method) && !ctx.super_ctor_called && !ctx.method->klass->valuetype && ctx.method->klass != mono_defaults.object_class)
5843 CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Constructor not calling super\n"));
5845 cleanup:
5846 if (ctx.code) {
5847 for (i = 0; i < ctx.header->code_size; ++i) {
5848 if (ctx.code [i].stack)
5849 g_free (ctx.code [i].stack);
5853 for (tmp = ctx.funptrs; tmp; tmp = tmp->next)
5854 g_free (tmp->data);
5855 g_slist_free (ctx.funptrs);
5857 for (tmp = ctx.exception_types; tmp; tmp = tmp->next)
5858 mono_metadata_free_type (tmp->data);
5859 g_slist_free (ctx.exception_types);
5861 for (i = 0; i < ctx.num_locals; ++i)
5862 mono_metadata_free_type (ctx.locals [i]);
5863 for (i = 0; i < ctx.max_args; ++i)
5864 mono_metadata_free_type (ctx.params [i]);
5866 if (ctx.eval.stack)
5867 g_free (ctx.eval.stack);
5868 if (ctx.code)
5869 g_free (ctx.code);
5870 g_free (ctx.locals);
5871 g_free (ctx.params);
5873 return ctx.list;
5876 char*
5877 mono_verify_corlib ()
5879 /* This is a public API function so cannot be removed */
5880 return NULL;
5884 * Returns true if @method needs to be verified.
5887 gboolean
5888 mono_verifier_is_enabled_for_method (MonoMethod *method)
5890 return mono_verifier_is_enabled_for_class (method->klass) && method->wrapper_type == MONO_WRAPPER_NONE;
5894 * Returns true if @klass need to be verified.
5897 gboolean
5898 mono_verifier_is_enabled_for_class (MonoClass *klass)
5900 return verify_all || (verifier_mode > MONO_VERIFIER_MODE_OFF && !klass->image->assembly->in_gac && klass->image != mono_defaults.corlib);
5903 gboolean
5904 mono_verifier_is_enabled_for_image (MonoImage *image)
5906 return verify_all || verifier_mode > MONO_VERIFIER_MODE_OFF;
5909 gboolean
5910 mono_verifier_is_method_full_trust (MonoMethod *method)
5912 return mono_verifier_is_class_full_trust (method->klass);
5916 * Returns if @klass is under full trust or not.
5918 * TODO This code doesn't take CAS into account.
5920 * Under verify_all all user code must be verifiable if no security option was set
5923 gboolean
5924 mono_verifier_is_class_full_trust (MonoClass *klass)
5926 /* under CoreCLR code is trusted if it is part of the "platform" otherwise all code inside the GAC is trusted */
5927 gboolean trusted_location = (mono_security_get_mode () != MONO_SECURITY_MODE_CORE_CLR) ?
5928 klass->image->assembly->in_gac : mono_security_core_clr_is_platform_image (klass->image);
5930 if (verify_all && verifier_mode == MONO_VERIFIER_MODE_OFF)
5931 return trusted_location || klass->image == mono_defaults.corlib;
5932 return verifier_mode < MONO_VERIFIER_MODE_VERIFIABLE || trusted_location || klass->image == mono_defaults.corlib;
5935 GSList*
5936 mono_method_verify_with_current_settings (MonoMethod *method, gboolean skip_visibility)
5938 return mono_method_verify (method,
5939 (verifier_mode != MONO_VERIFIER_MODE_STRICT ? MONO_VERIFY_NON_STRICT: 0)
5940 | (!mono_verifier_is_method_full_trust (method) ? MONO_VERIFY_FAIL_FAST : 0)
5941 | (skip_visibility ? MONO_VERIFY_SKIP_VISIBILITY : 0));
5944 static int
5945 get_field_end (MonoClassField *field)
5947 int align;
5948 int size = mono_type_size (field->type, &align);
5949 if (size == 0)
5950 size = 4; /*FIXME Is this a safe bet?*/
5951 return size + field->offset;
5954 static gboolean
5955 verify_class_for_overlapping_reference_fields (MonoClass *class)
5957 int i, j;
5958 gboolean is_fulltrust = mono_verifier_is_class_full_trust (class);
5959 if (!((class->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_EXPLICIT_LAYOUT) || !class->has_references)
5960 return TRUE;
5962 //we must check for stuff overlapping reference fields
5963 for (i = 0; i < class->field.count; ++i) {
5964 MonoClassField *field = &class->fields [i];
5965 int fieldEnd = get_field_end (field);
5966 gboolean is_valuetype = !MONO_TYPE_IS_REFERENCE (field->type);
5967 if (mono_field_is_deleted (field) || (field->type->attrs & FIELD_ATTRIBUTE_STATIC))
5968 continue;
5970 for (j = i + 1; j < class->field.count; ++j) {
5971 MonoClassField *other = &class->fields [j];
5972 int otherEnd = get_field_end (other);
5973 if (mono_field_is_deleted (other) || (is_valuetype && !MONO_TYPE_IS_REFERENCE (other->type)) || (other->type->attrs & FIELD_ATTRIBUTE_STATIC))
5974 continue;
5976 if (!is_valuetype && MONO_TYPE_IS_REFERENCE (other->type) && field->offset == other->offset && is_fulltrust)
5977 continue;
5979 if ((otherEnd > field->offset && otherEnd <= fieldEnd) || (other->offset >= field->offset && other->offset < fieldEnd))
5980 return FALSE;
5983 return TRUE;
5987 * Check if the class is verifiable.
5989 * Right now there are no conditions that make a class a valid but not verifiable. Both overlapping reference
5990 * field and invalid generic instantiation are fatal errors.
5992 * This method must be safe to be called from mono_class_init and all code must be carefull about that.
5995 gboolean
5996 mono_verifier_verify_class (MonoClass *class)
5998 if (class->generic_container && (class->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_EXPLICIT_LAYOUT)
5999 return FALSE;
6000 if (!verify_class_for_overlapping_reference_fields (class))
6001 return FALSE;
6003 if (class->generic_class && !mono_class_is_valid_generic_instantiation (NULL, class))
6004 return FALSE;
6005 return TRUE;
6007 #else
6009 gboolean
6010 mono_verifier_verify_class (MonoClass *class)
6012 /* The verifier was disabled at compile time */
6013 return TRUE;
6016 GSList*
6017 mono_method_verify_with_current_settings (MonoMethod *method, gboolean skip_visibility)
6019 /* The verifier was disabled at compile time */
6020 return NULL;
6023 gboolean
6024 mono_verifier_is_class_full_trust (MonoClass *klass)
6026 /* The verifier was disabled at compile time */
6027 return TRUE;
6030 gboolean
6031 mono_verifier_is_method_full_trust (MonoMethod *method)
6033 /* The verifier was disabled at compile time */
6034 return TRUE;
6037 gboolean
6038 mono_verifier_is_enabled_for_image (MonoImage *image)
6040 /* The verifier was disabled at compile time */
6041 return FALSE;
6044 gboolean
6045 mono_verifier_is_enabled_for_class (MonoClass *klass)
6047 /* The verifier was disabled at compile time */
6048 return FALSE;
6051 gboolean
6052 mono_verifier_is_enabled_for_method (MonoMethod *method)
6054 /* The verifier was disabled at compile time */
6055 return FALSE;
6058 GSList*
6059 mono_method_verify (MonoMethod *method, int level)
6061 /* The verifier was disabled at compile time */
6062 return NULL;
6065 void
6066 mono_free_verify_list (GSList *list)
6068 /* The verifier was disabled at compile time */
6069 /* will always be null if verifier is disabled */
6072 GSList*
6073 mono_image_verify_tables (MonoImage *image, int level)
6075 /* The verifier was disabled at compile time */
6076 return NULL;
6078 #endif