2009-11-23 Andreas Faerber <andreas.faerber@web.de>
[mono.git] / mono / metadata / verify.c
blob304657571b5503db2e4976e326028214c2661243
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 MonoError error;
469 MonoType *result;
471 result = mono_class_inflate_generic_type_checked (type, context, &error);
472 if (!mono_error_ok (&error)) {
473 mono_error_cleanup (&error);
474 return NULL;
476 return result;
479 * Test if @candidate is a subtype of @target using the minimal possible information
480 * TODO move the code for non finished TypeBuilders to here.
482 static gboolean
483 mono_class_is_constraint_compatible (MonoClass *candidate, MonoClass *target)
485 if (candidate == target)
486 return TRUE;
487 if (target == mono_defaults.object_class)
488 return TRUE;
490 //setup_supertypes don't mono_class_init anything
491 mono_class_setup_supertypes (candidate);
492 mono_class_setup_supertypes (target);
494 if (mono_class_has_parent (candidate, target))
495 return TRUE;
497 //if target is not a supertype it must be an interface
498 if (!MONO_CLASS_IS_INTERFACE (target))
499 return FALSE;
501 if (candidate->image->dynamic && !candidate->wastypebuilder) {
502 MonoReflectionTypeBuilder *tb = candidate->reflection_info;
503 int j;
504 if (tb->interfaces) {
505 for (j = mono_array_length (tb->interfaces) - 1; j >= 0; --j) {
506 MonoReflectionType *iface = mono_array_get (tb->interfaces, MonoReflectionType*, j);
507 MonoClass *ifaceClass = mono_class_from_mono_type (iface->type);
508 if (mono_class_is_constraint_compatible (ifaceClass, target)) {
509 return TRUE;
513 return FALSE;
515 return mono_class_interface_implements_interface (candidate, target);
518 static gboolean
519 is_valid_generic_instantiation (MonoGenericContainer *gc, MonoGenericContext *context, MonoGenericInst *ginst)
521 MonoError error;
522 int i;
524 if (ginst->type_argc != gc->type_argc)
525 return FALSE;
527 for (i = 0; i < gc->type_argc; ++i) {
528 MonoGenericParamInfo *param_info = mono_generic_container_get_param_info (gc, i);
529 MonoClass *paramClass;
530 MonoClass **constraints;
532 if (!param_info->constraints && !(param_info->flags & GENERIC_PARAMETER_ATTRIBUTE_SPECIAL_CONSTRAINTS_MASK))
533 continue;
534 if (mono_type_is_generic_argument (ginst->type_argv [i]))
535 continue; //it's not our job to validate type variables
537 paramClass = mono_class_from_mono_type (ginst->type_argv [i]);
539 if (paramClass->exception_type != MONO_EXCEPTION_NONE)
540 return FALSE;
542 /*it's not safe to call mono_class_init from here*/
543 if (paramClass->generic_class && !paramClass->inited) {
544 if (!mono_class_is_valid_generic_instantiation (NULL, paramClass))
545 return FALSE;
548 if ((param_info->flags & GENERIC_PARAMETER_ATTRIBUTE_VALUE_TYPE_CONSTRAINT) && (!paramClass->valuetype || mono_class_is_nullable (paramClass)))
549 return FALSE;
551 if ((param_info->flags & GENERIC_PARAMETER_ATTRIBUTE_REFERENCE_TYPE_CONSTRAINT) && paramClass->valuetype)
552 return FALSE;
554 if ((param_info->flags & GENERIC_PARAMETER_ATTRIBUTE_CONSTRUCTOR_CONSTRAINT) && !paramClass->valuetype && !mono_class_has_default_constructor (paramClass))
555 return FALSE;
557 if (!param_info->constraints)
558 continue;
560 for (constraints = param_info->constraints; *constraints; ++constraints) {
561 MonoClass *ctr = *constraints;
562 MonoType *inflated;
564 inflated = mono_class_inflate_generic_type_checked (&ctr->byval_arg, context, &error);
565 if (!mono_error_ok (&error)) {
566 mono_error_cleanup (&error);
567 return FALSE;
569 ctr = mono_class_from_mono_type (inflated);
570 mono_metadata_free_type (inflated);
572 if (!mono_class_is_constraint_compatible (paramClass, ctr))
573 return FALSE;
576 return TRUE;
580 * Return true if @candidate is constraint compatible with @target.
582 * This means that @candidate constraints are a super set of @target constaints
584 static gboolean
585 mono_generic_param_is_constraint_compatible (VerifyContext *ctx, MonoGenericParam *target, MonoGenericParam *candidate, MonoGenericContext *context)
587 MonoGenericParamInfo *tinfo = mono_generic_param_info (target);
588 MonoGenericParamInfo *cinfo = mono_generic_param_info (candidate);
590 int tmask = tinfo->flags & GENERIC_PARAMETER_ATTRIBUTE_SPECIAL_CONSTRAINTS_MASK;
591 int cmask = cinfo->flags & GENERIC_PARAMETER_ATTRIBUTE_SPECIAL_CONSTRAINTS_MASK;
592 if ((tmask & cmask) != tmask)
593 return FALSE;
595 if (tinfo->constraints) {
596 MonoClass **target_class, **candidate_class;
597 if (!cinfo->constraints)
598 return FALSE;
599 for (target_class = tinfo->constraints; *target_class; ++target_class) {
600 MonoClass *tc;
601 MonoType *inflated = verifier_inflate_type (ctx, &(*target_class)->byval_arg, context);
602 if (!inflated)
603 return FALSE;
604 tc = mono_class_from_mono_type (inflated);
605 mono_metadata_free_type (inflated);
607 for (candidate_class = cinfo->constraints; *candidate_class; ++candidate_class) {
608 MonoClass *cc;
609 inflated = verifier_inflate_type (ctx, &(*candidate_class)->byval_arg, ctx->generic_context);
610 if (!inflated)
611 return FALSE;
612 cc = mono_class_from_mono_type (inflated);
613 mono_metadata_free_type (inflated);
615 if (mono_class_is_assignable_from (tc, cc))
616 break;
618 if (!*candidate_class)
619 return FALSE;
622 return TRUE;
625 static MonoGenericParam*
626 verifier_get_generic_param_from_type (VerifyContext *ctx, MonoType *type)
628 MonoGenericContainer *gc;
629 MonoMethod *method = ctx->method;
630 int num;
632 num = mono_type_get_generic_param_num (type);
634 if (type->type == MONO_TYPE_VAR) {
635 MonoClass *gtd = method->klass;
636 if (gtd->generic_class)
637 gtd = gtd->generic_class->container_class;
638 gc = gtd->generic_container;
639 } else { //MVAR
640 MonoMethod *gmd = method;
641 if (method->is_inflated)
642 gmd = ((MonoMethodInflated*)method)->declaring;
643 gc = mono_method_get_generic_container (gmd);
645 if (!gc)
646 return FALSE;
647 return mono_generic_container_get_param (gc, num);
653 * Verify if @type is valid for the given @ctx verification context.
654 * this function checks for VAR and MVAR types that are invalid under the current verifier,
655 * This means that it either
657 static gboolean
658 is_valid_type_in_context (VerifyContext *ctx, MonoType *type)
660 return mono_type_is_valid_type_in_context (type, ctx->generic_context);
663 static gboolean
664 is_valid_generic_instantiation_in_context (VerifyContext *ctx, MonoGenericInst *ginst)
666 int i;
667 for (i = 0; i < ginst->type_argc; ++i) {
668 MonoType *type = ginst->type_argv [i];
669 if (!is_valid_type_in_context (ctx, type))
670 return FALSE;
672 return TRUE;
675 static gboolean
676 generic_arguments_respect_constraints (VerifyContext *ctx, MonoGenericContainer *gc, MonoGenericContext *context, MonoGenericInst *ginst)
678 int i;
679 for (i = 0; i < ginst->type_argc; ++i) {
680 MonoType *type = ginst->type_argv [i];
681 MonoGenericParam *target = mono_generic_container_get_param (gc, i);
682 MonoGenericParam *candidate;
684 if (!mono_type_is_generic_argument (type))
685 continue;
687 if (!is_valid_type_in_context (ctx, type))
688 return FALSE;
690 candidate = verifier_get_generic_param_from_type (ctx, type);
692 if (!mono_generic_param_is_constraint_compatible (ctx, target, candidate, context))
693 return FALSE;
695 return TRUE;
698 static gboolean
699 mono_method_repect_method_constraints (VerifyContext *ctx, MonoMethod *method)
701 MonoMethodInflated *gmethod = (MonoMethodInflated *)method;
702 MonoGenericInst *ginst = gmethod->context.method_inst;
703 MonoGenericContainer *gc = mono_method_get_generic_container (gmethod->declaring);
704 return !gc || generic_arguments_respect_constraints (ctx, gc, &gmethod->context, ginst);
707 static gboolean
708 mono_class_repect_method_constraints (VerifyContext *ctx, MonoClass *klass)
710 MonoGenericClass *gklass = klass->generic_class;
711 MonoGenericInst *ginst = gklass->context.class_inst;
712 MonoGenericContainer *gc = gklass->container_class->generic_container;
713 return !gc || generic_arguments_respect_constraints (ctx, gc, &gklass->context, ginst);
716 static gboolean
717 mono_method_is_valid_generic_instantiation (VerifyContext *ctx, MonoMethod *method)
719 MonoMethodInflated *gmethod = (MonoMethodInflated *)method;
720 MonoGenericInst *ginst = gmethod->context.method_inst;
721 MonoGenericContainer *gc = mono_method_get_generic_container (gmethod->declaring);
722 if (!gc) /*non-generic inflated method - it's part of a generic type */
723 return TRUE;
724 if (ctx && !is_valid_generic_instantiation_in_context (ctx, ginst))
725 return FALSE;
726 return is_valid_generic_instantiation (gc, &gmethod->context, ginst);
730 static gboolean
731 mono_class_is_valid_generic_instantiation (VerifyContext *ctx, MonoClass *klass)
733 MonoGenericClass *gklass = klass->generic_class;
734 MonoGenericInst *ginst = gklass->context.class_inst;
735 MonoGenericContainer *gc = gklass->container_class->generic_container;
736 if (ctx && !is_valid_generic_instantiation_in_context (ctx, ginst))
737 return FALSE;
738 return is_valid_generic_instantiation (gc, &gklass->context, ginst);
741 static gboolean
742 mono_type_is_valid_in_context (VerifyContext *ctx, MonoType *type)
744 MonoClass *klass;
746 if (type == NULL) {
747 ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid null type at 0x%04x", ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE);
748 return FALSE;
751 if (!is_valid_type_in_context (ctx, type)) {
752 char *str = mono_type_full_name (type);
753 ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid generic type (%s%s) (argument out of range or %s is not generic) at 0x%04x",
754 type->type == MONO_TYPE_VAR ? "!" : "!!",
755 str,
756 type->type == MONO_TYPE_VAR ? "class" : "method",
757 ctx->ip_offset),
758 MONO_EXCEPTION_BAD_IMAGE);
759 g_free (str);
760 return FALSE;
763 klass = mono_class_from_mono_type (type);
764 mono_class_init (klass);
765 if (mono_loader_get_last_error () || klass->exception_type != MONO_EXCEPTION_NONE) {
766 if (klass->generic_class && !mono_class_is_valid_generic_instantiation (NULL, klass))
767 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);
768 else
769 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);
770 return FALSE;
773 if (klass->generic_class && klass->generic_class->container_class->exception_type != MONO_EXCEPTION_NONE) {
774 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);
775 return FALSE;
778 if (!klass->generic_class)
779 return TRUE;
781 if (!mono_class_is_valid_generic_instantiation (ctx, klass)) {
782 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);
783 return FALSE;
786 if (!mono_class_repect_method_constraints (ctx, klass)) {
787 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);
788 return FALSE;
791 return TRUE;
794 static verify_result_t
795 mono_method_is_valid_in_context (VerifyContext *ctx, MonoMethod *method)
797 if (!mono_type_is_valid_in_context (ctx, &method->klass->byval_arg))
798 return RESULT_INVALID;
800 if (!method->is_inflated)
801 return RESULT_VALID;
803 if (!mono_method_is_valid_generic_instantiation (ctx, method)) {
804 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);
805 return RESULT_INVALID;
808 if (!mono_method_repect_method_constraints (ctx, method)) {
809 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));
810 return RESULT_UNVERIFIABLE;
812 return RESULT_VALID;
816 static MonoClassField*
817 verifier_load_field (VerifyContext *ctx, int token, MonoClass **out_klass, const char *opcode) {
818 MonoClassField *field;
819 MonoClass *klass = NULL;
821 if (!IS_FIELD_DEF_OR_REF (token) || !token_bounds_check (ctx->image, token)) {
822 ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid field token 0x%08x for %s at 0x%04x", token, opcode, ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE);
823 return NULL;
826 field = mono_field_from_token (ctx->image, token, &klass, ctx->generic_context);
827 if (!field || !field->parent || !klass) {
828 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);
829 return NULL;
832 if (!mono_type_is_valid_in_context (ctx, &klass->byval_arg))
833 return NULL;
835 *out_klass = klass;
836 return field;
839 static MonoMethod*
840 verifier_load_method (VerifyContext *ctx, int token, const char *opcode) {
841 MonoMethod* method;
843 if (!IS_METHOD_DEF_OR_REF_OR_SPEC (token) || !token_bounds_check (ctx->image, token)) {
844 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);
845 return NULL;
848 method = mono_get_method_full (ctx->image, token, NULL, ctx->generic_context);
850 if (!method) {
851 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);
852 return NULL;
855 if (mono_method_is_valid_in_context (ctx, method) == RESULT_INVALID)
856 return NULL;
858 return method;
861 static MonoType*
862 verifier_load_type (VerifyContext *ctx, int token, const char *opcode) {
863 MonoType* type;
865 if (!IS_TYPE_DEF_OR_REF_OR_SPEC (token) || !token_bounds_check (ctx->image, token)) {
866 ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid type token 0x%08x at 0x%04x", token, ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE);
867 return NULL;
870 type = mono_type_get_full (ctx->image, token, ctx->generic_context);
872 if (!type) {
873 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);
874 return NULL;
877 if (!mono_type_is_valid_in_context (ctx, type))
878 return NULL;
880 return type;
884 /* stack_slot_get_type:
886 * Returns the stack type of @value. This value includes POINTER_MASK.
888 * Use this function to checks that account for a managed pointer.
890 static gint32
891 stack_slot_get_type (ILStackDesc *value)
893 return value->stype & RAW_TYPE_MASK;
896 /* stack_slot_get_underlying_type:
898 * Returns the stack type of @value. This value does not include POINTER_MASK.
900 * Use this function is cases where the fact that the value could be a managed pointer is
901 * irrelevant. For example, field load doesn't care about this fact of type on stack.
903 static gint32
904 stack_slot_get_underlying_type (ILStackDesc *value)
906 return value->stype & TYPE_MASK;
909 /* stack_slot_is_managed_pointer:
911 * Returns TRUE is @value is a managed pointer.
913 static gboolean
914 stack_slot_is_managed_pointer (ILStackDesc *value)
916 return (value->stype & POINTER_MASK) == POINTER_MASK;
919 /* stack_slot_is_managed_mutability_pointer:
921 * Returns TRUE is @value is a managed mutability pointer.
923 static G_GNUC_UNUSED gboolean
924 stack_slot_is_managed_mutability_pointer (ILStackDesc *value)
926 return (value->stype & CMMP_MASK) == CMMP_MASK;
929 /* stack_slot_is_null_literal:
931 * Returns TRUE is @value is the null literal.
933 static gboolean
934 stack_slot_is_null_literal (ILStackDesc *value)
936 return (value->stype & NULL_LITERAL_MASK) == NULL_LITERAL_MASK;
940 /* stack_slot_is_this_pointer:
942 * Returns TRUE is @value is the this literal
944 static gboolean
945 stack_slot_is_this_pointer (ILStackDesc *value)
947 return (value->stype & THIS_POINTER_MASK) == THIS_POINTER_MASK;
950 /* stack_slot_is_boxed_value:
952 * Returns TRUE is @value is a boxed value
954 static gboolean
955 stack_slot_is_boxed_value (ILStackDesc *value)
957 return (value->stype & BOXED_MASK) == BOXED_MASK;
960 static const char *
961 stack_slot_get_name (ILStackDesc *value)
963 return type_names [value->stype & TYPE_MASK];
966 #define APPEND_WITH_PREDICATE(PRED,NAME) do {\
967 if (PRED (value)) { \
968 if (!first) \
969 g_string_append (str, ", "); \
970 g_string_append (str, NAME); \
971 first = FALSE; \
972 } } while (0)
974 static char*
975 stack_slot_stack_type_full_name (ILStackDesc *value)
977 GString *str = g_string_new ("");
978 char *result;
980 if ((value->stype & TYPE_MASK) != value->stype) {
981 gboolean first = TRUE;
982 g_string_append(str, "[");
983 APPEND_WITH_PREDICATE (stack_slot_is_this_pointer, "this");
984 APPEND_WITH_PREDICATE (stack_slot_is_boxed_value, "boxed");
985 APPEND_WITH_PREDICATE (stack_slot_is_null_literal, "null");
986 APPEND_WITH_PREDICATE (stack_slot_is_managed_mutability_pointer, "cmmp");
987 APPEND_WITH_PREDICATE (stack_slot_is_managed_pointer, "mp");
988 g_string_append(str, "] ");
991 g_string_append (str, stack_slot_get_name (value));
992 result = str->str;
993 g_string_free (str, FALSE);
994 return result;
997 static char*
998 stack_slot_full_name (ILStackDesc *value)
1000 char *type_name = mono_type_full_name (value->type);
1001 char *stack_name = stack_slot_stack_type_full_name (value);
1002 char *res = g_strdup_printf ("%s (%s)", type_name, stack_name);
1003 g_free (type_name);
1004 g_free (stack_name);
1005 return res;
1008 //////////////////////////////////////////////////////////////////
1009 void
1010 mono_free_verify_list (GSList *list)
1012 MonoVerifyInfoExtended *info;
1013 GSList *tmp;
1015 for (tmp = list; tmp; tmp = tmp->next) {
1016 info = tmp->data;
1017 g_free (info->info.message);
1018 g_free (info);
1020 g_slist_free (list);
1023 #define ADD_ERROR(list,msg) \
1024 do { \
1025 MonoVerifyInfoExtended *vinfo = g_new (MonoVerifyInfoExtended, 1); \
1026 vinfo->info.status = MONO_VERIFY_ERROR; \
1027 vinfo->info.message = (msg); \
1028 (list) = g_slist_prepend ((list), vinfo); \
1029 } while (0)
1031 #define ADD_WARN(list,code,msg) \
1032 do { \
1033 MonoVerifyInfoExtended *vinfo = g_new (MonoVerifyInfoExtended, 1); \
1034 vinfo->info.status = (code); \
1035 vinfo->info.message = (msg); \
1036 (list) = g_slist_prepend ((list), vinfo); \
1037 } while (0)
1039 static const char
1040 valid_cultures[][9] = {
1041 "ar-SA", "ar-IQ", "ar-EG", "ar-LY",
1042 "ar-DZ", "ar-MA", "ar-TN", "ar-OM",
1043 "ar-YE", "ar-SY", "ar-JO", "ar-LB",
1044 "ar-KW", "ar-AE", "ar-BH", "ar-QA",
1045 "bg-BG", "ca-ES", "zh-TW", "zh-CN",
1046 "zh-HK", "zh-SG", "zh-MO", "cs-CZ",
1047 "da-DK", "de-DE", "de-CH", "de-AT",
1048 "de-LU", "de-LI", "el-GR", "en-US",
1049 "en-GB", "en-AU", "en-CA", "en-NZ",
1050 "en-IE", "en-ZA", "en-JM", "en-CB",
1051 "en-BZ", "en-TT", "en-ZW", "en-PH",
1052 "es-ES-Ts", "es-MX", "es-ES-Is", "es-GT",
1053 "es-CR", "es-PA", "es-DO", "es-VE",
1054 "es-CO", "es-PE", "es-AR", "es-EC",
1055 "es-CL", "es-UY", "es-PY", "es-BO",
1056 "es-SV", "es-HN", "es-NI", "es-PR",
1057 "Fi-FI", "fr-FR", "fr-BE", "fr-CA",
1058 "Fr-CH", "fr-LU", "fr-MC", "he-IL",
1059 "hu-HU", "is-IS", "it-IT", "it-CH",
1060 "Ja-JP", "ko-KR", "nl-NL", "nl-BE",
1061 "nb-NO", "nn-NO", "pl-PL", "pt-BR",
1062 "pt-PT", "ro-RO", "ru-RU", "hr-HR",
1063 "Lt-sr-SP", "Cy-sr-SP", "sk-SK", "sq-AL",
1064 "sv-SE", "sv-FI", "th-TH", "tr-TR",
1065 "ur-PK", "id-ID", "uk-UA", "be-BY",
1066 "sl-SI", "et-EE", "lv-LV", "lt-LT",
1067 "fa-IR", "vi-VN", "hy-AM", "Lt-az-AZ",
1068 "Cy-az-AZ",
1069 "eu-ES", "mk-MK", "af-ZA",
1070 "ka-GE", "fo-FO", "hi-IN", "ms-MY",
1071 "ms-BN", "kk-KZ", "ky-KZ", "sw-KE",
1072 "Lt-uz-UZ", "Cy-uz-UZ", "tt-TA", "pa-IN",
1073 "gu-IN", "ta-IN", "te-IN", "kn-IN",
1074 "mr-IN", "sa-IN", "mn-MN", "gl-ES",
1075 "kok-IN", "syr-SY", "div-MV"
1078 static int
1079 is_valid_culture (const char *cname)
1081 int i;
1082 int found;
1084 found = *cname == 0;
1085 for (i = 0; i < G_N_ELEMENTS (valid_cultures); ++i) {
1086 if (g_ascii_strcasecmp (valid_cultures [i], cname)) {
1087 found = 1;
1088 break;
1091 return found;
1094 static int
1095 is_valid_assembly_flags (guint32 flags) {
1096 /* Metadata: 22.1.2 */
1097 flags &= ~(0x8000 | 0x4000); /* ignore reserved bits 0x0030? */
1098 return ((flags == 1) || (flags == 0));
1101 static int
1102 is_valid_blob (MonoImage *image, guint32 blob_index, int notnull)
1104 guint32 size;
1105 const char *p, *blob_end;
1107 if (blob_index >= image->heap_blob.size)
1108 return 0;
1109 p = mono_metadata_blob_heap (image, blob_index);
1110 size = mono_metadata_decode_blob_size (p, &blob_end);
1111 if (blob_index + size + (blob_end-p) > image->heap_blob.size)
1112 return 0;
1113 if (notnull && !size)
1114 return 0;
1115 return 1;
1118 static const char*
1119 is_valid_string (MonoImage *image, guint32 str_index, int notnull)
1121 const char *p, *blob_end, *res;
1123 if (str_index >= image->heap_strings.size)
1124 return NULL;
1125 res = p = mono_metadata_string_heap (image, str_index);
1126 blob_end = mono_metadata_string_heap (image, image->heap_strings.size - 1);
1127 if (notnull && !*p)
1128 return 0;
1130 * FIXME: should check it's a valid utf8 string, too.
1132 while (p <= blob_end) {
1133 if (!*p)
1134 return res;
1135 ++p;
1137 return *p? NULL: res;
1140 static int
1141 is_valid_cls_ident (const char *p)
1144 * FIXME: we need the full unicode glib support for this.
1145 * Check: http://www.unicode.org/unicode/reports/tr15/Identifier.java
1146 * We do the lame thing for now.
1148 if (!isalpha (*p))
1149 return 0;
1150 ++p;
1151 while (*p) {
1152 if (!isalnum (*p) && *p != '_')
1153 return 0;
1154 ++p;
1156 return 1;
1159 static int
1160 is_valid_filename (const char *p)
1162 if (!*p)
1163 return 0;
1164 return strpbrk (p, "\\//:")? 0: 1;
1167 static GSList*
1168 verify_assembly_table (MonoImage *image, GSList *list, int level)
1170 MonoTableInfo *t = &image->tables [MONO_TABLE_ASSEMBLY];
1171 guint32 cols [MONO_ASSEMBLY_SIZE];
1172 const char *p;
1174 if (level & MONO_VERIFY_ERROR) {
1175 if (t->rows > 1)
1176 ADD_ERROR (list, g_strdup ("Assembly table may only have 0 or 1 rows"));
1177 mono_metadata_decode_row (t, 0, cols, MONO_ASSEMBLY_SIZE);
1179 switch (cols [MONO_ASSEMBLY_HASH_ALG]) {
1180 case ASSEMBLY_HASH_NONE:
1181 case ASSEMBLY_HASH_MD5:
1182 case ASSEMBLY_HASH_SHA1:
1183 break;
1184 default:
1185 ADD_ERROR (list, g_strdup_printf ("Hash algorithm 0x%x unknown", cols [MONO_ASSEMBLY_HASH_ALG]));
1188 if (!is_valid_assembly_flags (cols [MONO_ASSEMBLY_FLAGS]))
1189 ADD_ERROR (list, g_strdup_printf ("Invalid flags in assembly: 0x%x", cols [MONO_ASSEMBLY_FLAGS]));
1191 if (!is_valid_blob (image, cols [MONO_ASSEMBLY_PUBLIC_KEY], FALSE))
1192 ADD_ERROR (list, g_strdup ("Assembly public key is an invalid index"));
1194 if (!(p = is_valid_string (image, cols [MONO_ASSEMBLY_NAME], TRUE))) {
1195 ADD_ERROR (list, g_strdup ("Assembly name is invalid"));
1196 } else {
1197 if (strpbrk (p, ":\\/."))
1198 ADD_ERROR (list, g_strdup_printf ("Assembly name `%s' contains invalid chars", p));
1201 if (!(p = is_valid_string (image, cols [MONO_ASSEMBLY_CULTURE], FALSE))) {
1202 ADD_ERROR (list, g_strdup ("Assembly culture is an invalid index"));
1203 } else {
1204 if (!is_valid_culture (p))
1205 ADD_ERROR (list, g_strdup_printf ("Assembly culture `%s' is invalid", p));
1208 return list;
1211 static GSList*
1212 verify_assemblyref_table (MonoImage *image, GSList *list, int level)
1214 MonoTableInfo *t = &image->tables [MONO_TABLE_ASSEMBLYREF];
1215 guint32 cols [MONO_ASSEMBLYREF_SIZE];
1216 const char *p;
1217 int i;
1219 if (level & MONO_VERIFY_ERROR) {
1220 for (i = 0; i < t->rows; ++i) {
1221 mono_metadata_decode_row (t, i, cols, MONO_ASSEMBLYREF_SIZE);
1222 if (!is_valid_assembly_flags (cols [MONO_ASSEMBLYREF_FLAGS]))
1223 ADD_ERROR (list, g_strdup_printf ("Invalid flags in assemblyref row %d: 0x%x", i + 1, cols [MONO_ASSEMBLY_FLAGS]));
1225 if (!is_valid_blob (image, cols [MONO_ASSEMBLYREF_PUBLIC_KEY], FALSE))
1226 ADD_ERROR (list, g_strdup_printf ("AssemblyRef public key in row %d is an invalid index", i + 1));
1228 if (!(p = is_valid_string (image, cols [MONO_ASSEMBLYREF_CULTURE], FALSE))) {
1229 ADD_ERROR (list, g_strdup_printf ("AssemblyRef culture in row %d is invalid", i + 1));
1230 } else {
1231 if (!is_valid_culture (p))
1232 ADD_ERROR (list, g_strdup_printf ("AssemblyRef culture `%s' in row %d is invalid", p, i + 1));
1235 if (cols [MONO_ASSEMBLYREF_HASH_VALUE] && !is_valid_blob (image, cols [MONO_ASSEMBLYREF_HASH_VALUE], TRUE))
1236 ADD_ERROR (list, g_strdup_printf ("AssemblyRef hash value in row %d is invalid or not null and empty", i + 1));
1239 if (level & MONO_VERIFY_WARNING) {
1240 /* check for duplicated rows */
1241 for (i = 0; i < t->rows; ++i) {
1244 return list;
1247 static GSList*
1248 verify_class_layout_table (MonoImage *image, GSList *list, int level)
1250 MonoTableInfo *t = &image->tables [MONO_TABLE_CLASSLAYOUT];
1251 MonoTableInfo *tdef = &image->tables [MONO_TABLE_TYPEDEF];
1252 guint32 cols [MONO_CLASS_LAYOUT_SIZE];
1253 guint32 value, i;
1255 if (level & MONO_VERIFY_ERROR) {
1256 for (i = 0; i < t->rows; ++i) {
1257 mono_metadata_decode_row (t, i, cols, MONO_CLASS_LAYOUT_SIZE);
1259 if (cols [MONO_CLASS_LAYOUT_PARENT] > tdef->rows || !cols [MONO_CLASS_LAYOUT_PARENT]) {
1260 ADD_ERROR (list, g_strdup_printf ("Parent in class layout is invalid in row %d", i + 1));
1261 } else {
1262 value = mono_metadata_decode_row_col (tdef, cols [MONO_CLASS_LAYOUT_PARENT] - 1, MONO_TYPEDEF_FLAGS);
1263 if (value & TYPE_ATTRIBUTE_INTERFACE)
1264 ADD_ERROR (list, g_strdup_printf ("Parent in class layout row %d is an interface", i + 1));
1265 if (value & TYPE_ATTRIBUTE_AUTO_LAYOUT)
1266 ADD_ERROR (list, g_strdup_printf ("Parent in class layout row %d is AutoLayout", i + 1));
1267 if (value & TYPE_ATTRIBUTE_SEQUENTIAL_LAYOUT) {
1268 switch (cols [MONO_CLASS_LAYOUT_PACKING_SIZE]) {
1269 case 0: case 1: case 2: case 4: case 8: case 16:
1270 case 32: case 64: case 128: break;
1271 default:
1272 ADD_ERROR (list, g_strdup_printf ("Packing size %d in class layout row %d is invalid", cols [MONO_CLASS_LAYOUT_PACKING_SIZE], i + 1));
1274 } else if (value & TYPE_ATTRIBUTE_EXPLICIT_LAYOUT) {
1276 * FIXME: LAMESPEC: it claims it must be 0 (it's 1, instead).
1277 if (cols [MONO_CLASS_LAYOUT_PACKING_SIZE])
1278 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));
1282 * FIXME: we need to check that if class size != 0,
1283 * it needs to be greater than the class calculated size.
1284 * If parent is a valuetype it also needs to be smaller than
1285 * 1 MByte (0x100000 bytes).
1286 * To do both these checks we need to load the referenced
1287 * assemblies, though (the spec claims we didn't have to, bah).
1290 * We need to check that the parent types have the same layout
1291 * type as well.
1297 return list;
1300 static GSList*
1301 verify_constant_table (MonoImage *image, GSList *list, int level)
1303 MonoTableInfo *t = &image->tables [MONO_TABLE_CONSTANT];
1304 guint32 cols [MONO_CONSTANT_SIZE];
1305 guint32 value, i;
1306 GHashTable *dups = g_hash_table_new (NULL, NULL);
1308 for (i = 0; i < t->rows; ++i) {
1309 mono_metadata_decode_row (t, i, cols, MONO_CONSTANT_SIZE);
1311 if (level & MONO_VERIFY_ERROR)
1312 if (g_hash_table_lookup (dups, GUINT_TO_POINTER (cols [MONO_CONSTANT_PARENT])))
1313 ADD_ERROR (list, g_strdup_printf ("Parent 0x%08x is duplicated in Constant row %d", cols [MONO_CONSTANT_PARENT], i + 1));
1314 g_hash_table_insert (dups, GUINT_TO_POINTER (cols [MONO_CONSTANT_PARENT]),
1315 GUINT_TO_POINTER (cols [MONO_CONSTANT_PARENT]));
1317 switch (cols [MONO_CONSTANT_TYPE]) {
1318 case MONO_TYPE_U1: /* LAMESPEC: it says I1...*/
1319 case MONO_TYPE_U2:
1320 case MONO_TYPE_U4:
1321 case MONO_TYPE_U8:
1322 if (level & MONO_VERIFY_CLS)
1323 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));
1324 case MONO_TYPE_BOOLEAN:
1325 case MONO_TYPE_CHAR:
1326 case MONO_TYPE_I1:
1327 case MONO_TYPE_I2:
1328 case MONO_TYPE_I4:
1329 case MONO_TYPE_I8:
1330 case MONO_TYPE_R4:
1331 case MONO_TYPE_R8:
1332 case MONO_TYPE_STRING:
1333 case MONO_TYPE_CLASS:
1334 break;
1335 default:
1336 if (level & MONO_VERIFY_ERROR)
1337 ADD_ERROR (list, g_strdup_printf ("Type 0x%x is invalid in Constant row %d", cols [MONO_CONSTANT_TYPE], i + 1));
1339 if (level & MONO_VERIFY_ERROR) {
1340 value = cols [MONO_CONSTANT_PARENT] >> MONO_HASCONSTANT_BITS;
1341 switch (cols [MONO_CONSTANT_PARENT] & MONO_HASCONSTANT_MASK) {
1342 case MONO_HASCONSTANT_FIEDDEF:
1343 if (value > image->tables [MONO_TABLE_FIELD].rows)
1344 ADD_ERROR (list, g_strdup_printf ("Parent (field) is invalid in Constant row %d", i + 1));
1345 break;
1346 case MONO_HASCONSTANT_PARAM:
1347 if (value > image->tables [MONO_TABLE_PARAM].rows)
1348 ADD_ERROR (list, g_strdup_printf ("Parent (param) is invalid in Constant row %d", i + 1));
1349 break;
1350 case MONO_HASCONSTANT_PROPERTY:
1351 if (value > image->tables [MONO_TABLE_PROPERTY].rows)
1352 ADD_ERROR (list, g_strdup_printf ("Parent (property) is invalid in Constant row %d", i + 1));
1353 break;
1354 default:
1355 ADD_ERROR (list, g_strdup_printf ("Parent is invalid in Constant row %d", i + 1));
1356 break;
1359 if (level & MONO_VERIFY_CLS) {
1361 * FIXME: verify types is consistent with the enum type
1362 * is parent is an enum.
1366 g_hash_table_destroy (dups);
1367 return list;
1370 static GSList*
1371 verify_event_map_table (MonoImage *image, GSList *list, int level)
1373 MonoTableInfo *t = &image->tables [MONO_TABLE_EVENTMAP];
1374 guint32 cols [MONO_EVENT_MAP_SIZE];
1375 guint32 i, last_event;
1376 GHashTable *dups = g_hash_table_new (NULL, NULL);
1378 last_event = 0;
1380 for (i = 0; i < t->rows; ++i) {
1381 mono_metadata_decode_row (t, i, cols, MONO_EVENT_MAP_SIZE);
1382 if (level & MONO_VERIFY_ERROR)
1383 if (g_hash_table_lookup (dups, GUINT_TO_POINTER (cols [MONO_EVENT_MAP_PARENT])))
1384 ADD_ERROR (list, g_strdup_printf ("Parent 0x%08x is duplicated in Event Map row %d", cols [MONO_EVENT_MAP_PARENT], i + 1));
1385 g_hash_table_insert (dups, GUINT_TO_POINTER (cols [MONO_EVENT_MAP_PARENT]),
1386 GUINT_TO_POINTER (cols [MONO_EVENT_MAP_PARENT]));
1387 if (level & MONO_VERIFY_ERROR) {
1388 if (cols [MONO_EVENT_MAP_PARENT] > image->tables [MONO_TABLE_TYPEDEF].rows)
1389 ADD_ERROR (list, g_strdup_printf ("Parent 0x%08x is invalid in Event Map row %d", cols [MONO_EVENT_MAP_PARENT], i + 1));
1390 if (cols [MONO_EVENT_MAP_EVENTLIST] > image->tables [MONO_TABLE_EVENT].rows)
1391 ADD_ERROR (list, g_strdup_printf ("EventList 0x%08x is invalid in Event Map row %d", cols [MONO_EVENT_MAP_EVENTLIST], i + 1));
1393 if (cols [MONO_EVENT_MAP_EVENTLIST] <= last_event)
1394 ADD_ERROR (list, g_strdup_printf ("EventList overlap in Event Map row %d", i + 1));
1395 last_event = cols [MONO_EVENT_MAP_EVENTLIST];
1399 g_hash_table_destroy (dups);
1400 return list;
1403 static GSList*
1404 verify_event_table (MonoImage *image, GSList *list, int level)
1406 MonoTableInfo *t = &image->tables [MONO_TABLE_EVENT];
1407 guint32 cols [MONO_EVENT_SIZE];
1408 const char *p;
1409 guint32 value, i;
1411 for (i = 0; i < t->rows; ++i) {
1412 mono_metadata_decode_row (t, i, cols, MONO_EVENT_SIZE);
1414 if (cols [MONO_EVENT_FLAGS] & ~(EVENT_SPECIALNAME|EVENT_RTSPECIALNAME)) {
1415 if (level & MONO_VERIFY_ERROR)
1416 ADD_ERROR (list, g_strdup_printf ("Flags 0x%04x invalid in Event row %d", cols [MONO_EVENT_FLAGS], i + 1));
1418 if (!(p = is_valid_string (image, cols [MONO_EVENT_NAME], TRUE))) {
1419 if (level & MONO_VERIFY_ERROR)
1420 ADD_ERROR (list, g_strdup_printf ("Invalid name in Event row %d", i + 1));
1421 } else {
1422 if (level & MONO_VERIFY_CLS) {
1423 if (!is_valid_cls_ident (p))
1424 ADD_WARN (list, MONO_VERIFY_CLS, g_strdup_printf ("Invalid CLS name '%s` in Event row %d", p, i + 1));
1428 if (level & MONO_VERIFY_ERROR && cols [MONO_EVENT_TYPE]) {
1429 value = cols [MONO_EVENT_TYPE] >> MONO_TYPEDEFORREF_BITS;
1430 switch (cols [MONO_EVENT_TYPE] & MONO_TYPEDEFORREF_MASK) {
1431 case MONO_TYPEDEFORREF_TYPEDEF:
1432 if (!value || value > image->tables [MONO_TABLE_TYPEDEF].rows)
1433 ADD_ERROR (list, g_strdup_printf ("Type invalid in Event row %d", i + 1));
1434 break;
1435 case MONO_TYPEDEFORREF_TYPEREF:
1436 if (!value || value > image->tables [MONO_TABLE_TYPEREF].rows)
1437 ADD_ERROR (list, g_strdup_printf ("Type invalid in Event row %d", i + 1));
1438 break;
1439 case MONO_TYPEDEFORREF_TYPESPEC:
1440 if (!value || value > image->tables [MONO_TABLE_TYPESPEC].rows)
1441 ADD_ERROR (list, g_strdup_printf ("Type invalid in Event row %d", i + 1));
1442 break;
1443 default:
1444 ADD_ERROR (list, g_strdup_printf ("Type invalid in Event row %d", i + 1));
1448 * FIXME: check that there is 1 add and remove row in methodsemantics
1449 * and 0 or 1 raise and 0 or more other (maybe it's better to check for
1450 * these while checking methodsemantics).
1451 * check for duplicated names for the same type [ERROR]
1452 * check for CLS duplicate names for the same type [CLS]
1455 return list;
1458 static GSList*
1459 verify_field_table (MonoImage *image, GSList *list, int level)
1461 MonoTableInfo *t = &image->tables [MONO_TABLE_FIELD];
1462 guint32 cols [MONO_FIELD_SIZE];
1463 const char *p;
1464 guint32 i, flags;
1466 for (i = 0; i < t->rows; ++i) {
1467 mono_metadata_decode_row (t, i, cols, MONO_FIELD_SIZE);
1469 * Check this field has only one owner and that the owner is not
1470 * an interface (done in verify_typedef_table() )
1472 flags = cols [MONO_FIELD_FLAGS];
1473 switch (flags & FIELD_ATTRIBUTE_FIELD_ACCESS_MASK) {
1474 case FIELD_ATTRIBUTE_COMPILER_CONTROLLED:
1475 case FIELD_ATTRIBUTE_PRIVATE:
1476 case FIELD_ATTRIBUTE_FAM_AND_ASSEM:
1477 case FIELD_ATTRIBUTE_ASSEMBLY:
1478 case FIELD_ATTRIBUTE_FAMILY:
1479 case FIELD_ATTRIBUTE_FAM_OR_ASSEM:
1480 case FIELD_ATTRIBUTE_PUBLIC:
1481 break;
1482 default:
1483 if (level & MONO_VERIFY_ERROR)
1484 ADD_ERROR (list, g_strdup_printf ("Invalid access mask in Field row %d", i + 1));
1485 break;
1487 if (level & MONO_VERIFY_ERROR) {
1488 if ((flags & FIELD_ATTRIBUTE_LITERAL) && (flags & FIELD_ATTRIBUTE_INIT_ONLY))
1489 ADD_ERROR (list, g_strdup_printf ("Literal and InitOnly cannot be both set in Field row %d", i + 1));
1490 if ((flags & FIELD_ATTRIBUTE_LITERAL) && !(flags & FIELD_ATTRIBUTE_STATIC))
1491 ADD_ERROR (list, g_strdup_printf ("Literal needs also Static set in Field row %d", i + 1));
1492 if ((flags & FIELD_ATTRIBUTE_RT_SPECIAL_NAME) && !(flags & FIELD_ATTRIBUTE_SPECIAL_NAME))
1493 ADD_ERROR (list, g_strdup_printf ("RTSpecialName needs also SpecialName set in Field row %d", i + 1));
1495 * FIXME: check there is only one owner in the respective table.
1496 * if (flags & FIELD_ATTRIBUTE_HAS_FIELD_MARSHAL)
1497 * if (flags & FIELD_ATTRIBUTE_HAS_DEFAULT)
1498 * if (flags & FIELD_ATTRIBUTE_HAS_FIELD_RVA)
1501 if (!(p = is_valid_string (image, cols [MONO_FIELD_NAME], TRUE))) {
1502 if (level & MONO_VERIFY_ERROR)
1503 ADD_ERROR (list, g_strdup_printf ("Invalid name in Field row %d", i + 1));
1504 } else {
1505 if (level & MONO_VERIFY_CLS) {
1506 if (!is_valid_cls_ident (p))
1507 ADD_WARN (list, MONO_VERIFY_CLS, g_strdup_printf ("Invalid CLS name '%s` in Field row %d", p, i + 1));
1511 * check signature.
1512 * if owner is module needs to be static, access mask needs to be compilercontrolled,
1513 * public or private (not allowed in cls mode).
1514 * if owner is an enum ...
1519 return list;
1522 static GSList*
1523 verify_file_table (MonoImage *image, GSList *list, int level)
1525 MonoTableInfo *t = &image->tables [MONO_TABLE_FILE];
1526 guint32 cols [MONO_FILE_SIZE];
1527 const char *p;
1528 guint32 i;
1529 GHashTable *dups = g_hash_table_new (g_str_hash, g_str_equal);
1531 for (i = 0; i < t->rows; ++i) {
1532 mono_metadata_decode_row (t, i, cols, MONO_FILE_SIZE);
1533 if (level & MONO_VERIFY_ERROR) {
1534 if (cols [MONO_FILE_FLAGS] != FILE_CONTAINS_METADATA && cols [MONO_FILE_FLAGS] != FILE_CONTAINS_NO_METADATA)
1535 ADD_ERROR (list, g_strdup_printf ("Invalid flags in File row %d", i + 1));
1536 if (!is_valid_blob (image, cols [MONO_FILE_HASH_VALUE], TRUE))
1537 ADD_ERROR (list, g_strdup_printf ("File hash value in row %d is invalid or not null and empty", i + 1));
1539 if (!(p = is_valid_string (image, cols [MONO_FILE_NAME], TRUE))) {
1540 if (level & MONO_VERIFY_ERROR)
1541 ADD_ERROR (list, g_strdup_printf ("Invalid name in File row %d", i + 1));
1542 } else {
1543 if (level & MONO_VERIFY_ERROR) {
1544 if (!is_valid_filename (p))
1545 ADD_ERROR (list, g_strdup_printf ("Invalid name '%s` in File row %d", p, i + 1));
1546 else if (g_hash_table_lookup (dups, p)) {
1547 ADD_ERROR (list, g_strdup_printf ("Duplicate name '%s` in File row %d", p, i + 1));
1549 g_hash_table_insert (dups, (gpointer)p, (gpointer)p);
1553 * FIXME: I don't understand what this means:
1554 * If this module contains a row in the Assembly table (that is, if this module "holds the manifest")
1555 * then there shall not be any row in the File table for this module - i.e., no self-reference [ERROR]
1559 if (level & MONO_VERIFY_WARNING) {
1560 if (!t->rows && image->tables [MONO_TABLE_EXPORTEDTYPE].rows)
1561 ADD_WARN (list, MONO_VERIFY_WARNING, g_strdup ("ExportedType table should be empty if File table is empty"));
1563 g_hash_table_destroy (dups);
1564 return list;
1567 static GSList*
1568 verify_moduleref_table (MonoImage *image, GSList *list, int level)
1570 MonoTableInfo *t = &image->tables [MONO_TABLE_MODULEREF];
1571 MonoTableInfo *tfile = &image->tables [MONO_TABLE_FILE];
1572 guint32 cols [MONO_MODULEREF_SIZE];
1573 const char *p, *pf;
1574 guint32 found, i, j, value;
1575 GHashTable *dups = g_hash_table_new (g_str_hash, g_str_equal);
1577 for (i = 0; i < t->rows; ++i) {
1578 mono_metadata_decode_row (t, i, cols, MONO_MODULEREF_SIZE);
1579 if (!(p = is_valid_string (image, cols [MONO_MODULEREF_NAME], TRUE))) {
1580 if (level & MONO_VERIFY_ERROR)
1581 ADD_ERROR (list, g_strdup_printf ("Invalid name in ModuleRef row %d", i + 1));
1582 } else {
1583 if (level & MONO_VERIFY_ERROR) {
1584 if (!is_valid_filename (p))
1585 ADD_ERROR (list, g_strdup_printf ("Invalid name '%s` in ModuleRef row %d", p, i + 1));
1586 else if (g_hash_table_lookup (dups, p)) {
1587 ADD_WARN (list, MONO_VERIFY_WARNING, g_strdup_printf ("Duplicate name '%s` in ModuleRef row %d", p, i + 1));
1588 g_hash_table_insert (dups, (gpointer)p, (gpointer)p);
1589 found = 0;
1590 for (j = 0; j < tfile->rows; ++j) {
1591 value = mono_metadata_decode_row_col (tfile, j, MONO_FILE_NAME);
1592 if ((pf = is_valid_string (image, value, TRUE)))
1593 if (strcmp (p, pf) == 0) {
1594 found = 1;
1595 break;
1598 if (!found)
1599 ADD_ERROR (list, g_strdup_printf ("Name '%s` in ModuleRef row %d doesn't have a match in File table", p, i + 1));
1604 g_hash_table_destroy (dups);
1605 return list;
1608 static GSList*
1609 verify_standalonesig_table (MonoImage *image, GSList *list, int level)
1611 MonoTableInfo *t = &image->tables [MONO_TABLE_STANDALONESIG];
1612 guint32 cols [MONO_STAND_ALONE_SIGNATURE_SIZE];
1613 const char *p;
1614 guint32 i;
1616 for (i = 0; i < t->rows; ++i) {
1617 mono_metadata_decode_row (t, i, cols, MONO_STAND_ALONE_SIGNATURE_SIZE);
1618 if (level & MONO_VERIFY_ERROR) {
1619 if (!is_valid_blob (image, cols [MONO_STAND_ALONE_SIGNATURE], TRUE)) {
1620 ADD_ERROR (list, g_strdup_printf ("Signature is invalid in StandAloneSig row %d", i + 1));
1621 } else {
1622 p = mono_metadata_blob_heap (image, cols [MONO_STAND_ALONE_SIGNATURE]);
1623 /* FIXME: check it's a valid locals or method sig.*/
1627 return list;
1630 GSList*
1631 mono_image_verify_tables (MonoImage *image, int level)
1633 GSList *error_list = NULL;
1635 error_list = verify_assembly_table (image, error_list, level);
1637 * AssemblyOS, AssemblyProcessor, AssemblyRefOs and
1638 * AssemblyRefProcessor should be ignored,
1639 * though we may want to emit a warning, since it should not
1640 * be present in a PE file.
1642 error_list = verify_assemblyref_table (image, error_list, level);
1643 error_list = verify_class_layout_table (image, error_list, level);
1644 error_list = verify_constant_table (image, error_list, level);
1646 * cutom attribute, declsecurity
1648 error_list = verify_event_map_table (image, error_list, level);
1649 error_list = verify_event_table (image, error_list, level);
1650 error_list = verify_field_table (image, error_list, level);
1651 error_list = verify_file_table (image, error_list, level);
1652 error_list = verify_moduleref_table (image, error_list, level);
1653 error_list = verify_standalonesig_table (image, error_list, level);
1655 return g_slist_reverse (error_list);
1658 #define ADD_INVALID(list,msg) \
1659 do { \
1660 MonoVerifyInfoExtended *vinfo = g_new (MonoVerifyInfoExtended, 1); \
1661 vinfo->status = MONO_VERIFY_ERROR; \
1662 vinfo->message = (msg); \
1663 (list) = g_slist_prepend ((list), vinfo); \
1664 /*G_BREAKPOINT ();*/ \
1665 goto invalid_cil; \
1666 } while (0)
1668 #define CHECK_STACK_UNDERFLOW(num) \
1669 do { \
1670 if (cur_stack < (num)) \
1671 ADD_INVALID (list, g_strdup_printf ("Stack underflow at 0x%04x (%d items instead of %d)", ip_offset, cur_stack, (num))); \
1672 } while (0)
1674 #define CHECK_STACK_OVERFLOW() \
1675 do { \
1676 if (cur_stack >= max_stack) \
1677 ADD_INVALID (list, g_strdup_printf ("Maxstack exceeded at 0x%04x", ip_offset)); \
1678 } while (0)
1681 static int
1682 in_any_block (MonoMethodHeader *header, guint offset)
1684 int i;
1685 MonoExceptionClause *clause;
1687 for (i = 0; i < header->num_clauses; ++i) {
1688 clause = &header->clauses [i];
1689 if (MONO_OFFSET_IN_CLAUSE (clause, offset))
1690 return 1;
1691 if (MONO_OFFSET_IN_HANDLER (clause, offset))
1692 return 1;
1693 if (MONO_OFFSET_IN_FILTER (clause, offset))
1694 return 1;
1696 return 0;
1700 * in_any_exception_block:
1702 * Returns TRUE is @offset is part of any exception clause (filter, handler, catch, finally or fault).
1704 static gboolean
1705 in_any_exception_block (MonoMethodHeader *header, guint offset)
1707 int i;
1708 MonoExceptionClause *clause;
1710 for (i = 0; i < header->num_clauses; ++i) {
1711 clause = &header->clauses [i];
1712 if (MONO_OFFSET_IN_HANDLER (clause, offset))
1713 return TRUE;
1714 if (MONO_OFFSET_IN_FILTER (clause, offset))
1715 return TRUE;
1717 return FALSE;
1721 * is_valid_branch_instruction:
1723 * Verify if it's valid to perform a branch from @offset to @target.
1724 * This should be used with br and brtrue/false.
1725 * It returns 0 if valid, 1 for unverifiable and 2 for invalid.
1726 * The major diferent from other similiar functions is that branching into a
1727 * finally/fault block is invalid instead of just unverifiable.
1729 static int
1730 is_valid_branch_instruction (MonoMethodHeader *header, guint offset, guint target)
1732 int i;
1733 MonoExceptionClause *clause;
1735 for (i = 0; i < header->num_clauses; ++i) {
1736 clause = &header->clauses [i];
1737 /*branching into a finally block is invalid*/
1738 if ((clause->flags == MONO_EXCEPTION_CLAUSE_FINALLY || clause->flags == MONO_EXCEPTION_CLAUSE_FAULT) &&
1739 !MONO_OFFSET_IN_HANDLER (clause, offset) &&
1740 MONO_OFFSET_IN_HANDLER (clause, target))
1741 return 2;
1743 if (clause->try_offset != target && (MONO_OFFSET_IN_CLAUSE (clause, offset) ^ MONO_OFFSET_IN_CLAUSE (clause, target)))
1744 return 1;
1745 if (MONO_OFFSET_IN_HANDLER (clause, offset) ^ MONO_OFFSET_IN_HANDLER (clause, target))
1746 return 1;
1747 if (MONO_OFFSET_IN_FILTER (clause, offset) ^ MONO_OFFSET_IN_FILTER (clause, target))
1748 return 1;
1750 return 0;
1754 * is_valid_cmp_branch_instruction:
1756 * Verify if it's valid to perform a branch from @offset to @target.
1757 * This should be used with binary comparison branching instruction, like beq, bge and similars.
1758 * It returns 0 if valid, 1 for unverifiable and 2 for invalid.
1760 * The major diferences from other similar functions are that most errors lead to invalid
1761 * code and only branching out of finally, filter or fault clauses is unverifiable.
1763 static int
1764 is_valid_cmp_branch_instruction (MonoMethodHeader *header, guint offset, guint target)
1766 int i;
1767 MonoExceptionClause *clause;
1769 for (i = 0; i < header->num_clauses; ++i) {
1770 clause = &header->clauses [i];
1771 /*branching out of a handler or finally*/
1772 if (clause->flags != MONO_EXCEPTION_CLAUSE_NONE &&
1773 MONO_OFFSET_IN_HANDLER (clause, offset) &&
1774 !MONO_OFFSET_IN_HANDLER (clause, target))
1775 return 1;
1777 if (clause->try_offset != target && (MONO_OFFSET_IN_CLAUSE (clause, offset) ^ MONO_OFFSET_IN_CLAUSE (clause, target)))
1778 return 2;
1779 if (MONO_OFFSET_IN_HANDLER (clause, offset) ^ MONO_OFFSET_IN_HANDLER (clause, target))
1780 return 2;
1781 if (MONO_OFFSET_IN_FILTER (clause, offset) ^ MONO_OFFSET_IN_FILTER (clause, target))
1782 return 2;
1784 return 0;
1788 * A leave can't escape a finally block
1790 static int
1791 is_correct_leave (MonoMethodHeader *header, guint offset, guint target)
1793 int i;
1794 MonoExceptionClause *clause;
1796 for (i = 0; i < header->num_clauses; ++i) {
1797 clause = &header->clauses [i];
1798 if (clause->flags == MONO_EXCEPTION_CLAUSE_FINALLY && MONO_OFFSET_IN_HANDLER (clause, offset) && !MONO_OFFSET_IN_HANDLER (clause, target))
1799 return 0;
1800 if (MONO_OFFSET_IN_FILTER (clause, offset))
1801 return 0;
1803 return 1;
1807 * A rethrow can't happen outside of a catch handler.
1809 static int
1810 is_correct_rethrow (MonoMethodHeader *header, guint offset)
1812 int i;
1813 MonoExceptionClause *clause;
1815 for (i = 0; i < header->num_clauses; ++i) {
1816 clause = &header->clauses [i];
1817 if (MONO_OFFSET_IN_HANDLER (clause, offset))
1818 return 1;
1819 if (MONO_OFFSET_IN_FILTER (clause, offset))
1820 return 1;
1822 return 0;
1826 * An endfinally can't happen outside of a finally/fault handler.
1828 static int
1829 is_correct_endfinally (MonoMethodHeader *header, guint offset)
1831 int i;
1832 MonoExceptionClause *clause;
1834 for (i = 0; i < header->num_clauses; ++i) {
1835 clause = &header->clauses [i];
1836 if (MONO_OFFSET_IN_HANDLER (clause, offset) && (clause->flags == MONO_EXCEPTION_CLAUSE_FAULT || clause->flags == MONO_EXCEPTION_CLAUSE_FINALLY))
1837 return 1;
1839 return 0;
1844 * An endfilter can only happens inside a filter clause.
1845 * In non-strict mode filter is allowed inside the handler clause too
1847 static MonoExceptionClause *
1848 is_correct_endfilter (VerifyContext *ctx, guint offset)
1850 int i;
1851 MonoExceptionClause *clause;
1853 for (i = 0; i < ctx->header->num_clauses; ++i) {
1854 clause = &ctx->header->clauses [i];
1855 if (clause->flags != MONO_EXCEPTION_CLAUSE_FILTER)
1856 continue;
1857 if (MONO_OFFSET_IN_FILTER (clause, offset))
1858 return clause;
1859 if (!IS_STRICT_MODE (ctx) && MONO_OFFSET_IN_HANDLER (clause, offset))
1860 return clause;
1862 return NULL;
1867 * Non-strict endfilter can happens inside a try block or any handler block
1869 static int
1870 is_unverifiable_endfilter (VerifyContext *ctx, guint offset)
1872 int i;
1873 MonoExceptionClause *clause;
1875 for (i = 0; i < ctx->header->num_clauses; ++i) {
1876 clause = &ctx->header->clauses [i];
1877 if (MONO_OFFSET_IN_CLAUSE (clause, offset))
1878 return 1;
1880 return 0;
1883 static gboolean
1884 is_valid_bool_arg (ILStackDesc *arg)
1886 if (stack_slot_is_managed_pointer (arg) || stack_slot_is_boxed_value (arg) || stack_slot_is_null_literal (arg))
1887 return TRUE;
1890 switch (stack_slot_get_underlying_type (arg)) {
1891 case TYPE_I4:
1892 case TYPE_I8:
1893 case TYPE_NATIVE_INT:
1894 case TYPE_PTR:
1895 return TRUE;
1896 case TYPE_COMPLEX:
1897 g_assert (arg->type);
1898 switch (arg->type->type) {
1899 case MONO_TYPE_CLASS:
1900 case MONO_TYPE_STRING:
1901 case MONO_TYPE_OBJECT:
1902 case MONO_TYPE_SZARRAY:
1903 case MONO_TYPE_ARRAY:
1904 case MONO_TYPE_FNPTR:
1905 case MONO_TYPE_PTR:
1906 return TRUE;
1907 case MONO_TYPE_GENERICINST:
1908 /*We need to check if the container class
1909 * of the generic type is a valuetype, iow:
1910 * is it a "class Foo<T>" or a "struct Foo<T>"?
1912 return !arg->type->data.generic_class->container_class->valuetype;
1914 default:
1915 return FALSE;
1920 /*Type manipulation helper*/
1922 /*Returns the byref version of the supplied MonoType*/
1923 static MonoType*
1924 mono_type_get_type_byref (MonoType *type)
1926 if (type->byref)
1927 return type;
1928 return &mono_class_from_mono_type (type)->this_arg;
1932 /*Returns the byval version of the supplied MonoType*/
1933 static MonoType*
1934 mono_type_get_type_byval (MonoType *type)
1936 if (!type->byref)
1937 return type;
1938 return &mono_class_from_mono_type (type)->byval_arg;
1941 static MonoType*
1942 mono_type_from_stack_slot (ILStackDesc *slot)
1944 if (stack_slot_is_managed_pointer (slot))
1945 return mono_type_get_type_byref (slot->type);
1946 return slot->type;
1949 /*Stack manipulation code*/
1951 static void
1952 stack_init (VerifyContext *ctx, ILCodeDesc *state)
1954 if (state->flags & IL_CODE_FLAG_STACK_INITED)
1955 return;
1956 state->size = 0;
1957 state->flags |= IL_CODE_FLAG_STACK_INITED;
1958 if (!state->stack)
1959 state->stack = g_new0 (ILStackDesc, ctx->max_stack);
1962 static void
1963 stack_copy (ILCodeDesc *to, ILCodeDesc *from)
1965 to->size = from->size;
1966 memcpy (to->stack, from->stack, sizeof (ILStackDesc) * from->size);
1969 static void
1970 copy_stack_value (ILStackDesc *to, ILStackDesc *from)
1972 to->stype = from->stype;
1973 to->type = from->type;
1974 to->method = from->method;
1977 static int
1978 check_underflow (VerifyContext *ctx, int size)
1980 if (ctx->eval.size < size) {
1981 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Stack underflow, required %d, but have %d at 0x%04x", size, ctx->eval.size, ctx->ip_offset));
1982 return 0;
1984 return 1;
1987 static int
1988 check_overflow (VerifyContext *ctx)
1990 if (ctx->eval.size >= ctx->max_stack) {
1991 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Method doesn't have stack-depth %d at 0x%04x", ctx->eval.size + 1, ctx->ip_offset));
1992 return 0;
1994 return 1;
1997 /*This reject out PTR, FNPTR and TYPEDBYREF*/
1998 static gboolean
1999 check_unmanaged_pointer (VerifyContext *ctx, ILStackDesc *value)
2001 if (stack_slot_get_type (value) == TYPE_PTR) {
2002 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Unmanaged pointer is not a verifiable type at 0x%04x", ctx->ip_offset));
2003 return 0;
2005 return 1;
2008 /*TODO verify if MONO_TYPE_TYPEDBYREF is not allowed here as well.*/
2009 static gboolean
2010 check_unverifiable_type (VerifyContext *ctx, MonoType *type)
2012 if (type->type == MONO_TYPE_PTR || type->type == MONO_TYPE_FNPTR) {
2013 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Unmanaged pointer is not a verifiable type at 0x%04x", ctx->ip_offset));
2014 return 0;
2016 return 1;
2020 static ILStackDesc *
2021 stack_push (VerifyContext *ctx)
2023 return & ctx->eval.stack [ctx->eval.size++];
2026 static ILStackDesc *
2027 stack_push_val (VerifyContext *ctx, int stype, MonoType *type)
2029 ILStackDesc *top = stack_push (ctx);
2030 top->stype = stype;
2031 top->type = type;
2032 return top;
2035 static ILStackDesc *
2036 stack_pop (VerifyContext *ctx)
2038 ILStackDesc *ret = ctx->eval.stack + --ctx->eval.size;
2039 if ((ret->stype & UNINIT_THIS_MASK) == UNINIT_THIS_MASK)
2040 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Found use of uninitialized 'this ptr' ref at 0x%04x", ctx->ip_offset));
2041 return ret;
2044 /* This function allows to safely pop an unititialized this ptr from
2045 * the eval stack without marking the method as unverifiable.
2047 static ILStackDesc *
2048 stack_pop_safe (VerifyContext *ctx)
2050 return ctx->eval.stack + --ctx->eval.size;
2053 static ILStackDesc *
2054 stack_push_stack_val (VerifyContext *ctx, ILStackDesc *value)
2056 ILStackDesc *top = stack_push (ctx);
2057 copy_stack_value (top, value);
2058 return top;
2061 /* Returns the MonoType associated with the token, or NULL if it is invalid.
2063 * A boxable type can be either a reference or value type, but cannot be a byref type or an unmanaged pointer
2064 * */
2065 static MonoType*
2066 get_boxable_mono_type (VerifyContext* ctx, int token, const char *opcode)
2068 MonoType *type;
2069 MonoClass *class;
2071 if (!(type = verifier_load_type (ctx, token, opcode)))
2072 return NULL;
2074 if (type->byref && type->type != MONO_TYPE_TYPEDBYREF) {
2075 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid use of byref type for %s at 0x%04x", opcode, ctx->ip_offset));
2076 return NULL;
2079 if (type->type == MONO_TYPE_VOID) {
2080 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid use of void type for %s at 0x%04x", opcode, ctx->ip_offset));
2081 return NULL;
2084 if (type->type == MONO_TYPE_TYPEDBYREF)
2085 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid use of typedbyref for %s at 0x%04x", opcode, ctx->ip_offset));
2087 if (!(class = mono_class_from_mono_type (type)))
2088 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Could not retrieve type token for %s at 0x%04x", opcode, ctx->ip_offset));
2090 if (class->generic_container && type->type != MONO_TYPE_GENERICINST)
2091 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use the generic type definition in a boxable type position for %s at 0x%04x", opcode, ctx->ip_offset));
2093 check_unverifiable_type (ctx, type);
2094 return type;
2098 /*operation result tables */
2100 static const unsigned char bin_op_table [TYPE_MAX][TYPE_MAX] = {
2101 {TYPE_I4, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV},
2102 {TYPE_INV, TYPE_I8, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
2103 {TYPE_NATIVE_INT, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV},
2104 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_R8, TYPE_INV, TYPE_INV},
2105 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
2106 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
2109 static const unsigned char add_table [TYPE_MAX][TYPE_MAX] = {
2110 {TYPE_I4, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV},
2111 {TYPE_INV, TYPE_I8, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
2112 {TYPE_NATIVE_INT, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV},
2113 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_R8, TYPE_INV, TYPE_INV},
2114 {TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV, TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV, TYPE_INV, TYPE_INV},
2115 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
2118 static const unsigned char sub_table [TYPE_MAX][TYPE_MAX] = {
2119 {TYPE_I4, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV},
2120 {TYPE_INV, TYPE_I8, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
2121 {TYPE_NATIVE_INT, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV},
2122 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_R8, TYPE_INV, TYPE_INV},
2123 {TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV, TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV, TYPE_NATIVE_INT | NON_VERIFIABLE_RESULT, TYPE_INV},
2124 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
2127 static const unsigned char int_bin_op_table [TYPE_MAX][TYPE_MAX] = {
2128 {TYPE_I4, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV},
2129 {TYPE_INV, TYPE_I8, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
2130 {TYPE_NATIVE_INT, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV},
2131 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
2132 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
2133 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
2136 static const unsigned char shift_op_table [TYPE_MAX][TYPE_MAX] = {
2137 {TYPE_I4, TYPE_INV, TYPE_I4, TYPE_INV, TYPE_INV, TYPE_INV},
2138 {TYPE_I8, TYPE_INV, TYPE_I8, TYPE_INV, TYPE_INV, TYPE_INV},
2139 {TYPE_NATIVE_INT, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV},
2140 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
2141 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
2142 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
2145 static const unsigned char cmp_br_op [TYPE_MAX][TYPE_MAX] = {
2146 {TYPE_I4, TYPE_INV, TYPE_I4, TYPE_INV, TYPE_INV, TYPE_INV},
2147 {TYPE_INV, TYPE_I4, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
2148 {TYPE_I4, TYPE_INV, TYPE_I4, TYPE_INV, TYPE_INV, TYPE_INV},
2149 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_I4, TYPE_INV, TYPE_INV},
2150 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_I4, TYPE_INV},
2151 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
2154 static const unsigned char cmp_br_eq_op [TYPE_MAX][TYPE_MAX] = {
2155 {TYPE_I4, TYPE_INV, TYPE_I4, TYPE_INV, TYPE_INV, TYPE_INV},
2156 {TYPE_INV, TYPE_I4, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
2157 {TYPE_I4, TYPE_INV, TYPE_I4, TYPE_INV, TYPE_I4 | NON_VERIFIABLE_RESULT, TYPE_INV},
2158 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_I4, TYPE_INV, TYPE_INV},
2159 {TYPE_INV, TYPE_INV, TYPE_I4 | NON_VERIFIABLE_RESULT, TYPE_INV, TYPE_I4, TYPE_INV},
2160 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_I4},
2163 static const unsigned char add_ovf_un_table [TYPE_MAX][TYPE_MAX] = {
2164 {TYPE_I4, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV},
2165 {TYPE_INV, TYPE_I8, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
2166 {TYPE_NATIVE_INT, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV},
2167 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
2168 {TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV, TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV, TYPE_INV, TYPE_INV},
2169 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
2172 static const unsigned char sub_ovf_un_table [TYPE_MAX][TYPE_MAX] = {
2173 {TYPE_I4, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV},
2174 {TYPE_INV, TYPE_I8, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
2175 {TYPE_NATIVE_INT, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV},
2176 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
2177 {TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV, TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV, TYPE_NATIVE_INT | NON_VERIFIABLE_RESULT, TYPE_INV},
2178 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
2181 static const unsigned char bin_ovf_table [TYPE_MAX][TYPE_MAX] = {
2182 {TYPE_I4, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV},
2183 {TYPE_INV, TYPE_I8, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
2184 {TYPE_NATIVE_INT, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV},
2185 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
2186 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
2187 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
2190 #ifdef MONO_VERIFIER_DEBUG
2192 /*debug helpers */
2193 static void
2194 dump_stack_value (ILStackDesc *value)
2196 printf ("[(%x)(%x)", value->type->type, value->stype);
2198 if (stack_slot_is_this_pointer (value))
2199 printf ("[this] ");
2201 if (stack_slot_is_boxed_value (value))
2202 printf ("[boxed] ");
2204 if (stack_slot_is_null_literal (value))
2205 printf ("[null] ");
2207 if (stack_slot_is_managed_mutability_pointer (value))
2208 printf ("Controled Mutability MP: ");
2210 if (stack_slot_is_managed_pointer (value))
2211 printf ("Managed Pointer to: ");
2213 switch (stack_slot_get_underlying_type (value)) {
2214 case TYPE_INV:
2215 printf ("invalid type]");
2216 return;
2217 case TYPE_I4:
2218 printf ("int32]");
2219 return;
2220 case TYPE_I8:
2221 printf ("int64]");
2222 return;
2223 case TYPE_NATIVE_INT:
2224 printf ("native int]");
2225 return;
2226 case TYPE_R8:
2227 printf ("float64]");
2228 return;
2229 case TYPE_PTR:
2230 printf ("unmanaged pointer]");
2231 return;
2232 case TYPE_COMPLEX:
2233 switch (value->type->type) {
2234 case MONO_TYPE_CLASS:
2235 case MONO_TYPE_VALUETYPE:
2236 printf ("complex] (%s)", value->type->data.klass->name);
2237 return;
2238 case MONO_TYPE_STRING:
2239 printf ("complex] (string)");
2240 return;
2241 case MONO_TYPE_OBJECT:
2242 printf ("complex] (object)");
2243 return;
2244 case MONO_TYPE_SZARRAY:
2245 printf ("complex] (%s [])", value->type->data.klass->name);
2246 return;
2247 case MONO_TYPE_ARRAY:
2248 printf ("complex] (%s [%d %d %d])",
2249 value->type->data.array->eklass->name,
2250 value->type->data.array->rank,
2251 value->type->data.array->numsizes,
2252 value->type->data.array->numlobounds);
2253 return;
2254 case MONO_TYPE_GENERICINST:
2255 printf ("complex] (inst of %s )", value->type->data.generic_class->container_class->name);
2256 return;
2257 case MONO_TYPE_VAR:
2258 printf ("complex] (type generic param !%d - %s) ", value->type->data.generic_param->num, mono_generic_param_info (value->type->data.generic_param)->name);
2259 return;
2260 case MONO_TYPE_MVAR:
2261 printf ("complex] (method generic param !!%d - %s) ", value->type->data.generic_param->num, mono_generic_param_info (value->type->data.generic_param)->name);
2262 return;
2263 default: {
2264 //should be a boxed value
2265 char * name = mono_type_full_name (value->type);
2266 printf ("complex] %s", name);
2267 g_free (name);
2268 return;
2271 default:
2272 printf ("unknown stack %x type]\n", value->stype);
2273 g_assert_not_reached ();
2277 static void
2278 dump_stack_state (ILCodeDesc *state)
2280 int i;
2282 printf ("(%d) ", state->size);
2283 for (i = 0; i < state->size; ++i)
2284 dump_stack_value (state->stack + i);
2285 printf ("\n");
2287 #endif
2289 /*Returns TRUE if candidate array type can be assigned to target.
2290 *Both parameters MUST be of type MONO_TYPE_ARRAY (target->type == MONO_TYPE_ARRAY)
2292 static gboolean
2293 is_array_type_compatible (MonoType *target, MonoType *candidate)
2295 MonoArrayType *left = target->data.array;
2296 MonoArrayType *right = candidate->data.array;
2298 g_assert (target->type == MONO_TYPE_ARRAY);
2299 g_assert (candidate->type == MONO_TYPE_ARRAY);
2301 if (left->rank != right->rank)
2302 return FALSE;
2304 return mono_class_is_assignable_from (left->eklass, right->eklass);
2307 static int
2308 get_stack_type (MonoType *type)
2310 int mask = 0;
2311 int type_kind = type->type;
2312 if (type->byref)
2313 mask = POINTER_MASK;
2314 /*TODO handle CMMP_MASK */
2316 handle_enum:
2317 switch (type_kind) {
2318 case MONO_TYPE_I1:
2319 case MONO_TYPE_U1:
2320 case MONO_TYPE_BOOLEAN:
2321 case MONO_TYPE_I2:
2322 case MONO_TYPE_U2:
2323 case MONO_TYPE_CHAR:
2324 case MONO_TYPE_I4:
2325 case MONO_TYPE_U4:
2326 return TYPE_I4 | mask;
2328 case MONO_TYPE_I:
2329 case MONO_TYPE_U:
2330 return TYPE_NATIVE_INT | mask;
2332 /* FIXME: the spec says that you cannot have a pointer to method pointer, do we need to check this here? */
2333 case MONO_TYPE_FNPTR:
2334 case MONO_TYPE_PTR:
2335 case MONO_TYPE_TYPEDBYREF:
2336 return TYPE_PTR | mask;
2338 case MONO_TYPE_VAR:
2339 case MONO_TYPE_MVAR:
2341 case MONO_TYPE_CLASS:
2342 case MONO_TYPE_STRING:
2343 case MONO_TYPE_OBJECT:
2344 case MONO_TYPE_SZARRAY:
2345 case MONO_TYPE_ARRAY:
2346 return TYPE_COMPLEX | mask;
2348 case MONO_TYPE_GENERICINST:
2349 if (mono_type_is_enum_type (type)) {
2350 type = mono_type_get_underlying_type_any (type);
2351 type_kind = type->type;
2352 goto handle_enum;
2353 } else {
2354 return TYPE_COMPLEX | mask;
2357 case MONO_TYPE_I8:
2358 case MONO_TYPE_U8:
2359 return TYPE_I8 | mask;
2361 case MONO_TYPE_R4:
2362 case MONO_TYPE_R8:
2363 return TYPE_R8 | mask;
2365 case MONO_TYPE_VALUETYPE:
2366 if (mono_type_is_enum_type (type)) {
2367 type = mono_type_get_underlying_type_any (type);
2368 type_kind = type->type;
2369 goto handle_enum;
2370 } else {
2371 return TYPE_COMPLEX | mask;
2374 default:
2375 VERIFIER_DEBUG ( printf ("unknown type %02x in eval stack type\n", type->type); );
2376 g_assert_not_reached ();
2377 return 0;
2381 /* convert MonoType to ILStackDesc format (stype) */
2382 static gboolean
2383 set_stack_value (VerifyContext *ctx, ILStackDesc *stack, MonoType *type, int take_addr)
2385 int mask = 0;
2386 int type_kind = type->type;
2388 if (type->byref || take_addr)
2389 mask = POINTER_MASK;
2390 /* TODO handle CMMP_MASK */
2392 handle_enum:
2393 stack->type = type;
2395 switch (type_kind) {
2396 case MONO_TYPE_I1:
2397 case MONO_TYPE_U1:
2398 case MONO_TYPE_BOOLEAN:
2399 case MONO_TYPE_I2:
2400 case MONO_TYPE_U2:
2401 case MONO_TYPE_CHAR:
2402 case MONO_TYPE_I4:
2403 case MONO_TYPE_U4:
2404 stack->stype = TYPE_I4 | mask;
2405 break;
2406 case MONO_TYPE_I:
2407 case MONO_TYPE_U:
2408 stack->stype = TYPE_NATIVE_INT | mask;
2409 break;
2411 /*FIXME: Do we need to check if it's a pointer to the method pointer? The spec says it' illegal to have that.*/
2412 case MONO_TYPE_FNPTR:
2413 case MONO_TYPE_PTR:
2414 case MONO_TYPE_TYPEDBYREF:
2415 stack->stype = TYPE_PTR | mask;
2416 break;
2418 case MONO_TYPE_CLASS:
2419 case MONO_TYPE_STRING:
2420 case MONO_TYPE_OBJECT:
2421 case MONO_TYPE_SZARRAY:
2422 case MONO_TYPE_ARRAY:
2424 case MONO_TYPE_VAR:
2425 case MONO_TYPE_MVAR:
2426 stack->stype = TYPE_COMPLEX | mask;
2427 break;
2429 case MONO_TYPE_GENERICINST:
2430 if (mono_type_is_enum_type (type)) {
2431 type = mono_type_get_underlying_type_any (type);
2432 type_kind = type->type;
2433 goto handle_enum;
2434 } else {
2435 stack->stype = TYPE_COMPLEX | mask;
2436 break;
2439 case MONO_TYPE_I8:
2440 case MONO_TYPE_U8:
2441 stack->stype = TYPE_I8 | mask;
2442 break;
2443 case MONO_TYPE_R4:
2444 case MONO_TYPE_R8:
2445 stack->stype = TYPE_R8 | mask;
2446 break;
2447 case MONO_TYPE_VALUETYPE:
2448 if (mono_type_is_enum_type (type)) {
2449 type = mono_type_get_underlying_type_any (type);
2450 type_kind = type->type;
2451 goto handle_enum;
2452 } else {
2453 stack->stype = TYPE_COMPLEX | mask;
2454 break;
2456 default:
2457 VERIFIER_DEBUG ( printf ("unknown type 0x%02x in eval stack type\n", type->type); );
2458 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Illegal value set on stack 0x%02x at %d", type->type, ctx->ip_offset));
2459 return FALSE;
2461 return TRUE;
2465 * init_stack_with_value_at_exception_boundary:
2467 * Initialize the stack and push a given type.
2468 * The instruction is marked as been on the exception boundary.
2470 static void
2471 init_stack_with_value_at_exception_boundary (VerifyContext *ctx, ILCodeDesc *code, MonoClass *klass)
2473 MonoError error;
2474 MonoType *type = mono_class_inflate_generic_type_checked (&klass->byval_arg, ctx->generic_context, &error);
2476 if (!mono_error_ok (&error)) {
2477 char *name = mono_type_get_full_name (klass);
2478 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid class %s used for exception", name));
2479 g_free (name);
2480 mono_error_cleanup (&error);
2481 return;
2484 stack_init (ctx, code);
2485 set_stack_value (ctx, code->stack, type, FALSE);
2486 ctx->exception_types = g_slist_prepend (ctx->exception_types, type);
2487 code->size = 1;
2488 code->flags |= IL_CODE_FLAG_WAS_TARGET;
2489 if (mono_type_is_generic_argument (type))
2490 code->stack->stype |= BOXED_MASK;
2493 /*Verify if type 'candidate' can be stored in type 'target'.
2495 * If strict, check for the underlying type and not the verification stack types
2497 static gboolean
2498 verify_type_compatibility_full (VerifyContext *ctx, MonoType *target, MonoType *candidate, gboolean strict)
2500 #define IS_ONE_OF3(T, A, B, C) (T == A || T == B || T == C)
2501 #define IS_ONE_OF2(T, A, B) (T == A || T == B)
2503 MonoType *original_candidate = candidate;
2504 VERIFIER_DEBUG ( printf ("checking type compatibility %s x %s strict %d\n", mono_type_full_name (target), mono_type_full_name (candidate), strict); );
2506 /*only one is byref */
2507 if (candidate->byref ^ target->byref) {
2508 /* converting from native int to byref*/
2509 if (get_stack_type (candidate) == TYPE_NATIVE_INT && target->byref) {
2510 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("using byref native int at 0x%04x", ctx->ip_offset));
2511 return TRUE;
2513 return FALSE;
2515 strict |= target->byref;
2516 /*From now on we don't care about byref anymore, so it's ok to discard it here*/
2517 candidate = mono_type_get_underlying_type_any (candidate);
2519 handle_enum:
2520 switch (target->type) {
2521 case MONO_TYPE_VOID:
2522 return candidate->type == MONO_TYPE_VOID;
2523 case MONO_TYPE_I1:
2524 case MONO_TYPE_U1:
2525 case MONO_TYPE_BOOLEAN:
2526 if (strict)
2527 return IS_ONE_OF3 (candidate->type, MONO_TYPE_I1, MONO_TYPE_U1, MONO_TYPE_BOOLEAN);
2528 case MONO_TYPE_I2:
2529 case MONO_TYPE_U2:
2530 case MONO_TYPE_CHAR:
2531 if (strict)
2532 return IS_ONE_OF3 (candidate->type, MONO_TYPE_I2, MONO_TYPE_U2, MONO_TYPE_CHAR);
2533 case MONO_TYPE_I4:
2534 case MONO_TYPE_U4: {
2535 gboolean is_native_int = IS_ONE_OF2 (candidate->type, MONO_TYPE_I, MONO_TYPE_U);
2536 gboolean is_int4 = IS_ONE_OF2 (candidate->type, MONO_TYPE_I4, MONO_TYPE_U4);
2537 if (strict)
2538 return is_native_int || is_int4;
2539 return is_native_int || get_stack_type (candidate) == TYPE_I4;
2542 case MONO_TYPE_I8:
2543 case MONO_TYPE_U8:
2544 return IS_ONE_OF2 (candidate->type, MONO_TYPE_I8, MONO_TYPE_U8);
2546 case MONO_TYPE_R4:
2547 case MONO_TYPE_R8:
2548 if (strict)
2549 return candidate->type == target->type;
2550 return IS_ONE_OF2 (candidate->type, MONO_TYPE_R4, MONO_TYPE_R8);
2552 case MONO_TYPE_I:
2553 case MONO_TYPE_U: {
2554 gboolean is_native_int = IS_ONE_OF2 (candidate->type, MONO_TYPE_I, MONO_TYPE_U);
2555 gboolean is_int4 = IS_ONE_OF2 (candidate->type, MONO_TYPE_I4, MONO_TYPE_U4);
2556 if (strict)
2557 return is_native_int || is_int4;
2558 return is_native_int || get_stack_type (candidate) == TYPE_I4;
2561 case MONO_TYPE_PTR:
2562 if (candidate->type != MONO_TYPE_PTR)
2563 return FALSE;
2564 /* check the underlying type */
2565 return verify_type_compatibility_full (ctx, target->data.type, candidate->data.type, TRUE);
2567 case MONO_TYPE_FNPTR: {
2568 MonoMethodSignature *left, *right;
2569 if (candidate->type != MONO_TYPE_FNPTR)
2570 return FALSE;
2572 left = mono_type_get_signature (target);
2573 right = mono_type_get_signature (candidate);
2574 return mono_metadata_signature_equal (left, right) && left->call_convention == right->call_convention;
2577 case MONO_TYPE_GENERICINST: {
2578 MonoClass *target_klass;
2579 MonoClass *candidate_klass;
2580 if (mono_type_is_enum_type (target)) {
2581 target = mono_type_get_underlying_type_any (target);
2582 goto handle_enum;
2584 target_klass = mono_class_from_mono_type (target);
2585 candidate_klass = mono_class_from_mono_type (candidate);
2586 if (mono_class_is_nullable (target_klass)) {
2587 if (!mono_class_is_nullable (candidate_klass))
2588 return FALSE;
2589 return target_klass == candidate_klass;
2592 return mono_class_is_assignable_from (target_klass, candidate_klass);
2595 case MONO_TYPE_STRING:
2596 return candidate->type == MONO_TYPE_STRING;
2598 case MONO_TYPE_CLASS:
2600 * VAR / MVAR compatibility must be checked by verify_stack_type_compatibility
2601 * to take boxing status into account.
2603 if (mono_type_is_generic_argument (original_candidate))
2604 return FALSE;
2605 /* If candidate is an enum it should return true for System.Enum and supertypes.
2606 * That's why here we use the original type and not the underlying type.
2608 return mono_class_is_assignable_from (target->data.klass, mono_class_from_mono_type (original_candidate));
2610 case MONO_TYPE_OBJECT:
2611 return MONO_TYPE_IS_REFERENCE (candidate);
2613 case MONO_TYPE_SZARRAY: {
2614 MonoClass *left;
2615 MonoClass *right;
2616 if (candidate->type != MONO_TYPE_SZARRAY)
2617 return FALSE;
2619 left = mono_class_from_mono_type (target)->element_class;
2620 right = mono_class_from_mono_type (candidate)->element_class;
2621 return mono_class_is_assignable_from (left, right);
2624 case MONO_TYPE_ARRAY:
2625 if (candidate->type != MONO_TYPE_ARRAY)
2626 return FALSE;
2627 return is_array_type_compatible (target, candidate);
2629 case MONO_TYPE_TYPEDBYREF:
2630 return candidate->type == MONO_TYPE_TYPEDBYREF;
2632 case MONO_TYPE_VALUETYPE: {
2633 MonoClass *target_klass = mono_class_from_mono_type (target);
2634 MonoClass *candidate_klass = mono_class_from_mono_type (candidate);
2636 if (target_klass == candidate_klass)
2637 return TRUE;
2638 if (mono_type_is_enum_type (target)) {
2639 target = mono_type_get_underlying_type_any (target);
2640 goto handle_enum;
2642 return FALSE;
2645 case MONO_TYPE_VAR:
2646 if (candidate->type != MONO_TYPE_VAR)
2647 return FALSE;
2648 return mono_type_get_generic_param_num (candidate) == mono_type_get_generic_param_num (target);
2650 case MONO_TYPE_MVAR:
2651 if (candidate->type != MONO_TYPE_MVAR)
2652 return FALSE;
2653 return mono_type_get_generic_param_num (candidate) == mono_type_get_generic_param_num (target);
2655 default:
2656 VERIFIER_DEBUG ( printf ("unknown store type %d\n", target->type); );
2657 g_assert_not_reached ();
2658 return FALSE;
2660 return 1;
2661 #undef IS_ONE_OF3
2662 #undef IS_ONE_OF2
2665 static gboolean
2666 verify_type_compatibility (VerifyContext *ctx, MonoType *target, MonoType *candidate)
2668 return verify_type_compatibility_full (ctx, target, candidate, FALSE);
2672 * Returns the generic param bound to the context been verified.
2675 static MonoGenericParam*
2676 get_generic_param (VerifyContext *ctx, MonoType *param)
2678 guint16 param_num = mono_type_get_generic_param_num (param);
2679 if (param->type == MONO_TYPE_VAR) {
2680 if (!ctx->generic_context->class_inst || ctx->generic_context->class_inst->type_argc <= param_num) {
2681 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid generic type argument %d", param_num));
2682 return NULL;
2684 return ctx->generic_context->class_inst->type_argv [param_num]->data.generic_param;
2687 /*param must be a MVAR */
2688 if (!ctx->generic_context->method_inst || ctx->generic_context->method_inst->type_argc <= param_num) {
2689 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid generic method argument %d", param_num));
2690 return NULL;
2692 return ctx->generic_context->method_inst->type_argv [param_num]->data.generic_param;
2696 * is_compatible_boxed_valuetype:
2698 * Returns TRUE if @candidate / @stack is a valid boxed valuetype.
2700 * @type The source type. It it tested to be of the proper type.
2701 * @candidate type of the boxed valuetype.
2702 * @stack stack slot of the boxed valuetype, separate from @candidade since one could be changed before calling this function
2703 * @strict if TRUE candidate must be boxed compatible to the target type
2706 static gboolean
2707 is_compatible_boxed_valuetype (VerifyContext *ctx, MonoType *type, MonoType *candidate, ILStackDesc *stack, gboolean strict)
2709 if (!stack_slot_is_boxed_value (stack))
2710 return FALSE;
2711 if (type->byref || candidate->byref)
2712 return FALSE;
2714 if (mono_type_is_generic_argument (candidate)) {
2715 MonoGenericParam *param = get_generic_param (ctx, candidate);
2716 MonoClass **class;
2717 for (class = mono_generic_param_info (param)->constraints; class && *class; ++class) {
2718 if (verify_type_compatibility_full (ctx, type, mono_type_get_type_byval (& (*class)->byval_arg), FALSE))
2719 return TRUE;
2723 if (mono_type_is_generic_argument (type))
2724 return FALSE;
2726 if (!strict)
2727 return TRUE;
2729 return MONO_TYPE_IS_REFERENCE (type) && mono_class_is_assignable_from (mono_class_from_mono_type (type), mono_class_from_mono_type (candidate));
2732 static int
2733 verify_stack_type_compatibility_full (VerifyContext *ctx, MonoType *type, ILStackDesc *stack, gboolean drop_byref, gboolean valuetype_must_be_boxed)
2735 MonoType *candidate = mono_type_from_stack_slot (stack);
2736 if (MONO_TYPE_IS_REFERENCE (type) && !type->byref && stack_slot_is_null_literal (stack))
2737 return TRUE;
2739 if (is_compatible_boxed_valuetype (ctx, type, candidate, stack, TRUE))
2740 return TRUE;
2742 if (valuetype_must_be_boxed && !stack_slot_is_boxed_value (stack) && !MONO_TYPE_IS_REFERENCE (candidate))
2743 return FALSE;
2745 if (!valuetype_must_be_boxed && stack_slot_is_boxed_value (stack))
2746 return FALSE;
2748 if (drop_byref)
2749 return verify_type_compatibility_full (ctx, type, mono_type_get_type_byval (candidate), FALSE);
2751 return verify_type_compatibility_full (ctx, type, candidate, FALSE);
2754 static int
2755 verify_stack_type_compatibility (VerifyContext *ctx, MonoType *type, ILStackDesc *stack)
2757 return verify_stack_type_compatibility_full (ctx, type, stack, FALSE, FALSE);
2760 static gboolean
2761 mono_delegate_type_equal (MonoType *target, MonoType *candidate)
2763 if (candidate->byref ^ target->byref)
2764 return FALSE;
2766 switch (target->type) {
2767 case MONO_TYPE_VOID:
2768 case MONO_TYPE_I1:
2769 case MONO_TYPE_U1:
2770 case MONO_TYPE_BOOLEAN:
2771 case MONO_TYPE_I2:
2772 case MONO_TYPE_U2:
2773 case MONO_TYPE_CHAR:
2774 case MONO_TYPE_I4:
2775 case MONO_TYPE_U4:
2776 case MONO_TYPE_I8:
2777 case MONO_TYPE_U8:
2778 case MONO_TYPE_R4:
2779 case MONO_TYPE_R8:
2780 case MONO_TYPE_I:
2781 case MONO_TYPE_U:
2782 case MONO_TYPE_STRING:
2783 case MONO_TYPE_TYPEDBYREF:
2784 return candidate->type == target->type;
2786 case MONO_TYPE_PTR:
2787 return mono_delegate_type_equal (target->data.type, candidate->data.type);
2789 case MONO_TYPE_FNPTR:
2790 if (candidate->type != MONO_TYPE_FNPTR)
2791 return FALSE;
2792 return mono_delegate_signature_equal (mono_type_get_signature (target), mono_type_get_signature (candidate), FALSE);
2794 case MONO_TYPE_GENERICINST: {
2795 MonoClass *target_klass;
2796 MonoClass *candidate_klass;
2797 target_klass = mono_class_from_mono_type (target);
2798 candidate_klass = mono_class_from_mono_type (candidate);
2799 /*FIXME handle nullables and enum*/
2800 return mono_class_is_assignable_from (target_klass, candidate_klass);
2802 case MONO_TYPE_OBJECT:
2803 return MONO_TYPE_IS_REFERENCE (candidate);
2805 case MONO_TYPE_CLASS:
2806 return mono_class_is_assignable_from(target->data.klass, mono_class_from_mono_type (candidate));
2808 case MONO_TYPE_SZARRAY:
2809 if (candidate->type != MONO_TYPE_SZARRAY)
2810 return FALSE;
2811 return mono_class_is_assignable_from (mono_class_from_mono_type (target)->element_class, mono_class_from_mono_type (candidate)->element_class);
2813 case MONO_TYPE_ARRAY:
2814 if (candidate->type != MONO_TYPE_ARRAY)
2815 return FALSE;
2816 return is_array_type_compatible (target, candidate);
2818 case MONO_TYPE_VALUETYPE:
2819 /*FIXME handle nullables and enum*/
2820 return mono_class_from_mono_type (candidate) == mono_class_from_mono_type (target);
2822 case MONO_TYPE_VAR:
2823 return candidate->type == MONO_TYPE_VAR && mono_type_get_generic_param_num (target) == mono_type_get_generic_param_num (candidate);
2824 return FALSE;
2826 case MONO_TYPE_MVAR:
2827 return candidate->type == MONO_TYPE_MVAR && mono_type_get_generic_param_num (target) == mono_type_get_generic_param_num (candidate);
2828 return FALSE;
2830 default:
2831 VERIFIER_DEBUG ( printf ("Unknown type %d. Implement me!\n", target->type); );
2832 g_assert_not_reached ();
2833 return FALSE;
2837 static gboolean
2838 mono_delegate_param_equal (MonoType *delegate, MonoType *method)
2840 if (mono_metadata_type_equal_full (delegate, method, TRUE))
2841 return TRUE;
2843 return mono_delegate_type_equal (method, delegate);
2846 static gboolean
2847 mono_delegate_ret_equal (MonoType *delegate, MonoType *method)
2849 if (mono_metadata_type_equal_full (delegate, method, TRUE))
2850 return TRUE;
2852 return mono_delegate_type_equal (delegate, method);
2856 * mono_delegate_signature_equal:
2858 * Compare two signatures in the way expected by delegates.
2860 * This function only exists due to the fact that it should ignore the 'has_this' part of the signature.
2862 * FIXME can this function be eliminated and proper metadata functionality be used?
2864 static gboolean
2865 mono_delegate_signature_equal (MonoMethodSignature *delegate_sig, MonoMethodSignature *method_sig, gboolean is_static_ldftn)
2867 int i;
2868 int method_offset = is_static_ldftn ? 1 : 0;
2870 if (delegate_sig->param_count + method_offset != method_sig->param_count)
2871 return FALSE;
2873 if (delegate_sig->call_convention != method_sig->call_convention)
2874 return FALSE;
2876 for (i = 0; i < delegate_sig->param_count; i++) {
2877 MonoType *p1 = delegate_sig->params [i];
2878 MonoType *p2 = method_sig->params [i + method_offset];
2880 if (!mono_delegate_param_equal (p1, p2))
2881 return FALSE;
2884 if (!mono_delegate_ret_equal (delegate_sig->ret, method_sig->ret))
2885 return FALSE;
2887 return TRUE;
2891 * verify_ldftn_delegate:
2893 * Verify properties of ldftn based delegates.
2895 static void
2896 verify_ldftn_delegate (VerifyContext *ctx, MonoClass *delegate, ILStackDesc *value, ILStackDesc *funptr)
2898 MonoMethod *method = funptr->method;
2900 /*ldftn non-final virtuals only allowed if method is not static,
2901 * the object is a this arg (comes from a ldarg.0), and there is no starg.0.
2902 * This rules doesn't apply if the object on stack is a boxed valuetype.
2904 if ((method->flags & METHOD_ATTRIBUTE_VIRTUAL) && !(method->flags & METHOD_ATTRIBUTE_FINAL) && !(method->klass->flags & TYPE_ATTRIBUTE_SEALED) && !stack_slot_is_boxed_value (value)) {
2905 /*A stdarg 0 must not happen, we fail here only in fail fast mode to avoid double error reports*/
2906 if (IS_FAIL_FAST_MODE (ctx) && ctx->has_this_store)
2907 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid ldftn with virtual function in method with stdarg 0 at 0x%04x", ctx->ip_offset));
2909 /*current method must not be static*/
2910 if (ctx->method->flags & METHOD_ATTRIBUTE_STATIC)
2911 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid ldftn with virtual function at 0x%04x", ctx->ip_offset));
2913 /*value is the this pointer, loaded using ldarg.0 */
2914 if (!stack_slot_is_this_pointer (value))
2915 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));
2917 ctx->code [ctx->ip_offset].flags |= IL_CODE_LDFTN_DELEGATE_NONFINAL_VIRTUAL;
2922 * verify_delegate_compatibility:
2924 * Verify delegate creation sequence.
2927 static void
2928 verify_delegate_compatibility (VerifyContext *ctx, MonoClass *delegate, ILStackDesc *value, ILStackDesc *funptr)
2930 #define IS_VALID_OPCODE(offset, opcode) (ip [ip_offset - offset] == opcode && (ctx->code [ip_offset - offset].flags & IL_CODE_FLAG_SEEN))
2931 #define IS_LOAD_FUN_PTR(kind) (IS_VALID_OPCODE (6, CEE_PREFIX1) && ip [ip_offset - 5] == kind)
2933 MonoMethod *invoke, *method;
2934 const guint8 *ip = ctx->header->code;
2935 guint32 ip_offset = ctx->ip_offset;
2936 gboolean is_static_ldftn = FALSE, is_first_arg_bound = FALSE;
2938 if (stack_slot_get_type (funptr) != TYPE_PTR || !funptr->method) {
2939 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid function pointer parameter for delegate constructor at 0x%04x", ctx->ip_offset));
2940 return;
2943 invoke = mono_get_delegate_invoke (delegate);
2944 method = funptr->method;
2946 is_static_ldftn = (ip_offset > 5 && IS_LOAD_FUN_PTR (CEE_LDFTN)) && method->flags & METHOD_ATTRIBUTE_STATIC;
2948 if (is_static_ldftn)
2949 is_first_arg_bound = mono_method_signature (invoke)->param_count + 1 == mono_method_signature (method)->param_count;
2951 if (!mono_delegate_signature_equal (mono_method_signature (invoke), mono_method_signature (method), is_first_arg_bound)) {
2952 char *fun_sig = mono_signature_get_desc (mono_method_signature (method), FALSE);
2953 char *invoke_sig = mono_signature_get_desc (mono_method_signature (invoke), FALSE);
2954 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));
2955 g_free (fun_sig);
2956 g_free (invoke_sig);
2960 * Delegate code sequences:
2961 * [-6] ldftn token
2962 * newobj ...
2965 * [-7] dup
2966 * [-6] ldvirtftn token
2967 * newobj ...
2969 * ldftn sequence:*/
2970 if (ip_offset > 5 && IS_LOAD_FUN_PTR (CEE_LDFTN)) {
2971 verify_ldftn_delegate (ctx, delegate, value, funptr);
2972 } else if (ip_offset > 6 && IS_VALID_OPCODE (7, CEE_DUP) && IS_LOAD_FUN_PTR (CEE_LDVIRTFTN)) {
2973 ctx->code [ip_offset - 6].flags |= IL_CODE_DELEGATE_SEQUENCE;
2974 }else {
2975 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid code sequence for delegate creation at 0x%04x", ctx->ip_offset));
2977 ctx->code [ip_offset].flags |= IL_CODE_DELEGATE_SEQUENCE;
2979 //general tests
2980 if (is_first_arg_bound) {
2981 if (mono_method_signature (method)->param_count == 0 || !verify_stack_type_compatibility_full (ctx, mono_method_signature (method)->params [0], value, FALSE, TRUE))
2982 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("This object not compatible with function pointer for delegate creation at 0x%04x", ctx->ip_offset));
2983 } else {
2984 if (method->flags & METHOD_ATTRIBUTE_STATIC) {
2985 if (!stack_slot_is_null_literal (value) && !is_first_arg_bound)
2986 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Non-null this args used with static function for delegate creation at 0x%04x", ctx->ip_offset));
2987 } else {
2988 if (!verify_stack_type_compatibility_full (ctx, &method->klass->byval_arg, value, FALSE, TRUE) && !stack_slot_is_null_literal (value))
2989 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("This object not compatible with function pointer for delegate creation at 0x%04x", ctx->ip_offset));
2993 if (stack_slot_get_type (value) != TYPE_COMPLEX)
2994 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid first parameter for delegate creation at 0x%04x", ctx->ip_offset));
2996 #undef IS_VALID_OPCODE
2997 #undef IS_LOAD_FUN_PTR
3000 /* implement the opcode checks*/
3001 static void
3002 push_arg (VerifyContext *ctx, unsigned int arg, int take_addr)
3004 ILStackDesc *top;
3006 if (arg >= ctx->max_args) {
3007 if (take_addr)
3008 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Method doesn't have argument %d", arg + 1));
3009 else {
3010 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Method doesn't have argument %d", arg + 1));
3011 if (check_overflow (ctx)) //FIXME: what sane value could we ever push?
3012 stack_push_val (ctx, TYPE_I4, &mono_defaults.int32_class->byval_arg);
3014 } else if (check_overflow (ctx)) {
3015 /*We must let the value be pushed, otherwise we would get an underflow error*/
3016 check_unverifiable_type (ctx, ctx->params [arg]);
3017 if (ctx->params [arg]->byref && take_addr)
3018 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("ByRef of ByRef at 0x%04x", ctx->ip_offset));
3019 top = stack_push (ctx);
3020 if (!set_stack_value (ctx, top, ctx->params [arg], take_addr))
3021 return;
3023 if (arg == 0 && !(ctx->method->flags & METHOD_ATTRIBUTE_STATIC)) {
3024 if (take_addr)
3025 ctx->has_this_store = TRUE;
3026 else
3027 top->stype |= THIS_POINTER_MASK;
3028 if (mono_method_is_constructor (ctx->method) && !ctx->super_ctor_called && !ctx->method->klass->valuetype)
3029 top->stype |= UNINIT_THIS_MASK;
3034 static void
3035 push_local (VerifyContext *ctx, guint32 arg, int take_addr)
3037 if (arg >= ctx->num_locals) {
3038 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Method doesn't have local %d", arg + 1));
3039 } else if (check_overflow (ctx)) {
3040 /*We must let the value be pushed, otherwise we would get an underflow error*/
3041 check_unverifiable_type (ctx, ctx->locals [arg]);
3042 if (ctx->locals [arg]->byref && take_addr)
3043 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("ByRef of ByRef at 0x%04x", ctx->ip_offset));
3045 set_stack_value (ctx, stack_push (ctx), ctx->locals [arg], take_addr);
3049 static void
3050 store_arg (VerifyContext *ctx, guint32 arg)
3052 ILStackDesc *value;
3054 if (arg >= ctx->max_args) {
3055 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Method doesn't have argument %d at 0x%04x", arg + 1, ctx->ip_offset));
3056 if (check_underflow (ctx, 1))
3057 stack_pop (ctx);
3058 return;
3061 if (check_underflow (ctx, 1)) {
3062 value = stack_pop (ctx);
3063 if (!verify_stack_type_compatibility (ctx, ctx->params [arg], value)) {
3064 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Incompatible type %s in argument store at 0x%04x", stack_slot_get_name (value), ctx->ip_offset));
3067 if (arg == 0 && !(ctx->method->flags & METHOD_ATTRIBUTE_STATIC))
3068 ctx->has_this_store = 1;
3071 static void
3072 store_local (VerifyContext *ctx, guint32 arg)
3074 ILStackDesc *value;
3075 if (arg >= ctx->num_locals) {
3076 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Method doesn't have local var %d at 0x%04x", arg + 1, ctx->ip_offset));
3077 return;
3080 /*TODO verify definite assigment */
3081 if (check_underflow (ctx, 1)) {
3082 value = stack_pop(ctx);
3083 if (!verify_stack_type_compatibility (ctx, ctx->locals [arg], value)) {
3084 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Incompatible type [%s], type [%s] was expected in local store at 0x%04x",
3085 stack_slot_get_name (value),
3086 mono_type_get_stack_name (ctx->locals [arg]),
3087 ctx->ip_offset));
3092 /*FIXME add and sub needs special care here*/
3093 static void
3094 do_binop (VerifyContext *ctx, unsigned int opcode, const unsigned char table [TYPE_MAX][TYPE_MAX])
3096 ILStackDesc *a, *b, *top;
3097 int idxa, idxb, complexMerge = 0;
3098 unsigned char res;
3100 if (!check_underflow (ctx, 2))
3101 return;
3102 b = stack_pop (ctx);
3103 a = stack_pop (ctx);
3105 idxa = stack_slot_get_underlying_type (a);
3106 if (stack_slot_is_managed_pointer (a)) {
3107 idxa = TYPE_PTR;
3108 complexMerge = 1;
3111 idxb = stack_slot_get_underlying_type (b);
3112 if (stack_slot_is_managed_pointer (b)) {
3113 idxb = TYPE_PTR;
3114 complexMerge = 2;
3117 --idxa;
3118 --idxb;
3119 res = table [idxa][idxb];
3121 VERIFIER_DEBUG ( printf ("binop res %d\n", res); );
3122 VERIFIER_DEBUG ( printf ("idxa %d idxb %d\n", idxa, idxb); );
3124 top = stack_push (ctx);
3125 if (res == TYPE_INV) {
3126 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)));
3127 copy_stack_value (top, a);
3128 return;
3131 if (res & NON_VERIFIABLE_RESULT) {
3132 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)));
3134 res = res & ~NON_VERIFIABLE_RESULT;
3137 if (complexMerge && res == TYPE_PTR) {
3138 if (complexMerge == 1)
3139 copy_stack_value (top, a);
3140 else if (complexMerge == 2)
3141 copy_stack_value (top, b);
3143 * There is no need to merge the type of two pointers.
3144 * The only valid operation is subtraction, that returns a native
3145 * int as result and can be used with any 2 pointer kinds.
3146 * This is valid acording to Patition III 1.1.4
3148 } else
3149 top->stype = res;
3154 static void
3155 do_boolean_branch_op (VerifyContext *ctx, int delta)
3157 int target = ctx->ip_offset + delta;
3158 ILStackDesc *top;
3160 VERIFIER_DEBUG ( printf ("boolean branch offset %d delta %d target %d\n", ctx->ip_offset, delta, target); );
3162 if (target < 0 || target >= ctx->code_size) {
3163 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Boolean branch target out of code at 0x%04x", ctx->ip_offset));
3164 return;
3167 switch (is_valid_branch_instruction (ctx->header, ctx->ip_offset, target)) {
3168 case 1:
3169 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Branch target escapes out of exception block at 0x%04x", ctx->ip_offset));
3170 break;
3171 case 2:
3172 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Branch target escapes out of exception block at 0x%04x", ctx->ip_offset));
3173 return;
3176 ctx->target = target;
3178 if (!check_underflow (ctx, 1))
3179 return;
3181 top = stack_pop (ctx);
3182 if (!is_valid_bool_arg (top))
3183 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));
3185 check_unmanaged_pointer (ctx, top);
3188 static gboolean
3189 stack_slot_is_complex_type_not_reference_type (ILStackDesc *slot)
3191 return stack_slot_get_type (slot) == TYPE_COMPLEX && !MONO_TYPE_IS_REFERENCE (slot->type) && !stack_slot_is_boxed_value (slot);
3194 static void
3195 do_branch_op (VerifyContext *ctx, signed int delta, const unsigned char table [TYPE_MAX][TYPE_MAX])
3197 ILStackDesc *a, *b;
3198 int idxa, idxb;
3199 unsigned char res;
3200 int target = ctx->ip_offset + delta;
3202 VERIFIER_DEBUG ( printf ("branch offset %d delta %d target %d\n", ctx->ip_offset, delta, target); );
3204 if (target < 0 || target >= ctx->code_size) {
3205 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Branch target out of code at 0x%04x", ctx->ip_offset));
3206 return;
3209 switch (is_valid_cmp_branch_instruction (ctx->header, ctx->ip_offset, target)) {
3210 case 1: /*FIXME use constants and not magic numbers.*/
3211 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Branch target escapes out of exception block at 0x%04x", ctx->ip_offset));
3212 break;
3213 case 2:
3214 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Branch target escapes out of exception block at 0x%04x", ctx->ip_offset));
3215 return;
3218 ctx->target = target;
3220 if (!check_underflow (ctx, 2))
3221 return;
3223 b = stack_pop (ctx);
3224 a = stack_pop (ctx);
3226 idxa = stack_slot_get_underlying_type (a);
3227 if (stack_slot_is_managed_pointer (a))
3228 idxa = TYPE_PTR;
3230 idxb = stack_slot_get_underlying_type (b);
3231 if (stack_slot_is_managed_pointer (b))
3232 idxb = TYPE_PTR;
3234 if (stack_slot_is_complex_type_not_reference_type (a) || stack_slot_is_complex_type_not_reference_type (b)) {
3235 res = TYPE_INV;
3236 } else {
3237 --idxa;
3238 --idxb;
3239 res = table [idxa][idxb];
3242 VERIFIER_DEBUG ( printf ("branch res %d\n", res); );
3243 VERIFIER_DEBUG ( printf ("idxa %d idxb %d\n", idxa, idxb); );
3245 if (res == TYPE_INV) {
3246 CODE_NOT_VERIFIABLE (ctx,
3247 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));
3248 } else if (res & NON_VERIFIABLE_RESULT) {
3249 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));
3250 res = res & ~NON_VERIFIABLE_RESULT;
3254 static void
3255 do_cmp_op (VerifyContext *ctx, const unsigned char table [TYPE_MAX][TYPE_MAX], guint32 opcode)
3257 ILStackDesc *a, *b;
3258 int idxa, idxb;
3259 unsigned char res;
3261 if (!check_underflow (ctx, 2))
3262 return;
3263 b = stack_pop (ctx);
3264 a = stack_pop (ctx);
3266 if (opcode == CEE_CGT_UN) {
3267 if (stack_slot_get_type (a) == TYPE_COMPLEX && stack_slot_get_type (b) == TYPE_COMPLEX) {
3268 stack_push_val (ctx, TYPE_I4, &mono_defaults.int32_class->byval_arg);
3269 return;
3273 idxa = stack_slot_get_underlying_type (a);
3274 if (stack_slot_is_managed_pointer (a))
3275 idxa = TYPE_PTR;
3277 idxb = stack_slot_get_underlying_type (b);
3278 if (stack_slot_is_managed_pointer (b))
3279 idxb = TYPE_PTR;
3281 if (stack_slot_is_complex_type_not_reference_type (a) || stack_slot_is_complex_type_not_reference_type (b)) {
3282 res = TYPE_INV;
3283 } else {
3284 --idxa;
3285 --idxb;
3286 res = table [idxa][idxb];
3289 if(res == TYPE_INV) {
3290 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));
3291 } else if (res & NON_VERIFIABLE_RESULT) {
3292 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));
3293 res = res & ~NON_VERIFIABLE_RESULT;
3295 stack_push_val (ctx, TYPE_I4, &mono_defaults.int32_class->byval_arg);
3298 static void
3299 do_ret (VerifyContext *ctx)
3301 MonoType *ret = ctx->signature->ret;
3302 VERIFIER_DEBUG ( printf ("checking ret\n"); );
3303 if (ret->type != MONO_TYPE_VOID) {
3304 ILStackDesc *top;
3305 if (!check_underflow (ctx, 1))
3306 return;
3308 top = stack_pop(ctx);
3310 if (!verify_stack_type_compatibility (ctx, ctx->signature->ret, top)) {
3311 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Incompatible return value on stack with method signature ret at 0x%04x", ctx->ip_offset));
3312 return;
3315 if (ret->byref || ret->type == MONO_TYPE_TYPEDBYREF || mono_type_is_value_type (ret, "System", "ArgIterator") || mono_type_is_value_type (ret, "System", "RuntimeArgumentHandle"))
3316 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Method returns byref, TypedReference, ArgIterator or RuntimeArgumentHandle at 0x%04x", ctx->ip_offset));
3319 if (ctx->eval.size > 0) {
3320 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Stack not empty (%d) after ret at 0x%04x", ctx->eval.size, ctx->ip_offset));
3322 if (in_any_block (ctx->header, ctx->ip_offset))
3323 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("ret cannot escape exception blocks at 0x%04x", ctx->ip_offset));
3327 * 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.
3328 * This is illegal but mono_get_method_full decoded it.
3329 * TODO handle calling .ctor outside one or calling the .ctor for other class but super
3331 static void
3332 do_invoke_method (VerifyContext *ctx, int method_token, gboolean virtual)
3334 int param_count, i;
3335 MonoMethodSignature *sig;
3336 ILStackDesc *value;
3337 MonoMethod *method;
3338 gboolean virt_check_this = FALSE;
3339 gboolean constrained = ctx->prefix_set & PREFIX_CONSTRAINED;
3341 if (!(method = verifier_load_method (ctx, method_token, virtual ? "callvirt" : "call")))
3342 return;
3344 if (virtual) {
3345 CLEAR_PREFIX (ctx, PREFIX_CONSTRAINED);
3347 if (method->klass->valuetype) // && !constrained ???
3348 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use callvirtual with valuetype method at 0x%04x", ctx->ip_offset));
3350 if ((method->flags & METHOD_ATTRIBUTE_STATIC))
3351 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use callvirtual with static method at 0x%04x", ctx->ip_offset));
3353 } else {
3354 if (method->flags & METHOD_ATTRIBUTE_ABSTRACT)
3355 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use call with an abstract method at 0x%04x", ctx->ip_offset));
3357 if ((method->flags & METHOD_ATTRIBUTE_VIRTUAL) && !(method->flags & METHOD_ATTRIBUTE_FINAL)) {
3358 virt_check_this = TRUE;
3359 ctx->code [ctx->ip_offset].flags |= IL_CODE_CALL_NONFINAL_VIRTUAL;
3363 if (!(sig = mono_method_get_signature_full (method, ctx->image, method_token, ctx->generic_context)))
3364 sig = mono_method_get_signature (method, ctx->image, method_token);
3366 param_count = sig->param_count + sig->hasthis;
3367 if (!check_underflow (ctx, param_count))
3368 return;
3370 for (i = sig->param_count - 1; i >= 0; --i) {
3371 VERIFIER_DEBUG ( printf ("verifying argument %d\n", i); );
3372 value = stack_pop (ctx);
3373 if (!verify_stack_type_compatibility (ctx, sig->params[i], value)) {
3374 char *stack_name = stack_slot_full_name (value);
3375 char *sig_name = mono_type_full_name (sig->params [i]);
3376 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));
3377 g_free (stack_name);
3378 g_free (sig_name);
3381 if (stack_slot_is_managed_mutability_pointer (value))
3382 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));
3384 if ((ctx->prefix_set & PREFIX_TAIL) && stack_slot_is_managed_pointer (value)) {
3385 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));
3386 return;
3390 if (sig->hasthis) {
3391 MonoType *type = &method->klass->byval_arg;
3392 ILStackDesc copy;
3394 if (mono_method_is_constructor (method) && !method->klass->valuetype) {
3395 if (!mono_method_is_constructor (ctx->method))
3396 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot call a constructor outside one at 0x%04x", ctx->ip_offset));
3397 if (method->klass != ctx->method->klass->parent && method->klass != ctx->method->klass)
3398 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));
3400 ctx->super_ctor_called = TRUE;
3401 value = stack_pop_safe (ctx);
3402 if ((value->stype & THIS_POINTER_MASK) != THIS_POINTER_MASK)
3403 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid 'this ptr' argument for constructor at 0x%04x", ctx->ip_offset));
3404 } else {
3405 value = stack_pop (ctx);
3408 copy_stack_value (&copy, value);
3409 //TODO we should extract this to a 'drop_byref_argument' and use everywhere
3410 //Other parts of the code suffer from the same issue of
3411 copy.type = mono_type_get_type_byval (copy.type);
3412 copy.stype &= ~POINTER_MASK;
3414 if (virt_check_this && !stack_slot_is_this_pointer (value) && !(method->klass->valuetype || stack_slot_is_boxed_value (value)))
3415 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));
3417 if (constrained && virtual) {
3418 if (!stack_slot_is_managed_pointer (value))
3419 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Object is not a managed pointer for a constrained call at 0x%04x", ctx->ip_offset));
3420 if (!mono_metadata_type_equal_full (mono_type_get_type_byval (value->type), ctx->constrained_type, TRUE))
3421 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Object not compatible with constrained type at 0x%04x", ctx->ip_offset));
3422 copy.stype |= BOXED_MASK;
3423 } else {
3424 if (stack_slot_is_managed_pointer (value) && !mono_class_from_mono_type (value->type)->valuetype)
3425 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));
3427 if (!virtual && mono_class_from_mono_type (value->type)->valuetype && !method->klass->valuetype && !stack_slot_is_boxed_value (value))
3428 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot call a valuetype baseclass at 0x%04x", ctx->ip_offset));
3430 if (virtual && mono_class_from_mono_type (value->type)->valuetype && !stack_slot_is_boxed_value (value))
3431 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use a valuetype with callvirt at 0x%04x", ctx->ip_offset));
3433 if (method->klass->valuetype && (stack_slot_is_boxed_value (value) || !stack_slot_is_managed_pointer (value)))
3434 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));
3436 if (!verify_stack_type_compatibility (ctx, type, &copy))
3437 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Incompatible this argument on stack with method signature at 0x%04x", ctx->ip_offset));
3439 if (!IS_SKIP_VISIBILITY (ctx) && !mono_method_can_access_method_full (ctx->method, method, mono_class_from_mono_type (value->type))) {
3440 char *name = mono_method_full_name (method, TRUE);
3441 CODE_NOT_VERIFIABLE2 (ctx, g_strdup_printf ("Method %s is not accessible at 0x%04x", name, ctx->ip_offset), MONO_EXCEPTION_METHOD_ACCESS);
3442 g_free (name);
3445 } else if (!IS_SKIP_VISIBILITY (ctx) && !mono_method_can_access_method_full (ctx->method, method, NULL)) {
3446 char *name = mono_method_full_name (method, TRUE);
3447 CODE_NOT_VERIFIABLE2 (ctx, g_strdup_printf ("Method %s is not accessible at 0x%04x", name, ctx->ip_offset), MONO_EXCEPTION_METHOD_ACCESS);
3448 g_free (name);
3451 if (sig->ret->type != MONO_TYPE_VOID) {
3452 if (check_overflow (ctx)) {
3453 value = stack_push (ctx);
3454 set_stack_value (ctx, value, sig->ret, FALSE);
3455 if ((ctx->prefix_set & PREFIX_READONLY) && method->klass->rank && !strcmp (method->name, "Address")) {
3456 ctx->prefix_set &= ~PREFIX_READONLY;
3457 value->stype |= CMMP_MASK;
3462 if ((ctx->prefix_set & PREFIX_TAIL)) {
3463 if (!mono_delegate_ret_equal (mono_method_signature (ctx->method)->ret, sig->ret))
3464 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Tail call with incompatible return type at 0x%04x", ctx->ip_offset));
3465 if (ctx->header->code [ctx->ip_offset + 5] != CEE_RET)
3466 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Tail call not followed by ret at 0x%04x", ctx->ip_offset));
3471 static void
3472 do_push_static_field (VerifyContext *ctx, int token, gboolean take_addr)
3474 MonoClassField *field;
3475 MonoClass *klass;
3476 if (!take_addr)
3477 CLEAR_PREFIX (ctx, PREFIX_VOLATILE);
3479 if (!(field = verifier_load_field (ctx, token, &klass, take_addr ? "ldsflda" : "ldsfld")))
3480 return;
3482 if (!(field->type->attrs & FIELD_ATTRIBUTE_STATIC)) {
3483 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Cannot load non static field at 0x%04x", ctx->ip_offset));
3484 return;
3486 /*taking the address of initonly field only works from the static constructor */
3487 if (take_addr && (field->type->attrs & FIELD_ATTRIBUTE_INIT_ONLY) &&
3488 !(field->parent == ctx->method->klass && (ctx->method->flags & (METHOD_ATTRIBUTE_SPECIAL_NAME | METHOD_ATTRIBUTE_STATIC)) && !strcmp (".cctor", ctx->method->name)))
3489 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot take the address of a init-only field at 0x%04x", ctx->ip_offset));
3491 if (!IS_SKIP_VISIBILITY (ctx) && !mono_method_can_access_field_full (ctx->method, field, NULL))
3492 CODE_NOT_VERIFIABLE2 (ctx, g_strdup_printf ("Type at stack is not accessible at 0x%04x", ctx->ip_offset), MONO_EXCEPTION_FIELD_ACCESS);
3494 set_stack_value (ctx, stack_push (ctx), field->type, take_addr);
3497 static void
3498 do_store_static_field (VerifyContext *ctx, int token) {
3499 MonoClassField *field;
3500 MonoClass *klass;
3501 ILStackDesc *value;
3502 CLEAR_PREFIX (ctx, PREFIX_VOLATILE);
3504 if (!check_underflow (ctx, 1))
3505 return;
3507 value = stack_pop (ctx);
3509 if (!(field = verifier_load_field (ctx, token, &klass, "stsfld")))
3510 return;
3512 if (!(field->type->attrs & FIELD_ATTRIBUTE_STATIC)) {
3513 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Cannot store non static field at 0x%04x", ctx->ip_offset));
3514 return;
3517 if (field->type->type == MONO_TYPE_TYPEDBYREF) {
3518 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Typedbyref field is an unverfiable type in store static field at 0x%04x", ctx->ip_offset));
3519 return;
3522 if (!IS_SKIP_VISIBILITY (ctx) && !mono_method_can_access_field_full (ctx->method, field, NULL))
3523 CODE_NOT_VERIFIABLE2 (ctx, g_strdup_printf ("Type at stack is not accessible at 0x%04x", ctx->ip_offset), MONO_EXCEPTION_FIELD_ACCESS);
3525 if (!verify_stack_type_compatibility (ctx, field->type, value))
3526 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));
3529 static gboolean
3530 check_is_valid_type_for_field_ops (VerifyContext *ctx, int token, ILStackDesc *obj, MonoClassField **ret_field, const char *opcode)
3532 MonoClassField *field;
3533 MonoClass *klass;
3534 gboolean is_pointer;
3536 /*must be a reference type, a managed pointer, an unamanaged pointer, or a valuetype*/
3537 if (!(field = verifier_load_field (ctx, token, &klass, opcode)))
3538 return FALSE;
3540 *ret_field = field;
3541 //the value on stack is going to be used as a pointer
3542 is_pointer = stack_slot_get_type (obj) == TYPE_PTR || (stack_slot_get_type (obj) == TYPE_NATIVE_INT && !get_stack_type (&field->parent->byval_arg));
3544 if (field->type->type == MONO_TYPE_TYPEDBYREF) {
3545 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Typedbyref field is an unverfiable type at 0x%04x", ctx->ip_offset));
3546 return FALSE;
3548 g_assert (obj->type);
3550 /*The value on the stack must be a subclass of the defining type of the field*/
3551 /* we need to check if we can load the field from the stack value*/
3552 if (is_pointer) {
3553 if (stack_slot_get_underlying_type (obj) == TYPE_NATIVE_INT)
3554 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Native int is not a verifiable type to reference a field at 0x%04x", ctx->ip_offset));
3556 if (!IS_SKIP_VISIBILITY (ctx) && !mono_method_can_access_field_full (ctx->method, field, NULL))
3557 CODE_NOT_VERIFIABLE2 (ctx, g_strdup_printf ("Type at stack is not accessible at 0x%04x", ctx->ip_offset), MONO_EXCEPTION_FIELD_ACCESS);
3558 } else {
3559 if (!field->parent->valuetype && stack_slot_is_managed_pointer (obj))
3560 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));
3562 /*a value type can be loaded from a value or a managed pointer, but not a boxed object*/
3563 if (field->parent->valuetype && stack_slot_is_boxed_value (obj))
3564 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));
3566 if (!stack_slot_is_null_literal (obj) && !verify_stack_type_compatibility_full (ctx, &field->parent->byval_arg, obj, TRUE, FALSE))
3567 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Type at stack is not compatible to reference the field at 0x%04x", ctx->ip_offset));
3569 if (!IS_SKIP_VISIBILITY (ctx) && !mono_method_can_access_field_full (ctx->method, field, mono_class_from_mono_type (obj->type)))
3570 CODE_NOT_VERIFIABLE2 (ctx, g_strdup_printf ("Type at stack is not accessible at 0x%04x", ctx->ip_offset), MONO_EXCEPTION_FIELD_ACCESS);
3573 check_unmanaged_pointer (ctx, obj);
3574 return TRUE;
3577 static void
3578 do_push_field (VerifyContext *ctx, int token, gboolean take_addr)
3580 ILStackDesc *obj;
3581 MonoClassField *field;
3583 if (!take_addr)
3584 CLEAR_PREFIX (ctx, PREFIX_UNALIGNED | PREFIX_VOLATILE);
3586 if (!check_underflow (ctx, 1))
3587 return;
3588 obj = stack_pop_safe (ctx);
3590 if (!check_is_valid_type_for_field_ops (ctx, token, obj, &field, take_addr ? "ldflda" : "ldfld"))
3591 return;
3593 if (take_addr && field->parent->valuetype && !stack_slot_is_managed_pointer (obj))
3594 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot take the address of a temporary value-type at 0x%04x", ctx->ip_offset));
3596 if (take_addr && (field->type->attrs & FIELD_ATTRIBUTE_INIT_ONLY) &&
3597 !(field->parent == ctx->method->klass && mono_method_is_constructor (ctx->method)))
3598 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot take the address of a init-only field at 0x%04x", ctx->ip_offset));
3600 set_stack_value (ctx, stack_push (ctx), field->type, take_addr);
3603 static void
3604 do_store_field (VerifyContext *ctx, int token)
3606 ILStackDesc *value, *obj;
3607 MonoClassField *field;
3608 CLEAR_PREFIX (ctx, PREFIX_UNALIGNED | PREFIX_VOLATILE);
3610 if (!check_underflow (ctx, 2))
3611 return;
3613 value = stack_pop (ctx);
3614 obj = stack_pop_safe (ctx);
3616 if (!check_is_valid_type_for_field_ops (ctx, token, obj, &field, "stfld"))
3617 return;
3619 if (!verify_stack_type_compatibility (ctx, field->type, value))
3620 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Incompatible type %s in field store at 0x%04x", stack_slot_get_name (value), ctx->ip_offset));
3623 /*TODO proper handle for Nullable<T>*/
3624 static void
3625 do_box_value (VerifyContext *ctx, int klass_token)
3627 ILStackDesc *value;
3628 MonoType *type = get_boxable_mono_type (ctx, klass_token, "box");
3629 MonoClass *klass;
3631 if (!type)
3632 return;
3634 if (!check_underflow (ctx, 1))
3635 return;
3637 value = stack_pop (ctx);
3638 /*box is a nop for reference types*/
3640 if (stack_slot_get_underlying_type (value) == TYPE_COMPLEX && MONO_TYPE_IS_REFERENCE (value->type) && MONO_TYPE_IS_REFERENCE (type)) {
3641 stack_push_stack_val (ctx, value)->stype |= BOXED_MASK;
3642 return;
3646 if (!verify_stack_type_compatibility (ctx, type, value))
3647 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid type at stack for boxing operation at 0x%04x", ctx->ip_offset));
3649 klass = mono_class_from_mono_type (type);
3650 if (mono_class_is_nullable (klass))
3651 type = &mono_class_get_nullable_param (klass)->byval_arg;
3652 stack_push_val (ctx, TYPE_COMPLEX | BOXED_MASK, type);
3655 static void
3656 do_unbox_value (VerifyContext *ctx, int klass_token)
3658 ILStackDesc *value;
3659 MonoType *type = get_boxable_mono_type (ctx, klass_token, "unbox");
3661 if (!type)
3662 return;
3664 if (!check_underflow (ctx, 1))
3665 return;
3667 if (!mono_class_from_mono_type (type)->valuetype)
3668 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid reference type for unbox at 0x%04x", ctx->ip_offset));
3670 value = stack_pop (ctx);
3672 /*Value should be: a boxed valuetype or a reference type*/
3673 if (!(stack_slot_get_type (value) == TYPE_COMPLEX &&
3674 (stack_slot_is_boxed_value (value) || !mono_class_from_mono_type (value->type)->valuetype)))
3675 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));
3677 set_stack_value (ctx, value = stack_push (ctx), mono_type_get_type_byref (type), FALSE);
3678 value->stype |= CMMP_MASK;
3681 static void
3682 do_unbox_any (VerifyContext *ctx, int klass_token)
3684 ILStackDesc *value;
3685 MonoType *type = get_boxable_mono_type (ctx, klass_token, "unbox.any");
3687 if (!type)
3688 return;
3690 if (!check_underflow (ctx, 1))
3691 return;
3693 value = stack_pop (ctx);
3695 /*Value should be: a boxed valuetype or a reference type*/
3696 if (!(stack_slot_get_type (value) == TYPE_COMPLEX &&
3697 (stack_slot_is_boxed_value (value) || !mono_class_from_mono_type (value->type)->valuetype)))
3698 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));
3700 set_stack_value (ctx, stack_push (ctx), type, FALSE);
3703 static void
3704 do_unary_math_op (VerifyContext *ctx, int op)
3706 ILStackDesc *value;
3707 if (!check_underflow (ctx, 1))
3708 return;
3709 value = stack_pop (ctx);
3710 switch (stack_slot_get_type (value)) {
3711 case TYPE_I4:
3712 case TYPE_I8:
3713 case TYPE_NATIVE_INT:
3714 break;
3715 case TYPE_R8:
3716 if (op == CEE_NEG)
3717 break;
3718 case TYPE_COMPLEX: /*only enums are ok*/
3719 if (mono_type_is_enum_type (value->type))
3720 break;
3721 default:
3722 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid type at stack for unary not at 0x%04x", ctx->ip_offset));
3724 stack_push_stack_val (ctx, value);
3727 static void
3728 do_conversion (VerifyContext *ctx, int kind)
3730 ILStackDesc *value;
3731 if (!check_underflow (ctx, 1))
3732 return;
3733 value = stack_pop (ctx);
3735 switch (stack_slot_get_type (value)) {
3736 case TYPE_I4:
3737 case TYPE_I8:
3738 case TYPE_NATIVE_INT:
3739 case TYPE_R8:
3740 break;
3741 default:
3742 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));
3745 switch (kind) {
3746 case TYPE_I4:
3747 stack_push_val (ctx, TYPE_I4, &mono_defaults.int32_class->byval_arg);
3748 break;
3749 case TYPE_I8:
3750 stack_push_val (ctx,TYPE_I8, &mono_defaults.int64_class->byval_arg);
3751 break;
3752 case TYPE_R8:
3753 stack_push_val (ctx, TYPE_R8, &mono_defaults.double_class->byval_arg);
3754 break;
3755 case TYPE_NATIVE_INT:
3756 stack_push_val (ctx, TYPE_NATIVE_INT, &mono_defaults.int_class->byval_arg);
3757 break;
3758 default:
3759 g_error ("unknown type %02x in conversion", kind);
3764 static void
3765 do_load_token (VerifyContext *ctx, int token)
3767 gpointer handle;
3768 MonoClass *handle_class;
3769 if (!check_overflow (ctx))
3770 return;
3771 handle = mono_ldtoken (ctx->image, token, &handle_class, ctx->generic_context);
3772 if (!handle) {
3773 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid token 0x%x for ldtoken at 0x%04x", token, ctx->ip_offset));
3774 return;
3776 if (handle_class == mono_defaults.typehandle_class) {
3777 mono_type_is_valid_in_context (ctx, (MonoType*)handle);
3778 } else if (handle_class == mono_defaults.methodhandle_class) {
3779 mono_method_is_valid_in_context (ctx, (MonoMethod*)handle);
3780 } else if (handle_class == mono_defaults.fieldhandle_class) {
3781 mono_type_is_valid_in_context (ctx, &((MonoClassField*)handle)->parent->byval_arg);
3782 } else {
3783 ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid ldtoken type %x at 0x%04x", token, ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE);
3785 stack_push_val (ctx, TYPE_COMPLEX, mono_class_get_type (handle_class));
3788 static void
3789 do_ldobj_value (VerifyContext *ctx, int token)
3791 ILStackDesc *value;
3792 MonoType *type = get_boxable_mono_type (ctx, token, "ldobj");
3793 CLEAR_PREFIX (ctx, PREFIX_UNALIGNED | PREFIX_VOLATILE);
3795 if (!type)
3796 return;
3798 if (!check_underflow (ctx, 1))
3799 return;
3801 value = stack_pop (ctx);
3802 if (!stack_slot_is_managed_pointer (value)
3803 && stack_slot_get_type (value) != TYPE_NATIVE_INT
3804 && !(stack_slot_get_type (value) == TYPE_PTR && value->type->type != MONO_TYPE_FNPTR)) {
3805 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid argument %s to ldobj at 0x%04x", stack_slot_get_name (value), ctx->ip_offset));
3806 return;
3809 if (stack_slot_get_type (value) == TYPE_NATIVE_INT)
3810 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Using native pointer to ldobj at 0x%04x", ctx->ip_offset));
3812 /*We have a byval on the stack, but the comparison must be strict. */
3813 if (!verify_type_compatibility_full (ctx, type, mono_type_get_type_byval (value->type), TRUE))
3814 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid type at stack for ldojb operation at 0x%04x", ctx->ip_offset));
3816 set_stack_value (ctx, stack_push (ctx), type, FALSE);
3819 static void
3820 do_stobj (VerifyContext *ctx, int token)
3822 ILStackDesc *dest, *src;
3823 MonoType *type = get_boxable_mono_type (ctx, token, "stobj");
3824 CLEAR_PREFIX (ctx, PREFIX_UNALIGNED | PREFIX_VOLATILE);
3826 if (!type)
3827 return;
3829 if (!check_underflow (ctx, 2))
3830 return;
3832 src = stack_pop (ctx);
3833 dest = stack_pop (ctx);
3835 if (stack_slot_is_managed_mutability_pointer (dest))
3836 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use a readonly pointer with stobj at 0x%04x", ctx->ip_offset));
3838 if (!stack_slot_is_managed_pointer (dest))
3839 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid destination of stobj operation at 0x%04x", ctx->ip_offset));
3841 if (stack_slot_is_boxed_value (src) && !MONO_TYPE_IS_REFERENCE (src->type) && !MONO_TYPE_IS_REFERENCE (type))
3842 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));
3844 if (!verify_stack_type_compatibility (ctx, type, src))
3845 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Token and source types of stobj don't match at 0x%04x", ctx->ip_offset));
3847 if (!verify_type_compatibility (ctx, mono_type_get_type_byval (dest->type), type))
3848 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Destination and token types of stobj don't match at 0x%04x", ctx->ip_offset));
3851 static void
3852 do_cpobj (VerifyContext *ctx, int token)
3854 ILStackDesc *dest, *src;
3855 MonoType *type = get_boxable_mono_type (ctx, token, "cpobj");
3856 if (!type)
3857 return;
3859 if (!check_underflow (ctx, 2))
3860 return;
3862 src = stack_pop (ctx);
3863 dest = stack_pop (ctx);
3865 if (!stack_slot_is_managed_pointer (src))
3866 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid source of cpobj operation at 0x%04x", ctx->ip_offset));
3868 if (!stack_slot_is_managed_pointer (dest))
3869 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid destination of cpobj operation at 0x%04x", ctx->ip_offset));
3871 if (stack_slot_is_managed_mutability_pointer (dest))
3872 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use a readonly pointer with cpobj at 0x%04x", ctx->ip_offset));
3874 if (!verify_type_compatibility (ctx, type, mono_type_get_type_byval (src->type)))
3875 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Token and source types of cpobj don't match at 0x%04x", ctx->ip_offset));
3877 if (!verify_type_compatibility (ctx, mono_type_get_type_byval (dest->type), type))
3878 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Destination and token types of cpobj don't match at 0x%04x", ctx->ip_offset));
3881 static void
3882 do_initobj (VerifyContext *ctx, int token)
3884 ILStackDesc *obj;
3885 MonoType *stack, *type = get_boxable_mono_type (ctx, token, "initobj");
3886 if (!type)
3887 return;
3889 if (!check_underflow (ctx, 1))
3890 return;
3892 obj = stack_pop (ctx);
3894 if (!stack_slot_is_managed_pointer (obj))
3895 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid object address for initobj at 0x%04x", ctx->ip_offset));
3897 if (stack_slot_is_managed_mutability_pointer (obj))
3898 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use a readonly pointer with initobj at 0x%04x", ctx->ip_offset));
3900 stack = mono_type_get_type_byval (obj->type);
3901 if (MONO_TYPE_IS_REFERENCE (stack)) {
3902 if (!verify_type_compatibility (ctx, stack, type))
3903 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Type token of initobj not compatible with value on stack at 0x%04x", ctx->ip_offset));
3904 else if (IS_STRICT_MODE (ctx) && !mono_metadata_type_equal (type, stack))
3905 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Type token of initobj not compatible with value on stack at 0x%04x", ctx->ip_offset));
3906 } else if (!verify_type_compatibility (ctx, stack, type)) {
3907 char *expected_name = mono_type_full_name (type);
3908 char *stack_name = mono_type_full_name (stack);
3910 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));
3911 g_free (expected_name);
3912 g_free (stack_name);
3916 static void
3917 do_newobj (VerifyContext *ctx, int token)
3919 ILStackDesc *value;
3920 int i;
3921 MonoMethodSignature *sig;
3922 MonoMethod *method;
3923 gboolean is_delegate = FALSE;
3925 if (!(method = verifier_load_method (ctx, token, "newobj")))
3926 return;
3928 if (!mono_method_is_constructor (method)) {
3929 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Method from token 0x%08x not a constructor at 0x%04x", token, ctx->ip_offset));
3930 return;
3933 if (method->klass->flags & (TYPE_ATTRIBUTE_ABSTRACT | TYPE_ATTRIBUTE_INTERFACE))
3934 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Trying to instantiate an abstract or interface type at 0x%04x", ctx->ip_offset));
3936 if (!mono_method_can_access_method_full (ctx->method, method, NULL)) {
3937 char *from = mono_method_full_name (ctx->method, TRUE);
3938 char *to = mono_method_full_name (method, TRUE);
3939 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);
3940 g_free (from);
3941 g_free (to);
3944 //FIXME use mono_method_get_signature_full
3945 sig = mono_method_signature (method);
3946 if (!check_underflow (ctx, sig->param_count))
3947 return;
3949 is_delegate = method->klass->parent == mono_defaults.multicastdelegate_class;
3951 if (is_delegate) {
3952 ILStackDesc *funptr;
3953 //first arg is object, second arg is fun ptr
3954 if (sig->param_count != 2) {
3955 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid delegate constructor at 0x%04x", ctx->ip_offset));
3956 return;
3958 funptr = stack_pop (ctx);
3959 value = stack_pop (ctx);
3960 verify_delegate_compatibility (ctx, method->klass, value, funptr);
3961 } else {
3962 for (i = sig->param_count - 1; i >= 0; --i) {
3963 VERIFIER_DEBUG ( printf ("verifying constructor argument %d\n", i); );
3964 value = stack_pop (ctx);
3965 if (!verify_stack_type_compatibility (ctx, sig->params [i], value)) {
3966 char *stack_name = stack_slot_full_name (value);
3967 char *sig_name = mono_type_full_name (sig->params [i]);
3968 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));
3969 g_free (stack_name);
3970 g_free (sig_name);
3973 if (stack_slot_is_managed_mutability_pointer (value))
3974 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use a readonly pointer as argument of newobj at 0x%04x", ctx->ip_offset));
3978 if (check_overflow (ctx))
3979 set_stack_value (ctx, stack_push (ctx), &method->klass->byval_arg, FALSE);
3982 static void
3983 do_cast (VerifyContext *ctx, int token, const char *opcode) {
3984 ILStackDesc *value;
3985 MonoType *type;
3986 gboolean is_boxed;
3987 gboolean do_box;
3989 if (!check_underflow (ctx, 1))
3990 return;
3992 if (!(type = verifier_load_type (ctx, token, opcode)))
3993 return;
3995 if (type->byref) {
3996 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid %s type at 0x%04x", opcode, ctx->ip_offset));
3997 return;
4000 value = stack_pop (ctx);
4001 is_boxed = stack_slot_is_boxed_value (value);
4003 if (stack_slot_is_managed_pointer (value))
4004 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid value for %s at 0x%04x", opcode, ctx->ip_offset));
4005 else if (!MONO_TYPE_IS_REFERENCE (value->type) && !is_boxed) {
4006 char *name = stack_slot_full_name (value);
4007 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Expected a reference type on stack for %s but found %s at 0x%04x", opcode, name, ctx->ip_offset));
4008 g_free (name);
4011 switch (value->type->type) {
4012 case MONO_TYPE_FNPTR:
4013 case MONO_TYPE_PTR:
4014 case MONO_TYPE_TYPEDBYREF:
4015 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid value for %s at 0x%04x", opcode, ctx->ip_offset));
4018 do_box = is_boxed || mono_type_is_generic_argument(type) || mono_class_from_mono_type (type)->valuetype;
4019 stack_push_val (ctx, TYPE_COMPLEX | (do_box ? BOXED_MASK : 0), type);
4022 static MonoType *
4023 mono_type_from_opcode (int opcode) {
4024 switch (opcode) {
4025 case CEE_LDIND_I1:
4026 case CEE_LDIND_U1:
4027 case CEE_STIND_I1:
4028 case CEE_LDELEM_I1:
4029 case CEE_LDELEM_U1:
4030 case CEE_STELEM_I1:
4031 return &mono_defaults.sbyte_class->byval_arg;
4033 case CEE_LDIND_I2:
4034 case CEE_LDIND_U2:
4035 case CEE_STIND_I2:
4036 case CEE_LDELEM_I2:
4037 case CEE_LDELEM_U2:
4038 case CEE_STELEM_I2:
4039 return &mono_defaults.int16_class->byval_arg;
4041 case CEE_LDIND_I4:
4042 case CEE_LDIND_U4:
4043 case CEE_STIND_I4:
4044 case CEE_LDELEM_I4:
4045 case CEE_LDELEM_U4:
4046 case CEE_STELEM_I4:
4047 return &mono_defaults.int32_class->byval_arg;
4049 case CEE_LDIND_I8:
4050 case CEE_STIND_I8:
4051 case CEE_LDELEM_I8:
4052 case CEE_STELEM_I8:
4053 return &mono_defaults.int64_class->byval_arg;
4055 case CEE_LDIND_R4:
4056 case CEE_STIND_R4:
4057 case CEE_LDELEM_R4:
4058 case CEE_STELEM_R4:
4059 return &mono_defaults.single_class->byval_arg;
4061 case CEE_LDIND_R8:
4062 case CEE_STIND_R8:
4063 case CEE_LDELEM_R8:
4064 case CEE_STELEM_R8:
4065 return &mono_defaults.double_class->byval_arg;
4067 case CEE_LDIND_I:
4068 case CEE_STIND_I:
4069 case CEE_LDELEM_I:
4070 case CEE_STELEM_I:
4071 return &mono_defaults.int_class->byval_arg;
4073 case CEE_LDIND_REF:
4074 case CEE_STIND_REF:
4075 case CEE_LDELEM_REF:
4076 case CEE_STELEM_REF:
4077 return &mono_defaults.object_class->byval_arg;
4079 default:
4080 g_error ("unknown opcode %02x in mono_type_from_opcode ", opcode);
4081 return NULL;
4085 static void
4086 do_load_indirect (VerifyContext *ctx, int opcode)
4088 ILStackDesc *value;
4089 CLEAR_PREFIX (ctx, PREFIX_UNALIGNED | PREFIX_VOLATILE);
4091 if (!check_underflow (ctx, 1))
4092 return;
4094 value = stack_pop (ctx);
4095 if (!stack_slot_is_managed_pointer (value)) {
4096 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Load indirect not using a manager pointer at 0x%04x", ctx->ip_offset));
4097 set_stack_value (ctx, stack_push (ctx), mono_type_from_opcode (opcode), FALSE);
4098 return;
4101 if (opcode == CEE_LDIND_REF) {
4102 if (stack_slot_get_underlying_type (value) != TYPE_COMPLEX || mono_class_from_mono_type (value->type)->valuetype)
4103 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid type at stack for ldind_ref expected object byref operation at 0x%04x", ctx->ip_offset));
4104 set_stack_value (ctx, stack_push (ctx), mono_type_get_type_byval (value->type), FALSE);
4105 } else {
4106 if (!verify_type_compatibility_full (ctx, mono_type_from_opcode (opcode), mono_type_get_type_byval (value->type), TRUE))
4107 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid type at stack for ldind 0x%x operation at 0x%04x", opcode, ctx->ip_offset));
4108 set_stack_value (ctx, stack_push (ctx), mono_type_from_opcode (opcode), FALSE);
4112 static void
4113 do_store_indirect (VerifyContext *ctx, int opcode)
4115 ILStackDesc *addr, *val;
4116 CLEAR_PREFIX (ctx, PREFIX_UNALIGNED | PREFIX_VOLATILE);
4118 if (!check_underflow (ctx, 2))
4119 return;
4121 val = stack_pop (ctx);
4122 addr = stack_pop (ctx);
4124 check_unmanaged_pointer (ctx, addr);
4126 if (!stack_slot_is_managed_pointer (addr) && stack_slot_get_type (addr) != TYPE_PTR) {
4127 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid non-pointer argument to stind at 0x%04x", ctx->ip_offset));
4128 return;
4131 if (stack_slot_is_managed_mutability_pointer (addr)) {
4132 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use a readonly pointer with stind at 0x%04x", ctx->ip_offset));
4133 return;
4136 if (!verify_type_compatibility_full (ctx, mono_type_from_opcode (opcode), mono_type_get_type_byval (addr->type), TRUE))
4137 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid addr type at stack for stind 0x%x operation at 0x%04x", opcode, ctx->ip_offset));
4139 if (!verify_stack_type_compatibility (ctx, mono_type_from_opcode (opcode), val))
4140 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid value type at stack for stind 0x%x operation at 0x%04x", opcode, ctx->ip_offset));
4143 static void
4144 do_newarr (VerifyContext *ctx, int token)
4146 ILStackDesc *value;
4147 MonoType *type = get_boxable_mono_type (ctx, token, "newarr");
4149 if (!type)
4150 return;
4152 if (!check_underflow (ctx, 1))
4153 return;
4155 value = stack_pop (ctx);
4156 if (stack_slot_get_type (value) != TYPE_I4 && stack_slot_get_type (value) != TYPE_NATIVE_INT)
4157 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));
4159 set_stack_value (ctx, stack_push (ctx), mono_class_get_type (mono_array_class_get (mono_class_from_mono_type (type), 1)), FALSE);
4162 /*FIXME handle arrays that are not 0-indexed*/
4163 static void
4164 do_ldlen (VerifyContext *ctx)
4166 ILStackDesc *value;
4168 if (!check_underflow (ctx, 1))
4169 return;
4171 value = stack_pop (ctx);
4173 if (stack_slot_get_type (value) != TYPE_COMPLEX || value->type->type != MONO_TYPE_SZARRAY)
4174 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type for ldlen at 0x%04x", ctx->ip_offset));
4176 stack_push_val (ctx, TYPE_NATIVE_INT, &mono_defaults.int_class->byval_arg);
4179 /*FIXME handle arrays that are not 0-indexed*/
4180 /*FIXME handle readonly prefix and CMMP*/
4181 static void
4182 do_ldelema (VerifyContext *ctx, int klass_token)
4184 ILStackDesc *index, *array, *res;
4185 MonoType *type = get_boxable_mono_type (ctx, klass_token, "ldelema");
4186 gboolean valid;
4188 if (!type)
4189 return;
4191 if (!check_underflow (ctx, 2))
4192 return;
4194 index = stack_pop (ctx);
4195 array = stack_pop (ctx);
4197 if (stack_slot_get_type (index) != TYPE_I4 && stack_slot_get_type (index) != TYPE_NATIVE_INT)
4198 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));
4200 if (!stack_slot_is_null_literal (array)) {
4201 if (stack_slot_get_type (array) != TYPE_COMPLEX || array->type->type != MONO_TYPE_SZARRAY)
4202 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type(%s) for ldelema at 0x%04x", stack_slot_get_name (array), ctx->ip_offset));
4203 else {
4204 if (get_stack_type (type) == TYPE_I4 || get_stack_type (type) == TYPE_NATIVE_INT) {
4205 valid = verify_type_compatibility_full (ctx, type, &array->type->data.klass->byval_arg, TRUE);
4206 } else {
4207 valid = mono_metadata_type_equal (type, &array->type->data.klass->byval_arg);
4209 if (!valid)
4210 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type on stack for ldelema at 0x%04x", ctx->ip_offset));
4214 res = stack_push (ctx);
4215 set_stack_value (ctx, res, type, TRUE);
4216 if (ctx->prefix_set & PREFIX_READONLY) {
4217 ctx->prefix_set &= ~PREFIX_READONLY;
4218 res->stype |= CMMP_MASK;
4223 * FIXME handle arrays that are not 0-indexed
4224 * FIXME handle readonly prefix and CMMP
4226 static void
4227 do_ldelem (VerifyContext *ctx, int opcode, int token)
4229 #define IS_ONE_OF2(T, A, B) (T == A || T == B)
4230 ILStackDesc *index, *array;
4231 MonoType *type;
4232 if (!check_underflow (ctx, 2))
4233 return;
4235 if (opcode == CEE_LDELEM) {
4236 if (!(type = verifier_load_type (ctx, token, "ldelem.any"))) {
4237 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Type (0x%08x) not found at 0x%04x", token, ctx->ip_offset));
4238 return;
4240 } else {
4241 type = mono_type_from_opcode (opcode);
4244 index = stack_pop (ctx);
4245 array = stack_pop (ctx);
4247 if (stack_slot_get_type (index) != TYPE_I4 && stack_slot_get_type (index) != TYPE_NATIVE_INT)
4248 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));
4250 if (!stack_slot_is_null_literal (array)) {
4251 if (stack_slot_get_type (array) != TYPE_COMPLEX || array->type->type != MONO_TYPE_SZARRAY)
4252 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));
4253 else {
4254 if (opcode == CEE_LDELEM_REF) {
4255 if (array->type->data.klass->valuetype)
4256 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type is not a reference type for ldelem.ref 0x%04x", ctx->ip_offset));
4257 type = &array->type->data.klass->byval_arg;
4258 } else {
4259 MonoType *candidate = &array->type->data.klass->byval_arg;
4260 if (IS_STRICT_MODE (ctx)) {
4261 MonoType *underlying_type = mono_type_get_underlying_type_any (type);
4262 MonoType *underlying_candidate = mono_type_get_underlying_type_any (candidate);
4263 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)) ||
4264 (IS_ONE_OF2 (underlying_candidate->type, MONO_TYPE_I4, MONO_TYPE_U4) && IS_ONE_OF2 (underlying_type->type, MONO_TYPE_I, MONO_TYPE_U)))
4265 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type on stack for ldelem.X at 0x%04x", ctx->ip_offset));
4267 if (!verify_type_compatibility_full (ctx, type, candidate, TRUE))
4268 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type on stack for ldelem.X at 0x%04x", ctx->ip_offset));
4273 set_stack_value (ctx, stack_push (ctx), type, FALSE);
4274 #undef IS_ONE_OF2
4278 * FIXME handle arrays that are not 0-indexed
4280 static void
4281 do_stelem (VerifyContext *ctx, int opcode, int token)
4283 ILStackDesc *index, *array, *value;
4284 MonoType *type;
4285 if (!check_underflow (ctx, 3))
4286 return;
4288 if (opcode == CEE_STELEM) {
4289 if (!(type = verifier_load_type (ctx, token, "stelem.any"))) {
4290 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Type (0x%08x) not found at 0x%04x", token, ctx->ip_offset));
4291 return;
4293 } else {
4294 type = mono_type_from_opcode (opcode);
4297 value = stack_pop (ctx);
4298 index = stack_pop (ctx);
4299 array = stack_pop (ctx);
4301 if (stack_slot_get_type (index) != TYPE_I4 && stack_slot_get_type (index) != TYPE_NATIVE_INT)
4302 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));
4304 if (!stack_slot_is_null_literal (array)) {
4305 if (stack_slot_get_type (array) != TYPE_COMPLEX || array->type->type != MONO_TYPE_SZARRAY) {
4306 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));
4307 } else {
4308 if (opcode == CEE_STELEM_REF) {
4309 if (array->type->data.klass->valuetype)
4310 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type is not a reference type for stelem.ref 0x%04x", ctx->ip_offset));
4311 } else if (!verify_type_compatibility_full (ctx, &array->type->data.klass->byval_arg, type, TRUE)) {
4312 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type on stack for stdelem.X at 0x%04x", ctx->ip_offset));
4316 if (opcode == CEE_STELEM_REF) {
4317 if (!stack_slot_is_boxed_value (value) && mono_class_from_mono_type (value->type)->valuetype)
4318 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid value is not a reference type for stelem.ref 0x%04x", ctx->ip_offset));
4319 } else if (opcode != CEE_STELEM_REF) {
4320 if (!verify_stack_type_compatibility (ctx, type, value))
4321 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid value on stack for stdelem.X at 0x%04x", ctx->ip_offset));
4323 if (stack_slot_is_boxed_value (value) && !MONO_TYPE_IS_REFERENCE (value->type) && !MONO_TYPE_IS_REFERENCE (type))
4324 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));
4329 static void
4330 do_throw (VerifyContext *ctx)
4332 ILStackDesc *exception;
4333 if (!check_underflow (ctx, 1))
4334 return;
4335 exception = stack_pop (ctx);
4337 if (!stack_slot_is_null_literal (exception) && !(stack_slot_get_type (exception) == TYPE_COMPLEX && !mono_class_from_mono_type (exception->type)->valuetype))
4338 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid type on stack for throw, expected reference type at 0x%04x", ctx->ip_offset));
4340 if (mono_type_is_generic_argument (exception->type) && !stack_slot_is_boxed_value (exception)) {
4341 char *name = mono_type_full_name (exception->type);
4342 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));
4343 g_free (name);
4345 /*The stack is left empty after a throw*/
4346 ctx->eval.size = 0;
4350 static void
4351 do_endfilter (VerifyContext *ctx)
4353 MonoExceptionClause *clause;
4355 if (IS_STRICT_MODE (ctx)) {
4356 if (ctx->eval.size != 1)
4357 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Stack size must have one item for endfilter at 0x%04x", ctx->ip_offset));
4359 if (ctx->eval.size >= 1 && stack_slot_get_type (stack_pop (ctx)) != TYPE_I4)
4360 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Stack item type is not an int32 for endfilter at 0x%04x", ctx->ip_offset));
4363 if ((clause = is_correct_endfilter (ctx, ctx->ip_offset))) {
4364 if (IS_STRICT_MODE (ctx)) {
4365 if (ctx->ip_offset != clause->handler_offset - 2)
4366 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("endfilter is not the last instruction of the filter clause at 0x%04x", ctx->ip_offset));
4367 } else {
4368 if ((ctx->ip_offset != clause->handler_offset - 2) && !MONO_OFFSET_IN_HANDLER (clause, ctx->ip_offset))
4369 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("endfilter is not the last instruction of the filter clause at 0x%04x", ctx->ip_offset));
4371 } else {
4372 if (IS_STRICT_MODE (ctx) && !is_unverifiable_endfilter (ctx, ctx->ip_offset))
4373 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("endfilter outside filter clause at 0x%04x", ctx->ip_offset));
4374 else
4375 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("endfilter outside filter clause at 0x%04x", ctx->ip_offset));
4378 ctx->eval.size = 0;
4381 static void
4382 do_leave (VerifyContext *ctx, int delta)
4384 int target = ((gint32)ctx->ip_offset) + delta;
4385 if (target >= ctx->code_size || target < 0)
4386 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Branch target out of code at 0x%04x", ctx->ip_offset));
4388 if (!is_correct_leave (ctx->header, ctx->ip_offset, target))
4389 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Leave not allowed in finally block at 0x%04x", ctx->ip_offset));
4390 ctx->eval.size = 0;
4394 * do_static_branch:
4396 * Verify br and br.s opcodes.
4398 static void
4399 do_static_branch (VerifyContext *ctx, int delta)
4401 int target = ctx->ip_offset + delta;
4402 if (target < 0 || target >= ctx->code_size) {
4403 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("branch target out of code at 0x%04x", ctx->ip_offset));
4404 return;
4407 switch (is_valid_branch_instruction (ctx->header, ctx->ip_offset, target)) {
4408 case 1:
4409 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Branch target escapes out of exception block at 0x%04x", ctx->ip_offset));
4410 break;
4411 case 2:
4412 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Branch target escapes out of exception block at 0x%04x", ctx->ip_offset));
4413 break;
4416 ctx->target = target;
4419 static void
4420 do_switch (VerifyContext *ctx, int count, const unsigned char *data)
4422 int i, base = ctx->ip_offset + 5 + count * 4;
4423 ILStackDesc *value;
4425 if (!check_underflow (ctx, 1))
4426 return;
4428 value = stack_pop (ctx);
4430 if (stack_slot_get_type (value) != TYPE_I4 && stack_slot_get_type (value) != TYPE_NATIVE_INT)
4431 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid argument to switch at 0x%04x", ctx->ip_offset));
4433 for (i = 0; i < count; ++i) {
4434 int target = base + read32 (data + i * 4);
4436 if (target < 0 || target >= ctx->code_size) {
4437 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Switch target %x out of code at 0x%04x", i, ctx->ip_offset));
4438 return;
4441 switch (is_valid_branch_instruction (ctx->header, ctx->ip_offset, target)) {
4442 case 1:
4443 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Switch target %x escapes out of exception block at 0x%04x", i, ctx->ip_offset));
4444 break;
4445 case 2:
4446 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Switch target %x escapes out of exception block at 0x%04x", i, ctx->ip_offset));
4447 return;
4449 merge_stacks (ctx, &ctx->eval, &ctx->code [target], FALSE, TRUE);
4453 static void
4454 do_load_function_ptr (VerifyContext *ctx, guint32 token, gboolean virtual)
4456 ILStackDesc *top;
4457 MonoMethod *method;
4459 if (virtual && !check_underflow (ctx, 1))
4460 return;
4462 if (!virtual && !check_overflow (ctx))
4463 return;
4465 if (!IS_METHOD_DEF_OR_REF_OR_SPEC (token) || !token_bounds_check (ctx->image, token)) {
4466 ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid token %x for ldftn at 0x%04x", token, ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE);
4467 return;
4470 if (!(method = verifier_load_method (ctx, token, virtual ? "ldvirtfrn" : "ldftn")))
4471 return;
4473 if (mono_method_is_constructor (method))
4474 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use ldftn with a constructor at 0x%04x", ctx->ip_offset));
4476 if (virtual) {
4477 ILStackDesc *top = stack_pop (ctx);
4479 if (stack_slot_get_type (top) != TYPE_COMPLEX || top->type->type == MONO_TYPE_VALUETYPE)
4480 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid argument to ldvirtftn at 0x%04x", ctx->ip_offset));
4482 if (method->flags & METHOD_ATTRIBUTE_STATIC)
4483 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use ldvirtftn with a constructor at 0x%04x", ctx->ip_offset));
4485 if (!verify_stack_type_compatibility (ctx, &method->klass->byval_arg, top))
4486 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Unexpected object for ldvirtftn at 0x%04x", ctx->ip_offset));
4489 if (!mono_method_can_access_method_full (ctx->method, method, NULL))
4490 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);
4492 top = stack_push_val(ctx, TYPE_PTR, mono_type_create_fnptr_from_mono_method (ctx, method));
4493 top->method = method;
4496 static void
4497 do_sizeof (VerifyContext *ctx, int token)
4499 MonoType *type;
4501 if (!IS_TYPE_DEF_OR_REF_OR_SPEC (token) || !token_bounds_check (ctx->image, token)) {
4502 ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid type token %x at 0x%04x", token, ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE);
4503 return;
4506 if (!(type = verifier_load_type (ctx, token, "sizeof")))
4507 return;
4509 if (type->byref && type->type != MONO_TYPE_TYPEDBYREF) {
4510 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid use of byref type at 0x%04x", ctx->ip_offset));
4511 return;
4514 if (type->type == MONO_TYPE_VOID) {
4515 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid use of void type at 0x%04x", ctx->ip_offset));
4516 return;
4519 if (check_overflow (ctx))
4520 set_stack_value (ctx, stack_push (ctx), &mono_defaults.uint32_class->byval_arg, FALSE);
4523 /* Stack top can be of any type, the runtime doesn't care and treat everything as an int. */
4524 static void
4525 do_localloc (VerifyContext *ctx)
4527 ILStackDesc *top;
4529 if (ctx->eval.size != 1) {
4530 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Stack must have only size item in localloc at 0x%04x", ctx->ip_offset));
4531 return;
4534 if (in_any_exception_block (ctx->header, ctx->ip_offset)) {
4535 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Stack must have only size item in localloc at 0x%04x", ctx->ip_offset));
4536 return;
4539 /*TODO verify top type*/
4540 top = stack_pop (ctx);
4542 set_stack_value (ctx, stack_push (ctx), &mono_defaults.int_class->byval_arg, FALSE);
4543 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Instruction localloc in never verifiable at 0x%04x", ctx->ip_offset));
4546 static void
4547 do_ldstr (VerifyContext *ctx, guint32 token)
4549 if (mono_metadata_token_code (token) != MONO_TOKEN_STRING) {
4550 ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid string token %x at 0x%04x", token, ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE);
4551 return;
4554 if (!ctx->image->dynamic && mono_metadata_token_index (token) >= ctx->image->heap_us.size) {
4555 ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid string index %x at 0x%04x", token, ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE);
4556 return;
4559 if (check_overflow (ctx))
4560 stack_push_val (ctx, TYPE_COMPLEX, &mono_defaults.string_class->byval_arg);
4563 static void
4564 do_refanyval (VerifyContext *ctx, int token)
4566 ILStackDesc *top;
4567 MonoType *type;
4568 if (!check_underflow (ctx, 1))
4569 return;
4571 if (!(type = get_boxable_mono_type (ctx, token, "refanyval")))
4572 return;
4574 top = stack_pop (ctx);
4576 if (top->stype != TYPE_PTR || top->type->type != MONO_TYPE_TYPEDBYREF)
4577 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));
4579 set_stack_value (ctx, stack_push (ctx), type, TRUE);
4582 static void
4583 do_refanytype (VerifyContext *ctx)
4585 ILStackDesc *top;
4587 if (!check_underflow (ctx, 1))
4588 return;
4590 top = stack_pop (ctx);
4592 if (top->stype != TYPE_PTR || top->type->type != MONO_TYPE_TYPEDBYREF)
4593 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));
4595 set_stack_value (ctx, stack_push (ctx), &mono_defaults.typehandle_class->byval_arg, FALSE);
4599 static void
4600 do_mkrefany (VerifyContext *ctx, int token)
4602 ILStackDesc *top;
4603 MonoType *type;
4604 if (!check_underflow (ctx, 1))
4605 return;
4607 if (!(type = get_boxable_mono_type (ctx, token, "refanyval")))
4608 return;
4610 top = stack_pop (ctx);
4612 if (stack_slot_is_managed_mutability_pointer (top))
4613 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use a readonly pointer with mkrefany at 0x%04x", ctx->ip_offset));
4615 if (!stack_slot_is_managed_pointer (top)) {
4616 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));
4617 }else {
4618 MonoType *stack_type = mono_type_get_type_byval (top->type);
4619 if (MONO_TYPE_IS_REFERENCE (type) && !mono_metadata_type_equal (type, stack_type))
4620 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Type not compatible for mkrefany at 0x%04x", ctx->ip_offset));
4622 if (!MONO_TYPE_IS_REFERENCE (type) && !verify_type_compatibility_full (ctx, type, stack_type, TRUE))
4623 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Type not compatible for mkrefany at 0x%04x", ctx->ip_offset));
4626 set_stack_value (ctx, stack_push (ctx), &mono_defaults.typed_reference_class->byval_arg, FALSE);
4629 static void
4630 do_ckfinite (VerifyContext *ctx)
4632 ILStackDesc *top;
4633 if (!check_underflow (ctx, 1))
4634 return;
4636 top = stack_pop (ctx);
4638 if (stack_slot_get_underlying_type (top) != TYPE_R8)
4639 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));
4640 stack_push_stack_val (ctx, top);
4643 * merge_stacks:
4644 * Merge the stacks and perform compat checks. The merge check if types of @from are mergeable with type of @to
4646 * @from holds new values for a given control path
4647 * @to holds the current values of a given control path
4649 * TODO we can eliminate the from argument as all callers pass &ctx->eval
4651 static void
4652 merge_stacks (VerifyContext *ctx, ILCodeDesc *from, ILCodeDesc *to, gboolean start, gboolean external)
4654 int i, j, k;
4655 stack_init (ctx, to);
4657 if (start) {
4658 if (to->flags == IL_CODE_FLAG_NOT_PROCESSED)
4659 from->size = 0;
4660 else
4661 stack_copy (&ctx->eval, to);
4662 goto end_verify;
4663 } else if (!(to->flags & IL_CODE_STACK_MERGED)) {
4664 stack_copy (to, &ctx->eval);
4665 goto end_verify;
4667 VERIFIER_DEBUG ( printf ("performing stack merge %d x %d\n", from->size, to->size); );
4669 if (from->size != to->size) {
4670 VERIFIER_DEBUG ( printf ("different stack sizes %d x %d at 0x%04x\n", from->size, to->size, ctx->ip_offset); );
4671 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));
4672 goto end_verify;
4675 //FIXME we need to preserve CMMP attributes
4676 //FIXME we must take null literals into consideration.
4677 for (i = 0; i < from->size; ++i) {
4678 ILStackDesc *new_slot = from->stack + i;
4679 ILStackDesc *old_slot = to->stack + i;
4680 MonoType *new_type = mono_type_from_stack_slot (new_slot);
4681 MonoType *old_type = mono_type_from_stack_slot (old_slot);
4682 MonoClass *old_class = mono_class_from_mono_type (old_type);
4683 MonoClass *new_class = mono_class_from_mono_type (new_type);
4684 MonoClass *match_class = NULL;
4686 // S := T then U = S (new value is compatible with current value, keep current)
4687 if (verify_stack_type_compatibility (ctx, old_type, new_slot)) {
4688 copy_stack_value (new_slot, old_slot);
4689 continue;
4692 // T := S then U = T (old value is compatible with current value, use new)
4693 if (verify_stack_type_compatibility (ctx, new_type, old_slot)) {
4694 copy_stack_value (old_slot, new_slot);
4695 continue;
4698 if (mono_type_is_generic_argument (old_type) || mono_type_is_generic_argument (new_type)) {
4699 char *old_name = stack_slot_full_name (old_slot);
4700 char *new_name = stack_slot_full_name (new_slot);
4701 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));
4702 g_free (old_name);
4703 g_free (new_name);
4704 goto end_verify;
4707 //both are reference types, use closest common super type
4708 if (!mono_class_from_mono_type (old_type)->valuetype
4709 && !mono_class_from_mono_type (new_type)->valuetype
4710 && !stack_slot_is_managed_pointer (old_slot)
4711 && !stack_slot_is_managed_pointer (new_slot)) {
4713 for (j = MIN (old_class->idepth, new_class->idepth) - 1; j > 0; --j) {
4714 if (mono_metadata_type_equal (&old_class->supertypes [j]->byval_arg, &new_class->supertypes [j]->byval_arg)) {
4715 match_class = old_class->supertypes [j];
4716 goto match_found;
4720 mono_class_setup_interfaces (old_class);
4721 for (j = 0; j < old_class->interface_count; ++j) {
4722 for (k = 0; k < new_class->interface_count; ++k) {
4723 if (mono_metadata_type_equal (&old_class->interfaces [j]->byval_arg, &new_class->interfaces [k]->byval_arg)) {
4724 match_class = old_class->interfaces [j];
4725 goto match_found;
4730 //No decent super type found, use object
4731 match_class = mono_defaults.object_class;
4732 goto match_found;
4733 } 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)) {
4734 match_class = mono_defaults.object_class;
4735 goto match_found;
4739 char *old_name = stack_slot_full_name (old_slot);
4740 char *new_name = stack_slot_full_name (new_slot);
4741 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));
4742 g_free (old_name);
4743 g_free (new_name);
4745 set_stack_value (ctx, old_slot, &new_class->byval_arg, stack_slot_is_managed_pointer (old_slot));
4746 goto end_verify;
4748 match_found:
4749 g_assert (match_class);
4750 set_stack_value (ctx, old_slot, &match_class->byval_arg, stack_slot_is_managed_pointer (old_slot));
4751 set_stack_value (ctx, new_slot, &match_class->byval_arg, stack_slot_is_managed_pointer (old_slot));
4752 continue;
4755 end_verify:
4756 if (external)
4757 to->flags |= IL_CODE_FLAG_WAS_TARGET;
4758 to->flags |= IL_CODE_STACK_MERGED;
4761 #define HANDLER_START(clause) ((clause)->flags == MONO_EXCEPTION_CLAUSE_FILTER ? (clause)->data.filter_offset : clause->handler_offset)
4762 #define IS_CATCH_OR_FILTER(clause) ((clause)->flags == MONO_EXCEPTION_CLAUSE_FILTER || (clause)->flags == MONO_EXCEPTION_CLAUSE_NONE)
4765 * is_clause_in_range :
4767 * Returns TRUE if either the protected block or the handler of @clause is in the @start - @end range.
4769 static gboolean
4770 is_clause_in_range (MonoExceptionClause *clause, guint32 start, guint32 end)
4772 if (clause->try_offset >= start && clause->try_offset < end)
4773 return TRUE;
4774 if (HANDLER_START (clause) >= start && HANDLER_START (clause) < end)
4775 return TRUE;
4776 return FALSE;
4780 * is_clause_inside_range :
4782 * Returns TRUE if @clause lies completely inside the @start - @end range.
4784 static gboolean
4785 is_clause_inside_range (MonoExceptionClause *clause, guint32 start, guint32 end)
4787 if (clause->try_offset < start || (clause->try_offset + clause->try_len) > end)
4788 return FALSE;
4789 if (HANDLER_START (clause) < start || (clause->handler_offset + clause->handler_len) > end)
4790 return FALSE;
4791 return TRUE;
4795 * is_clause_nested :
4797 * Returns TRUE if @nested is nested in @clause.
4799 static gboolean
4800 is_clause_nested (MonoExceptionClause *clause, MonoExceptionClause *nested)
4802 if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER && is_clause_inside_range (nested, clause->data.filter_offset, clause->handler_offset))
4803 return TRUE;
4804 return is_clause_inside_range (nested, clause->try_offset, clause->try_offset + clause->try_len) ||
4805 is_clause_inside_range (nested, clause->handler_offset, clause->handler_offset + clause->handler_len);
4808 /* Test the relationship between 2 exception clauses. Follow P.1 12.4.2.7 of ECMA
4809 * the each pair of exception must have the following properties:
4810 * - one is fully nested on another (the outer must not be a filter clause) (the nested one must come earlier)
4811 * - completely disjoin (none of the 3 regions of each entry overlap with the other 3)
4812 * - mutual protection (protected block is EXACT the same, handlers are disjoin and all handler are catch or all handler are filter)
4814 static void
4815 verify_clause_relationship (VerifyContext *ctx, MonoExceptionClause *clause, MonoExceptionClause *to_test)
4817 /*clause is nested*/
4818 if (to_test->flags == MONO_EXCEPTION_CLAUSE_FILTER && is_clause_inside_range (clause, to_test->data.filter_offset, to_test->handler_offset)) {
4819 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Exception clause inside filter"));
4820 return;
4823 /*wrong nesting order.*/
4824 if (is_clause_nested (clause, to_test)) {
4825 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Nested exception clause appears after enclosing clause"));
4826 return;
4829 /*mutual protection*/
4830 if (clause->try_offset == to_test->try_offset && clause->try_len == to_test->try_len) {
4831 /*handlers are not disjoint*/
4832 if (is_clause_in_range (to_test, HANDLER_START (clause), clause->handler_offset + clause->handler_len)) {
4833 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Exception handlers overlap"));
4834 return;
4836 /* handlers are not catch or filter */
4837 if (!IS_CATCH_OR_FILTER (clause) || !IS_CATCH_OR_FILTER (to_test)) {
4838 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Exception clauses with shared protected block are neither catch or filter"));
4839 return;
4841 /*OK*/
4842 return;
4845 /*not completelly disjoint*/
4846 if ((is_clause_in_range (to_test, clause->try_offset, clause->try_offset + clause->try_len) ||
4847 is_clause_in_range (to_test, HANDLER_START (clause), clause->handler_offset + clause->handler_len)) && !is_clause_nested (to_test, clause))
4848 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Exception clauses overlap"));
4851 #define code_bounds_check(size) \
4852 if (ip + size > end) {\
4853 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Code overrun starting with 0x%x at 0x%04x", *ip, ctx.ip_offset)); \
4854 break; \
4858 * FIXME: need to distinguish between valid and verifiable.
4859 * Need to keep track of types on the stack.
4860 * Verify types for opcodes.
4862 GSList*
4863 mono_method_verify (MonoMethod *method, int level)
4865 MonoError error;
4866 const unsigned char *ip;
4867 const unsigned char *end;
4868 int i, n, need_merge = 0, start = 0;
4869 guint token, ip_offset = 0, prefix = 0;
4870 MonoGenericContext *generic_context = NULL;
4871 MonoImage *image;
4872 VerifyContext ctx;
4873 GSList *tmp;
4874 VERIFIER_DEBUG ( printf ("Verify IL for method %s %s %s\n", method->klass->name_space, method->klass->name, method->name); );
4876 if (method->iflags & (METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL | METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
4877 (method->flags & (METHOD_ATTRIBUTE_PINVOKE_IMPL | METHOD_ATTRIBUTE_ABSTRACT))) {
4878 return NULL;
4881 memset (&ctx, 0, sizeof (VerifyContext));
4883 //FIXME use mono_method_get_signature_full
4884 ctx.signature = mono_method_signature (method);
4885 if (!ctx.signature) {
4886 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Could not decode method signature"));
4887 return ctx.list;
4889 ctx.header = mono_method_get_header (method);
4890 if (!ctx.header) {
4891 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Could not decode method header"));
4892 return ctx.list;
4894 ctx.method = method;
4895 ip = ctx.header->code;
4896 end = ip + ctx.header->code_size;
4897 ctx.image = image = method->klass->image;
4900 ctx.max_args = ctx.signature->param_count + ctx.signature->hasthis;
4901 ctx.max_stack = ctx.header->max_stack;
4902 ctx.verifiable = ctx.valid = 1;
4903 ctx.level = level;
4905 ctx.code = g_new (ILCodeDesc, ctx.header->code_size);
4906 ctx.code_size = ctx.header->code_size;
4908 memset(ctx.code, 0, sizeof (ILCodeDesc) * ctx.header->code_size);
4911 ctx.num_locals = ctx.header->num_locals;
4912 ctx.locals = g_memdup (ctx.header->locals, sizeof (MonoType*) * ctx.header->num_locals);
4914 if (ctx.num_locals > 0 && !ctx.header->init_locals)
4915 CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Method with locals variable but without init locals set"));
4917 ctx.params = g_new (MonoType*, ctx.max_args);
4918 if (ctx.signature->hasthis)
4919 ctx.params [0] = method->klass->valuetype ? &method->klass->this_arg : &method->klass->byval_arg;
4920 memcpy (ctx.params + ctx.signature->hasthis, ctx.signature->params, sizeof (MonoType *) * ctx.signature->param_count);
4922 if (ctx.signature->is_inflated)
4923 ctx.generic_context = generic_context = mono_method_get_context (method);
4925 if (!generic_context && (method->klass->generic_container || method->is_generic)) {
4926 if (method->is_generic)
4927 ctx.generic_context = generic_context = &(mono_method_get_generic_container (method)->context);
4928 else
4929 ctx.generic_context = generic_context = &method->klass->generic_container->context;
4932 for (i = 0; i < ctx.num_locals; ++i) {
4933 ctx.locals [i] = mono_class_inflate_generic_type_checked (ctx.locals [i], ctx.generic_context, &error);
4934 if (!mono_error_ok (&error)) {
4935 char *name = mono_type_full_name (ctx.locals [i]);
4936 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid local %d of type %s", i, name));
4937 g_free (name);
4938 mono_error_cleanup (&error);
4939 goto cleanup;
4942 for (i = 0; i < ctx.max_args; ++i) {
4943 ctx.params [i] = mono_class_inflate_generic_type_checked (ctx.params [i], ctx.generic_context, &error);
4944 if (!mono_error_ok (&error)) {
4945 char *name = mono_type_full_name (ctx.locals [i]);
4946 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid parameter %d of type %s", i, name));
4947 g_free (name);
4948 mono_error_cleanup (&error);
4949 goto cleanup;
4952 stack_init (&ctx, &ctx.eval);
4954 for (i = 0; i < ctx.num_locals; ++i) {
4955 if (!mono_type_is_valid_in_context (&ctx, ctx.locals [i]))
4956 break;
4959 for (i = 0; i < ctx.max_args; ++i) {
4960 if (!mono_type_is_valid_in_context (&ctx, ctx.params [i]))
4961 break;
4964 if (!ctx.valid)
4965 goto cleanup;
4967 for (i = 0; i < ctx.header->num_clauses && ctx.valid; ++i) {
4968 MonoExceptionClause *clause = ctx.header->clauses + i;
4969 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); );
4971 if (clause->try_offset > ctx.code_size || clause->try_offset + clause->try_len > ctx.code_size)
4972 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("try clause out of bounds at 0x%04x", clause->try_offset));
4974 if (clause->try_len <= 0)
4975 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("try clause len <= 0 at 0x%04x", clause->try_offset));
4977 if (clause->handler_offset > ctx.code_size || clause->handler_offset + clause->handler_len > ctx.code_size)
4978 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("handler clause out of bounds at 0x%04x", clause->try_offset));
4980 if (clause->handler_len <= 0)
4981 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("try clause len <= 0 at 0x%04x", clause->try_offset));
4983 if (clause->try_offset < clause->handler_offset && clause->try_offset + clause->try_len > HANDLER_START (clause))
4984 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("try block (at 0x%04x) includes handler block (at 0x%04x)", clause->try_offset, clause->handler_offset));
4986 for (n = i + 1; n < ctx.header->num_clauses && ctx.valid; ++n)
4987 verify_clause_relationship (&ctx, clause, ctx.header->clauses + n);
4989 if (!ctx.valid)
4990 break;
4992 ctx.code [clause->try_offset].flags |= IL_CODE_FLAG_WAS_TARGET;
4993 if (clause->try_offset + clause->try_len < ctx.code_size)
4994 ctx.code [clause->try_offset + clause->try_len].flags |= IL_CODE_FLAG_WAS_TARGET;
4995 if (clause->handler_offset + clause->handler_len < ctx.code_size)
4996 ctx.code [clause->handler_offset + clause->handler_len].flags |= IL_CODE_FLAG_WAS_TARGET;
4998 if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE) {
4999 init_stack_with_value_at_exception_boundary (&ctx, ctx.code + clause->handler_offset, clause->data.catch_class);
5001 else if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
5002 init_stack_with_value_at_exception_boundary (&ctx, ctx.code + clause->data.filter_offset, mono_defaults.exception_class);
5003 init_stack_with_value_at_exception_boundary (&ctx, ctx.code + clause->handler_offset, mono_defaults.exception_class);
5007 while (ip < end && ctx.valid) {
5008 ctx.ip_offset = ip_offset = ip - ctx.header->code;
5010 /*We need to check against fallthrou in and out of protected blocks.
5011 * For fallout we check the once a protected block ends, if the start flag is not set.
5012 * Likewise for fallthru in, we check if ip is the start of a protected block and start is not set
5013 * TODO convert these checks to be done using flags and not this loop
5015 for (i = 0; i < ctx.header->num_clauses && ctx.valid; ++i) {
5016 MonoExceptionClause *clause = ctx.header->clauses + i;
5018 if ((clause->try_offset + clause->try_len == ip_offset) && start == 0) {
5019 CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("fallthru off try block at 0x%04x", ip_offset));
5020 start = 1;
5023 if ((clause->handler_offset + clause->handler_len == ip_offset) && start == 0) {
5024 if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER)
5025 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("fallout of handler block at 0x%04x", ip_offset));
5026 else
5027 CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("fallout of handler block at 0x%04x", ip_offset));
5028 start = 1;
5031 if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER && clause->handler_offset == ip_offset && start == 0) {
5032 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("fallout of filter block at 0x%04x", ip_offset));
5033 start = 1;
5036 if (clause->handler_offset == ip_offset && start == 0) {
5037 CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("fallthru handler block at 0x%04x", ip_offset));
5038 start = 1;
5041 if (clause->try_offset == ip_offset && ctx.eval.size > 0 && start == 0) {
5042 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Try to enter try block with a non-empty stack at 0x%04x", ip_offset));
5043 start = 1;
5047 if (!ctx.valid)
5048 break;
5050 if (need_merge) {
5051 VERIFIER_DEBUG ( printf ("extra merge needed! 0x%04x \n", ctx.target); );
5052 merge_stacks (&ctx, &ctx.eval, &ctx.code [ctx.target], FALSE, TRUE);
5053 need_merge = 0;
5055 merge_stacks (&ctx, &ctx.eval, &ctx.code[ip_offset], start, FALSE);
5056 start = 0;
5058 /*TODO we can fast detect a forward branch or exception block targeting code after prefix, we should fail fast*/
5059 #ifdef MONO_VERIFIER_DEBUG
5061 char *discode;
5062 discode = mono_disasm_code_one (NULL, method, ip, NULL);
5063 discode [strlen (discode) - 1] = 0; /* no \n */
5064 g_print ("[%d] %-29s (%d)\n", ip_offset, discode, ctx.eval.size);
5065 g_free (discode);
5067 dump_stack_state (&ctx.code [ip_offset]);
5068 dump_stack_state (&ctx.eval);
5069 #endif
5071 switch (*ip) {
5072 case CEE_NOP:
5073 case CEE_BREAK:
5074 ++ip;
5075 break;
5077 case CEE_LDARG_0:
5078 case CEE_LDARG_1:
5079 case CEE_LDARG_2:
5080 case CEE_LDARG_3:
5081 push_arg (&ctx, *ip - CEE_LDARG_0, FALSE);
5082 ++ip;
5083 break;
5085 case CEE_LDARG_S:
5086 case CEE_LDARGA_S:
5087 code_bounds_check (2);
5088 push_arg (&ctx, ip [1], *ip == CEE_LDARGA_S);
5089 ip += 2;
5090 break;
5092 case CEE_ADD_OVF_UN:
5093 do_binop (&ctx, *ip, add_ovf_un_table);
5094 ++ip;
5095 break;
5097 case CEE_SUB_OVF_UN:
5098 do_binop (&ctx, *ip, sub_ovf_un_table);
5099 ++ip;
5100 break;
5102 case CEE_ADD_OVF:
5103 case CEE_SUB_OVF:
5104 case CEE_MUL_OVF:
5105 case CEE_MUL_OVF_UN:
5106 do_binop (&ctx, *ip, bin_ovf_table);
5107 ++ip;
5108 break;
5110 case CEE_ADD:
5111 do_binop (&ctx, *ip, add_table);
5112 ++ip;
5113 break;
5115 case CEE_SUB:
5116 do_binop (&ctx, *ip, sub_table);
5117 ++ip;
5118 break;
5120 case CEE_MUL:
5121 case CEE_DIV:
5122 case CEE_REM:
5123 do_binop (&ctx, *ip, bin_op_table);
5124 ++ip;
5125 break;
5127 case CEE_AND:
5128 case CEE_DIV_UN:
5129 case CEE_OR:
5130 case CEE_REM_UN:
5131 case CEE_XOR:
5132 do_binop (&ctx, *ip, int_bin_op_table);
5133 ++ip;
5134 break;
5136 case CEE_SHL:
5137 case CEE_SHR:
5138 case CEE_SHR_UN:
5139 do_binop (&ctx, *ip, shift_op_table);
5140 ++ip;
5141 break;
5143 case CEE_POP:
5144 if (!check_underflow (&ctx, 1))
5145 break;
5146 stack_pop_safe (&ctx);
5147 ++ip;
5148 break;
5150 case CEE_RET:
5151 do_ret (&ctx);
5152 ++ip;
5153 start = 1;
5154 break;
5156 case CEE_LDLOC_0:
5157 case CEE_LDLOC_1:
5158 case CEE_LDLOC_2:
5159 case CEE_LDLOC_3:
5160 /*TODO support definite assignment verification? */
5161 push_local (&ctx, *ip - CEE_LDLOC_0, FALSE);
5162 ++ip;
5163 break;
5165 case CEE_STLOC_0:
5166 case CEE_STLOC_1:
5167 case CEE_STLOC_2:
5168 case CEE_STLOC_3:
5169 store_local (&ctx, *ip - CEE_STLOC_0);
5170 ++ip;
5171 break;
5173 case CEE_STLOC_S:
5174 code_bounds_check (2);
5175 store_local (&ctx, ip [1]);
5176 ip += 2;
5177 break;
5179 case CEE_STARG_S:
5180 code_bounds_check (2);
5181 store_arg (&ctx, ip [1]);
5182 ip += 2;
5183 break;
5185 case CEE_LDC_I4_M1:
5186 case CEE_LDC_I4_0:
5187 case CEE_LDC_I4_1:
5188 case CEE_LDC_I4_2:
5189 case CEE_LDC_I4_3:
5190 case CEE_LDC_I4_4:
5191 case CEE_LDC_I4_5:
5192 case CEE_LDC_I4_6:
5193 case CEE_LDC_I4_7:
5194 case CEE_LDC_I4_8:
5195 if (check_overflow (&ctx))
5196 stack_push_val (&ctx, TYPE_I4, &mono_defaults.int32_class->byval_arg);
5197 ++ip;
5198 break;
5200 case CEE_LDC_I4_S:
5201 code_bounds_check (2);
5202 if (check_overflow (&ctx))
5203 stack_push_val (&ctx, TYPE_I4, &mono_defaults.int32_class->byval_arg);
5204 ip += 2;
5205 break;
5207 case CEE_LDC_I4:
5208 code_bounds_check (5);
5209 if (check_overflow (&ctx))
5210 stack_push_val (&ctx,TYPE_I4, &mono_defaults.int32_class->byval_arg);
5211 ip += 5;
5212 break;
5214 case CEE_LDC_I8:
5215 code_bounds_check (9);
5216 if (check_overflow (&ctx))
5217 stack_push_val (&ctx,TYPE_I8, &mono_defaults.int64_class->byval_arg);
5218 ip += 9;
5219 break;
5221 case CEE_LDC_R4:
5222 code_bounds_check (5);
5223 if (check_overflow (&ctx))
5224 stack_push_val (&ctx, TYPE_R8, &mono_defaults.double_class->byval_arg);
5225 ip += 5;
5226 break;
5228 case CEE_LDC_R8:
5229 code_bounds_check (9);
5230 if (check_overflow (&ctx))
5231 stack_push_val (&ctx, TYPE_R8, &mono_defaults.double_class->byval_arg);
5232 ip += 9;
5233 break;
5235 case CEE_LDNULL:
5236 if (check_overflow (&ctx))
5237 stack_push_val (&ctx, TYPE_COMPLEX | NULL_LITERAL_MASK, &mono_defaults.object_class->byval_arg);
5238 ++ip;
5239 break;
5241 case CEE_BEQ_S:
5242 case CEE_BNE_UN_S:
5243 code_bounds_check (2);
5244 do_branch_op (&ctx, (signed char)ip [1] + 2, cmp_br_eq_op);
5245 ip += 2;
5246 need_merge = 1;
5247 break;
5249 case CEE_BGE_S:
5250 case CEE_BGT_S:
5251 case CEE_BLE_S:
5252 case CEE_BLT_S:
5253 case CEE_BGE_UN_S:
5254 case CEE_BGT_UN_S:
5255 case CEE_BLE_UN_S:
5256 case CEE_BLT_UN_S:
5257 code_bounds_check (2);
5258 do_branch_op (&ctx, (signed char)ip [1] + 2, cmp_br_op);
5259 ip += 2;
5260 need_merge = 1;
5261 break;
5263 case CEE_BEQ:
5264 case CEE_BNE_UN:
5265 code_bounds_check (5);
5266 do_branch_op (&ctx, (gint32)read32 (ip + 1) + 5, cmp_br_eq_op);
5267 ip += 5;
5268 need_merge = 1;
5269 break;
5271 case CEE_BGE:
5272 case CEE_BGT:
5273 case CEE_BLE:
5274 case CEE_BLT:
5275 case CEE_BGE_UN:
5276 case CEE_BGT_UN:
5277 case CEE_BLE_UN:
5278 case CEE_BLT_UN:
5279 code_bounds_check (5);
5280 do_branch_op (&ctx, (gint32)read32 (ip + 1) + 5, cmp_br_op);
5281 ip += 5;
5282 need_merge = 1;
5283 break;
5285 case CEE_LDLOC_S:
5286 case CEE_LDLOCA_S:
5287 code_bounds_check (2);
5288 push_local (&ctx, ip[1], *ip == CEE_LDLOCA_S);
5289 ip += 2;
5290 break;
5292 /* FIXME: warn/error instead? */
5293 case CEE_UNUSED99:
5294 ++ip;
5295 break;
5297 case CEE_DUP: {
5298 ILStackDesc * top;
5299 if (!check_underflow (&ctx, 1))
5300 break;
5301 if (!check_overflow (&ctx))
5302 break;
5303 top = stack_pop_safe (&ctx);
5304 copy_stack_value (stack_push (&ctx), top);
5305 copy_stack_value (stack_push (&ctx), top);
5306 ++ip;
5307 break;
5310 case CEE_JMP:
5311 code_bounds_check (5);
5312 if (ctx.eval.size)
5313 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Eval stack must be empty in jmp at 0x%04x", ip_offset));
5314 token = read32 (ip + 1);
5315 if (in_any_block (ctx.header, ip_offset))
5316 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("jmp cannot escape exception blocks at 0x%04x", ip_offset));
5318 CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Intruction jmp is not verifiable at 0x%04x", ctx.ip_offset));
5320 * FIXME: check signature, retval, arguments etc.
5322 ip += 5;
5323 break;
5324 case CEE_CALL:
5325 case CEE_CALLVIRT:
5326 code_bounds_check (5);
5327 do_invoke_method (&ctx, read32 (ip + 1), *ip == CEE_CALLVIRT);
5328 ip += 5;
5329 break;
5331 case CEE_CALLI:
5332 code_bounds_check (5);
5333 token = read32 (ip + 1);
5335 * FIXME: check signature, retval, arguments etc.
5336 * FIXME: check requirements for tail call
5338 CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Intruction calli is not verifiable at 0x%04x", ctx.ip_offset));
5339 ip += 5;
5340 break;
5341 case CEE_BR_S:
5342 code_bounds_check (2);
5343 do_static_branch (&ctx, (signed char)ip [1] + 2);
5344 need_merge = 1;
5345 ip += 2;
5346 start = 1;
5347 break;
5349 case CEE_BRFALSE_S:
5350 case CEE_BRTRUE_S:
5351 code_bounds_check (2);
5352 do_boolean_branch_op (&ctx, (signed char)ip [1] + 2);
5353 ip += 2;
5354 need_merge = 1;
5355 break;
5357 case CEE_BR:
5358 code_bounds_check (5);
5359 do_static_branch (&ctx, (gint32)read32 (ip + 1) + 5);
5360 need_merge = 1;
5361 ip += 5;
5362 start = 1;
5363 break;
5365 case CEE_BRFALSE:
5366 case CEE_BRTRUE:
5367 code_bounds_check (5);
5368 do_boolean_branch_op (&ctx, (gint32)read32 (ip + 1) + 5);
5369 ip += 5;
5370 need_merge = 1;
5371 break;
5373 case CEE_SWITCH:
5374 code_bounds_check (5);
5375 n = read32 (ip + 1);
5376 code_bounds_check (5 + sizeof (guint32) * n);
5378 do_switch (&ctx, n, (ip + 5));
5379 start = 1;
5380 ip += 5 + sizeof (guint32) * n;
5381 break;
5383 case CEE_LDIND_I1:
5384 case CEE_LDIND_U1:
5385 case CEE_LDIND_I2:
5386 case CEE_LDIND_U2:
5387 case CEE_LDIND_I4:
5388 case CEE_LDIND_U4:
5389 case CEE_LDIND_I8:
5390 case CEE_LDIND_I:
5391 case CEE_LDIND_R4:
5392 case CEE_LDIND_R8:
5393 case CEE_LDIND_REF:
5394 do_load_indirect (&ctx, *ip);
5395 ++ip;
5396 break;
5398 case CEE_STIND_REF:
5399 case CEE_STIND_I1:
5400 case CEE_STIND_I2:
5401 case CEE_STIND_I4:
5402 case CEE_STIND_I8:
5403 case CEE_STIND_R4:
5404 case CEE_STIND_R8:
5405 case CEE_STIND_I:
5406 do_store_indirect (&ctx, *ip);
5407 ++ip;
5408 break;
5410 case CEE_NOT:
5411 case CEE_NEG:
5412 do_unary_math_op (&ctx, *ip);
5413 ++ip;
5414 break;
5416 case CEE_CONV_I1:
5417 case CEE_CONV_I2:
5418 case CEE_CONV_I4:
5419 case CEE_CONV_U1:
5420 case CEE_CONV_U2:
5421 case CEE_CONV_U4:
5422 do_conversion (&ctx, TYPE_I4);
5423 ++ip;
5424 break;
5426 case CEE_CONV_I8:
5427 case CEE_CONV_U8:
5428 do_conversion (&ctx, TYPE_I8);
5429 ++ip;
5430 break;
5432 case CEE_CONV_R4:
5433 case CEE_CONV_R8:
5434 case CEE_CONV_R_UN:
5435 do_conversion (&ctx, TYPE_R8);
5436 ++ip;
5437 break;
5439 case CEE_CONV_I:
5440 case CEE_CONV_U:
5441 do_conversion (&ctx, TYPE_NATIVE_INT);
5442 ++ip;
5443 break;
5445 case CEE_CPOBJ:
5446 code_bounds_check (5);
5447 do_cpobj (&ctx, read32 (ip + 1));
5448 ip += 5;
5449 break;
5451 case CEE_LDOBJ:
5452 code_bounds_check (5);
5453 do_ldobj_value (&ctx, read32 (ip + 1));
5454 ip += 5;
5455 break;
5457 case CEE_LDSTR:
5458 code_bounds_check (5);
5459 do_ldstr (&ctx, read32 (ip + 1));
5460 ip += 5;
5461 break;
5463 case CEE_NEWOBJ:
5464 code_bounds_check (5);
5465 do_newobj (&ctx, read32 (ip + 1));
5466 ip += 5;
5467 break;
5469 case CEE_CASTCLASS:
5470 case CEE_ISINST:
5471 code_bounds_check (5);
5472 do_cast (&ctx, read32 (ip + 1), *ip == CEE_CASTCLASS ? "castclass" : "isinst");
5473 ip += 5;
5474 break;
5476 case CEE_UNUSED58:
5477 case CEE_UNUSED1:
5478 ++ip; /* warn, error ? */
5479 break;
5481 case CEE_UNBOX:
5482 code_bounds_check (5);
5483 do_unbox_value (&ctx, read32 (ip + 1));
5484 ip += 5;
5485 break;
5487 case CEE_THROW:
5488 do_throw (&ctx);
5489 start = 1;
5490 ++ip;
5491 break;
5493 case CEE_LDFLD:
5494 case CEE_LDFLDA:
5495 code_bounds_check (5);
5496 do_push_field (&ctx, read32 (ip + 1), *ip == CEE_LDFLDA);
5497 ip += 5;
5498 break;
5500 case CEE_LDSFLD:
5501 case CEE_LDSFLDA:
5502 code_bounds_check (5);
5503 do_push_static_field (&ctx, read32 (ip + 1), *ip == CEE_LDSFLDA);
5504 ip += 5;
5505 break;
5507 case CEE_STFLD:
5508 code_bounds_check (5);
5509 do_store_field (&ctx, read32 (ip + 1));
5510 ip += 5;
5511 break;
5513 case CEE_STSFLD:
5514 code_bounds_check (5);
5515 do_store_static_field (&ctx, read32 (ip + 1));
5516 ip += 5;
5517 break;
5519 case CEE_STOBJ:
5520 code_bounds_check (5);
5521 do_stobj (&ctx, read32 (ip + 1));
5522 ip += 5;
5523 break;
5525 case CEE_CONV_OVF_I1_UN:
5526 case CEE_CONV_OVF_I2_UN:
5527 case CEE_CONV_OVF_I4_UN:
5528 case CEE_CONV_OVF_U1_UN:
5529 case CEE_CONV_OVF_U2_UN:
5530 case CEE_CONV_OVF_U4_UN:
5531 do_conversion (&ctx, TYPE_I4);
5532 ++ip;
5533 break;
5535 case CEE_CONV_OVF_I8_UN:
5536 case CEE_CONV_OVF_U8_UN:
5537 do_conversion (&ctx, TYPE_I8);
5538 ++ip;
5539 break;
5541 case CEE_CONV_OVF_I_UN:
5542 case CEE_CONV_OVF_U_UN:
5543 do_conversion (&ctx, TYPE_NATIVE_INT);
5544 ++ip;
5545 break;
5547 case CEE_BOX:
5548 code_bounds_check (5);
5549 do_box_value (&ctx, read32 (ip + 1));
5550 ip += 5;
5551 break;
5553 case CEE_NEWARR:
5554 code_bounds_check (5);
5555 do_newarr (&ctx, read32 (ip + 1));
5556 ip += 5;
5557 break;
5559 case CEE_LDLEN:
5560 do_ldlen (&ctx);
5561 ++ip;
5562 break;
5564 case CEE_LDELEMA:
5565 code_bounds_check (5);
5566 do_ldelema (&ctx, read32 (ip + 1));
5567 ip += 5;
5568 break;
5570 case CEE_LDELEM_I1:
5571 case CEE_LDELEM_U1:
5572 case CEE_LDELEM_I2:
5573 case CEE_LDELEM_U2:
5574 case CEE_LDELEM_I4:
5575 case CEE_LDELEM_U4:
5576 case CEE_LDELEM_I8:
5577 case CEE_LDELEM_I:
5578 case CEE_LDELEM_R4:
5579 case CEE_LDELEM_R8:
5580 case CEE_LDELEM_REF:
5581 do_ldelem (&ctx, *ip, 0);
5582 ++ip;
5583 break;
5585 case CEE_STELEM_I:
5586 case CEE_STELEM_I1:
5587 case CEE_STELEM_I2:
5588 case CEE_STELEM_I4:
5589 case CEE_STELEM_I8:
5590 case CEE_STELEM_R4:
5591 case CEE_STELEM_R8:
5592 case CEE_STELEM_REF:
5593 do_stelem (&ctx, *ip, 0);
5594 ++ip;
5595 break;
5597 case CEE_LDELEM:
5598 code_bounds_check (5);
5599 do_ldelem (&ctx, *ip, read32 (ip + 1));
5600 ip += 5;
5601 break;
5603 case CEE_STELEM:
5604 code_bounds_check (5);
5605 do_stelem (&ctx, *ip, read32 (ip + 1));
5606 ip += 5;
5607 break;
5609 case CEE_UNBOX_ANY:
5610 code_bounds_check (5);
5611 do_unbox_any (&ctx, read32 (ip + 1));
5612 ip += 5;
5613 break;
5615 case CEE_CONV_OVF_I1:
5616 case CEE_CONV_OVF_U1:
5617 case CEE_CONV_OVF_I2:
5618 case CEE_CONV_OVF_U2:
5619 case CEE_CONV_OVF_I4:
5620 case CEE_CONV_OVF_U4:
5621 do_conversion (&ctx, TYPE_I4);
5622 ++ip;
5623 break;
5625 case CEE_CONV_OVF_I8:
5626 case CEE_CONV_OVF_U8:
5627 do_conversion (&ctx, TYPE_I8);
5628 ++ip;
5629 break;
5631 case CEE_CONV_OVF_I:
5632 case CEE_CONV_OVF_U:
5633 do_conversion (&ctx, TYPE_NATIVE_INT);
5634 ++ip;
5635 break;
5637 case CEE_REFANYVAL:
5638 code_bounds_check (5);
5639 do_refanyval (&ctx, read32 (ip + 1));
5640 ip += 5;
5641 break;
5643 case CEE_CKFINITE:
5644 do_ckfinite (&ctx);
5645 ++ip;
5646 break;
5648 case CEE_MKREFANY:
5649 code_bounds_check (5);
5650 do_mkrefany (&ctx, read32 (ip + 1));
5651 ip += 5;
5652 break;
5654 case CEE_LDTOKEN:
5655 code_bounds_check (5);
5656 do_load_token (&ctx, read32 (ip + 1));
5657 ip += 5;
5658 break;
5660 case CEE_ENDFINALLY:
5661 if (!is_correct_endfinally (ctx.header, ip_offset))
5662 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("endfinally must be used inside a finally/fault handler at 0x%04x", ctx.ip_offset));
5663 ctx.eval.size = 0;
5664 start = 1;
5665 ++ip;
5666 break;
5668 case CEE_LEAVE:
5669 code_bounds_check (5);
5670 do_leave (&ctx, read32 (ip + 1) + 5);
5671 ip += 5;
5672 start = 1;
5673 break;
5675 case CEE_LEAVE_S:
5676 code_bounds_check (2);
5677 do_leave (&ctx, (signed char)ip [1] + 2);
5678 ip += 2;
5679 start = 1;
5680 break;
5682 case CEE_PREFIX1:
5683 code_bounds_check (2);
5684 ++ip;
5685 switch (*ip) {
5686 case CEE_STLOC:
5687 code_bounds_check (3);
5688 store_local (&ctx, read16 (ip + 1));
5689 ip += 3;
5690 break;
5692 case CEE_CEQ:
5693 do_cmp_op (&ctx, cmp_br_eq_op, *ip);
5694 ++ip;
5695 break;
5697 case CEE_CGT:
5698 case CEE_CGT_UN:
5699 case CEE_CLT:
5700 case CEE_CLT_UN:
5701 do_cmp_op (&ctx, cmp_br_op, *ip);
5702 ++ip;
5703 break;
5705 case CEE_STARG:
5706 code_bounds_check (3);
5707 store_arg (&ctx, read16 (ip + 1) );
5708 ip += 3;
5709 break;
5712 case CEE_ARGLIST:
5713 check_overflow (&ctx);
5714 if (ctx.signature->call_convention != MONO_CALL_VARARG)
5715 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Cannot use arglist on method without VARGARG calling convention at 0x%04x", ctx.ip_offset));
5716 set_stack_value (&ctx, stack_push (&ctx), &mono_defaults.argumenthandle_class->byval_arg, FALSE);
5717 ++ip;
5718 break;
5720 case CEE_LDFTN:
5721 code_bounds_check (5);
5722 do_load_function_ptr (&ctx, read32 (ip + 1), FALSE);
5723 ip += 5;
5724 break;
5726 case CEE_LDVIRTFTN:
5727 code_bounds_check (5);
5728 do_load_function_ptr (&ctx, read32 (ip + 1), TRUE);
5729 ip += 5;
5730 break;
5732 case CEE_UNUSED56:
5733 ++ip;
5734 break;
5736 case CEE_LDARG:
5737 case CEE_LDARGA:
5738 code_bounds_check (3);
5739 push_arg (&ctx, read16 (ip + 1), *ip == CEE_LDARGA);
5740 ip += 3;
5741 break;
5743 case CEE_LDLOC:
5744 case CEE_LDLOCA:
5745 code_bounds_check (3);
5746 push_local (&ctx, read16 (ip + 1), *ip == CEE_LDLOCA);
5747 ip += 3;
5748 break;
5750 case CEE_LOCALLOC:
5751 do_localloc (&ctx);
5752 ++ip;
5753 break;
5755 case CEE_UNUSED57:
5756 ++ip;
5757 break;
5758 case CEE_ENDFILTER:
5759 do_endfilter (&ctx);
5760 start = 1;
5761 ++ip;
5762 break;
5763 case CEE_UNALIGNED_:
5764 code_bounds_check (2);
5765 prefix |= PREFIX_UNALIGNED;
5766 ip += 2;
5767 break;
5768 case CEE_VOLATILE_:
5769 prefix |= PREFIX_VOLATILE;
5770 ++ip;
5771 break;
5772 case CEE_TAIL_:
5773 prefix |= PREFIX_TAIL;
5774 ++ip;
5775 if (ip < end && (*ip != CEE_CALL && *ip != CEE_CALLI && *ip != CEE_CALLVIRT))
5776 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("tail prefix must be used only with call opcodes at 0x%04x", ip_offset));
5777 break;
5779 case CEE_INITOBJ:
5780 code_bounds_check (5);
5781 do_initobj (&ctx, read32 (ip + 1));
5782 ip += 5;
5783 break;
5785 case CEE_CONSTRAINED_:
5786 code_bounds_check (5);
5787 ctx.constrained_type = get_boxable_mono_type (&ctx, read32 (ip + 1), "constrained.");
5788 prefix |= PREFIX_CONSTRAINED;
5789 ip += 5;
5790 break;
5792 case CEE_READONLY_:
5793 prefix |= PREFIX_READONLY;
5794 ip++;
5795 break;
5797 case CEE_CPBLK:
5798 CLEAR_PREFIX (&ctx, PREFIX_UNALIGNED | PREFIX_VOLATILE);
5799 if (!check_underflow (&ctx, 3))
5800 break;
5801 CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Instruction cpblk is not verifiable at 0x%04x", ctx.ip_offset));
5802 ip++;
5803 break;
5805 case CEE_INITBLK:
5806 CLEAR_PREFIX (&ctx, PREFIX_UNALIGNED | PREFIX_VOLATILE);
5807 if (!check_underflow (&ctx, 3))
5808 break;
5809 CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Instruction initblk is not verifiable at 0x%04x", ctx.ip_offset));
5810 ip++;
5811 break;
5813 case CEE_NO_:
5814 ip += 2;
5815 break;
5816 case CEE_RETHROW:
5817 if (!is_correct_rethrow (ctx.header, ip_offset))
5818 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("rethrow must be used inside a catch handler at 0x%04x", ctx.ip_offset));
5819 ctx.eval.size = 0;
5820 start = 1;
5821 ++ip;
5822 break;
5823 case CEE_UNUSED:
5824 ++ip;
5825 break;
5827 case CEE_SIZEOF:
5828 code_bounds_check (5);
5829 do_sizeof (&ctx, read32 (ip + 1));
5830 ip += 5;
5831 break;
5833 case CEE_REFANYTYPE:
5834 do_refanytype (&ctx);
5835 ++ip;
5836 break;
5838 default:
5839 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid instruction FE %x at 0x%04x", *ip, ctx.ip_offset));
5840 ++ip;
5842 break;
5844 default:
5845 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid instruction %x at 0x%04x", *ip, ctx.ip_offset));
5846 ++ip;
5849 /*TODO we can fast detect a forward branch or exception block targeting code after prefix, we should fail fast*/
5850 if (prefix) {
5851 if (!ctx.prefix_set) //first prefix
5852 ctx.code [ctx.ip_offset].flags |= IL_CODE_FLAG_SEEN;
5853 ctx.prefix_set |= prefix;
5854 ctx.has_flags = TRUE;
5855 prefix = 0;
5856 } else {
5857 if (!ctx.has_flags)
5858 ctx.code [ctx.ip_offset].flags |= IL_CODE_FLAG_SEEN;
5860 if (ctx.prefix_set & PREFIX_CONSTRAINED)
5861 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid instruction after constrained prefix at 0x%04x", ctx.ip_offset));
5862 if (ctx.prefix_set & PREFIX_READONLY)
5863 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid instruction after readonly prefix at 0x%04x", ctx.ip_offset));
5864 if (ctx.prefix_set & PREFIX_VOLATILE)
5865 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid instruction after volatile prefix at 0x%04x", ctx.ip_offset));
5866 if (ctx.prefix_set & PREFIX_UNALIGNED)
5867 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid instruction after unaligned prefix at 0x%04x", ctx.ip_offset));
5868 ctx.prefix_set = prefix = 0;
5869 ctx.has_flags = FALSE;
5873 * if ip != end we overflowed: mark as error.
5875 if ((ip != end || !start) && ctx.verifiable && !ctx.list) {
5876 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Run ahead of method code at 0x%04x", ip_offset));
5879 /*We should guard against the last decoded opcode, otherwise we might add errors that doesn't make sense.*/
5880 for (i = 0; i < ctx.code_size && i < ip_offset; ++i) {
5881 if (ctx.code [i].flags & IL_CODE_FLAG_WAS_TARGET) {
5882 if (!(ctx.code [i].flags & IL_CODE_FLAG_SEEN))
5883 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Branch or exception block target middle of intruction at 0x%04x", i));
5885 if (ctx.code [i].flags & IL_CODE_DELEGATE_SEQUENCE)
5886 CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Branch to delegate code sequence at 0x%04x", i));
5888 if ((ctx.code [i].flags & IL_CODE_LDFTN_DELEGATE_NONFINAL_VIRTUAL) && ctx.has_this_store)
5889 CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Invalid ldftn with virtual function in method with stdarg 0 at 0x%04x", i));
5891 if ((ctx.code [i].flags & IL_CODE_CALL_NONFINAL_VIRTUAL) && ctx.has_this_store)
5892 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));
5895 if (mono_method_is_constructor (ctx.method) && !ctx.super_ctor_called && !ctx.method->klass->valuetype && ctx.method->klass != mono_defaults.object_class) {
5896 char *method_name = mono_method_full_name (ctx.method, TRUE);
5897 char *type = mono_type_get_full_name (ctx.method->klass);
5898 if (ctx.method->klass->parent && ctx.method->klass->parent->exception_type != MONO_EXCEPTION_NONE)
5899 CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Constructor %s for type %s not calling base type ctor due to a TypeLoadException on base type.", method_name, type));
5900 else
5901 CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Constructor %s for type %s not calling base type ctor.", method_name, type));
5902 g_free (method_name);
5903 g_free (type);
5906 cleanup:
5907 if (ctx.code) {
5908 for (i = 0; i < ctx.header->code_size; ++i) {
5909 if (ctx.code [i].stack)
5910 g_free (ctx.code [i].stack);
5914 for (tmp = ctx.funptrs; tmp; tmp = tmp->next)
5915 g_free (tmp->data);
5916 g_slist_free (ctx.funptrs);
5918 for (tmp = ctx.exception_types; tmp; tmp = tmp->next)
5919 mono_metadata_free_type (tmp->data);
5920 g_slist_free (ctx.exception_types);
5922 for (i = 0; i < ctx.num_locals; ++i)
5923 mono_metadata_free_type (ctx.locals [i]);
5924 for (i = 0; i < ctx.max_args; ++i)
5925 mono_metadata_free_type (ctx.params [i]);
5927 if (ctx.eval.stack)
5928 g_free (ctx.eval.stack);
5929 if (ctx.code)
5930 g_free (ctx.code);
5931 g_free (ctx.locals);
5932 g_free (ctx.params);
5934 return ctx.list;
5937 char*
5938 mono_verify_corlib ()
5940 /* This is a public API function so cannot be removed */
5941 return NULL;
5945 * Returns true if @method needs to be verified.
5948 gboolean
5949 mono_verifier_is_enabled_for_method (MonoMethod *method)
5951 return mono_verifier_is_enabled_for_class (method->klass) && method->wrapper_type == MONO_WRAPPER_NONE;
5955 * Returns true if @klass need to be verified.
5958 gboolean
5959 mono_verifier_is_enabled_for_class (MonoClass *klass)
5961 return verify_all || (verifier_mode > MONO_VERIFIER_MODE_OFF && !klass->image->assembly->in_gac && klass->image != mono_defaults.corlib);
5964 gboolean
5965 mono_verifier_is_enabled_for_image (MonoImage *image)
5967 return verify_all || verifier_mode > MONO_VERIFIER_MODE_OFF;
5970 gboolean
5971 mono_verifier_is_method_full_trust (MonoMethod *method)
5973 return mono_verifier_is_class_full_trust (method->klass);
5977 * Returns if @klass is under full trust or not.
5979 * TODO This code doesn't take CAS into account.
5981 * Under verify_all all user code must be verifiable if no security option was set
5984 gboolean
5985 mono_verifier_is_class_full_trust (MonoClass *klass)
5987 /* under CoreCLR code is trusted if it is part of the "platform" otherwise all code inside the GAC is trusted */
5988 gboolean trusted_location = (mono_security_get_mode () != MONO_SECURITY_MODE_CORE_CLR) ?
5989 klass->image->assembly->in_gac : mono_security_core_clr_is_platform_image (klass->image);
5991 if (verify_all && verifier_mode == MONO_VERIFIER_MODE_OFF)
5992 return trusted_location || klass->image == mono_defaults.corlib;
5993 return verifier_mode < MONO_VERIFIER_MODE_VERIFIABLE || trusted_location || klass->image == mono_defaults.corlib;
5996 GSList*
5997 mono_method_verify_with_current_settings (MonoMethod *method, gboolean skip_visibility)
5999 return mono_method_verify (method,
6000 (verifier_mode != MONO_VERIFIER_MODE_STRICT ? MONO_VERIFY_NON_STRICT: 0)
6001 | (!mono_verifier_is_method_full_trust (method) ? MONO_VERIFY_FAIL_FAST : 0)
6002 | (skip_visibility ? MONO_VERIFY_SKIP_VISIBILITY : 0));
6005 static int
6006 get_field_end (MonoClassField *field)
6008 int align;
6009 int size = mono_type_size (field->type, &align);
6010 if (size == 0)
6011 size = 4; /*FIXME Is this a safe bet?*/
6012 return size + field->offset;
6015 static gboolean
6016 verify_class_for_overlapping_reference_fields (MonoClass *class)
6018 int i, j;
6019 gboolean is_fulltrust = mono_verifier_is_class_full_trust (class);
6020 if (!((class->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_EXPLICIT_LAYOUT) || !class->has_references)
6021 return TRUE;
6023 //we must check for stuff overlapping reference fields
6024 for (i = 0; i < class->field.count; ++i) {
6025 MonoClassField *field = &class->fields [i];
6026 int fieldEnd = get_field_end (field);
6027 gboolean is_valuetype = !MONO_TYPE_IS_REFERENCE (field->type);
6028 if (mono_field_is_deleted (field) || (field->type->attrs & FIELD_ATTRIBUTE_STATIC))
6029 continue;
6031 for (j = i + 1; j < class->field.count; ++j) {
6032 MonoClassField *other = &class->fields [j];
6033 int otherEnd = get_field_end (other);
6034 if (mono_field_is_deleted (other) || (is_valuetype && !MONO_TYPE_IS_REFERENCE (other->type)) || (other->type->attrs & FIELD_ATTRIBUTE_STATIC))
6035 continue;
6037 if (!is_valuetype && MONO_TYPE_IS_REFERENCE (other->type) && field->offset == other->offset && is_fulltrust)
6038 continue;
6040 if ((otherEnd > field->offset && otherEnd <= fieldEnd) || (other->offset >= field->offset && other->offset < fieldEnd))
6041 return FALSE;
6044 return TRUE;
6047 static guint
6048 field_hash (gconstpointer key)
6050 const MonoClassField *field = key;
6051 return g_str_hash (field->name) ^ mono_metadata_type_hash (field->type); /**/
6054 static gboolean
6055 field_equals (gconstpointer _a, gconstpointer _b)
6057 const MonoClassField *a = _a;
6058 const MonoClassField *b = _b;
6059 return !strcmp (a->name, b->name) && mono_metadata_type_equal (a->type, b->type);
6063 static gboolean
6064 verify_class_fields (MonoClass *class)
6066 gpointer iter = NULL;
6067 MonoClassField *field;
6068 MonoGenericContext *context = mono_class_get_context (class);
6069 GHashTable *unique_fields = g_hash_table_new_full (&field_hash, &field_equals, NULL, NULL);
6070 if (class->generic_container)
6071 context = &class->generic_container->context;
6073 while ((field = mono_class_get_fields (class, &iter)) != NULL) {
6074 if (!mono_type_is_valid_type_in_context (field->type, context)) {
6075 g_hash_table_destroy (unique_fields);
6076 return FALSE;
6078 if (g_hash_table_lookup (unique_fields, field)) {
6079 g_hash_table_destroy (unique_fields);
6080 return FALSE;
6082 g_hash_table_insert (unique_fields, field, field);
6084 g_hash_table_destroy (unique_fields);
6085 return TRUE;
6088 static gboolean
6089 verify_interfaces (MonoClass *class)
6091 int i;
6092 for (i = 0; i < class->interface_count; ++i) {
6093 MonoClass *iface = class->interfaces [i];
6094 if (!(iface->flags & TYPE_ATTRIBUTE_INTERFACE))
6095 return FALSE;
6097 return TRUE;
6100 static gboolean
6101 verify_valuetype_layout_with_target (MonoClass *class, MonoClass *target_class)
6103 int type;
6104 gpointer iter = NULL;
6105 MonoClassField *field;
6106 MonoClass *field_class;
6108 if (!class->valuetype)
6109 return TRUE;
6111 type = class->byval_arg.type;
6112 /*primitive type fields are not properly decoded*/
6113 if ((type >= MONO_TYPE_BOOLEAN && type <= MONO_TYPE_R8) || (type >= MONO_TYPE_I && type <= MONO_TYPE_U))
6114 return TRUE;
6116 while ((field = mono_class_get_fields (class, &iter)) != NULL) {
6117 if (!field->type)
6118 return FALSE;
6120 if (field->type->attrs & (FIELD_ATTRIBUTE_STATIC | FIELD_ATTRIBUTE_HAS_FIELD_RVA))
6121 continue;
6123 field_class = mono_class_get_generic_type_definition (mono_class_from_mono_type (field->type));
6125 if (field_class == target_class || !verify_valuetype_layout_with_target (field_class, target_class))
6126 return FALSE;
6129 return TRUE;
6132 static gboolean
6133 verify_valuetype_layout (MonoClass *class)
6135 gboolean res;
6136 res = verify_valuetype_layout_with_target (class, class);
6137 return res;
6141 * Check if the class is verifiable.
6143 * Right now there are no conditions that make a class a valid but not verifiable. Both overlapping reference
6144 * field and invalid generic instantiation are fatal errors.
6146 * This method must be safe to be called from mono_class_init and all code must be carefull about that.
6149 gboolean
6150 mono_verifier_verify_class (MonoClass *class)
6152 if (class->generic_container && (class->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_EXPLICIT_LAYOUT)
6153 return FALSE;
6154 if (!verify_class_for_overlapping_reference_fields (class))
6155 return FALSE;
6156 if (class->generic_class && !mono_class_is_valid_generic_instantiation (NULL, class))
6157 return FALSE;
6158 if (class->generic_class == NULL && !verify_class_fields (class))
6159 return FALSE;
6160 if (class->valuetype && !verify_valuetype_layout (class))
6161 return FALSE;
6162 if (!verify_interfaces (class))
6163 return FALSE;
6164 return TRUE;
6166 #else
6168 gboolean
6169 mono_verifier_verify_class (MonoClass *class)
6171 /* The verifier was disabled at compile time */
6172 return TRUE;
6175 GSList*
6176 mono_method_verify_with_current_settings (MonoMethod *method, gboolean skip_visibility)
6178 /* The verifier was disabled at compile time */
6179 return NULL;
6182 gboolean
6183 mono_verifier_is_class_full_trust (MonoClass *klass)
6185 /* The verifier was disabled at compile time */
6186 return TRUE;
6189 gboolean
6190 mono_verifier_is_method_full_trust (MonoMethod *method)
6192 /* The verifier was disabled at compile time */
6193 return TRUE;
6196 gboolean
6197 mono_verifier_is_enabled_for_image (MonoImage *image)
6199 /* The verifier was disabled at compile time */
6200 return FALSE;
6203 gboolean
6204 mono_verifier_is_enabled_for_class (MonoClass *klass)
6206 /* The verifier was disabled at compile time */
6207 return FALSE;
6210 gboolean
6211 mono_verifier_is_enabled_for_method (MonoMethod *method)
6213 /* The verifier was disabled at compile time */
6214 return FALSE;
6217 GSList*
6218 mono_method_verify (MonoMethod *method, int level)
6220 /* The verifier was disabled at compile time */
6221 return NULL;
6224 void
6225 mono_free_verify_list (GSList *list)
6227 /* The verifier was disabled at compile time */
6228 /* will always be null if verifier is disabled */
6231 GSList*
6232 mono_image_verify_tables (MonoImage *image, int level)
6234 /* The verifier was disabled at compile time */
6235 return NULL;
6237 #endif