2009-12-01 Jb Evain <jbevain@novell.com>
[mono.git] / mono / metadata / verify.c
blobb877c67a0ca648a228cf202144177a56e31644e1
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 g_assert (ctx->eval.size < ctx->max_stack);
2024 return & ctx->eval.stack [ctx->eval.size++];
2027 static ILStackDesc *
2028 stack_push_val (VerifyContext *ctx, int stype, MonoType *type)
2030 ILStackDesc *top = stack_push (ctx);
2031 top->stype = stype;
2032 top->type = type;
2033 return top;
2036 static ILStackDesc *
2037 stack_pop (VerifyContext *ctx)
2039 ILStackDesc *ret;
2040 g_assert (ctx->eval.size > 0);
2041 ret = ctx->eval.stack + --ctx->eval.size;
2042 if ((ret->stype & UNINIT_THIS_MASK) == UNINIT_THIS_MASK)
2043 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Found use of uninitialized 'this ptr' ref at 0x%04x", ctx->ip_offset));
2044 return ret;
2047 /* This function allows to safely pop an unititialized this ptr from
2048 * the eval stack without marking the method as unverifiable.
2050 static ILStackDesc *
2051 stack_pop_safe (VerifyContext *ctx)
2053 g_assert (ctx->eval.size > 0);
2054 return ctx->eval.stack + --ctx->eval.size;
2057 static ILStackDesc *
2058 stack_push_stack_val (VerifyContext *ctx, ILStackDesc *value)
2060 ILStackDesc *top = stack_push (ctx);
2061 copy_stack_value (top, value);
2062 return top;
2065 /* Returns the MonoType associated with the token, or NULL if it is invalid.
2067 * A boxable type can be either a reference or value type, but cannot be a byref type or an unmanaged pointer
2068 * */
2069 static MonoType*
2070 get_boxable_mono_type (VerifyContext* ctx, int token, const char *opcode)
2072 MonoType *type;
2073 MonoClass *class;
2075 if (!(type = verifier_load_type (ctx, token, opcode)))
2076 return NULL;
2078 if (type->byref && type->type != MONO_TYPE_TYPEDBYREF) {
2079 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid use of byref type for %s at 0x%04x", opcode, ctx->ip_offset));
2080 return NULL;
2083 if (type->type == MONO_TYPE_VOID) {
2084 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid use of void type for %s at 0x%04x", opcode, ctx->ip_offset));
2085 return NULL;
2088 if (type->type == MONO_TYPE_TYPEDBYREF)
2089 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid use of typedbyref for %s at 0x%04x", opcode, ctx->ip_offset));
2091 if (!(class = mono_class_from_mono_type (type)))
2092 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Could not retrieve type token for %s at 0x%04x", opcode, ctx->ip_offset));
2094 if (class->generic_container && type->type != MONO_TYPE_GENERICINST)
2095 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));
2097 check_unverifiable_type (ctx, type);
2098 return type;
2102 /*operation result tables */
2104 static const unsigned char bin_op_table [TYPE_MAX][TYPE_MAX] = {
2105 {TYPE_I4, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV},
2106 {TYPE_INV, TYPE_I8, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
2107 {TYPE_NATIVE_INT, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV},
2108 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_R8, TYPE_INV, TYPE_INV},
2109 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
2110 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
2113 static const unsigned char add_table [TYPE_MAX][TYPE_MAX] = {
2114 {TYPE_I4, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV},
2115 {TYPE_INV, TYPE_I8, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
2116 {TYPE_NATIVE_INT, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV},
2117 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_R8, TYPE_INV, TYPE_INV},
2118 {TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV, TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV, TYPE_INV, TYPE_INV},
2119 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
2122 static const unsigned char sub_table [TYPE_MAX][TYPE_MAX] = {
2123 {TYPE_I4, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV},
2124 {TYPE_INV, TYPE_I8, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
2125 {TYPE_NATIVE_INT, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV},
2126 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_R8, TYPE_INV, TYPE_INV},
2127 {TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV, TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV, TYPE_NATIVE_INT | NON_VERIFIABLE_RESULT, TYPE_INV},
2128 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
2131 static const unsigned char int_bin_op_table [TYPE_MAX][TYPE_MAX] = {
2132 {TYPE_I4, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV},
2133 {TYPE_INV, TYPE_I8, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
2134 {TYPE_NATIVE_INT, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV},
2135 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
2136 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
2137 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
2140 static const unsigned char shift_op_table [TYPE_MAX][TYPE_MAX] = {
2141 {TYPE_I4, TYPE_INV, TYPE_I4, TYPE_INV, TYPE_INV, TYPE_INV},
2142 {TYPE_I8, TYPE_INV, TYPE_I8, TYPE_INV, TYPE_INV, TYPE_INV},
2143 {TYPE_NATIVE_INT, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV},
2144 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
2145 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
2146 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
2149 static const unsigned char cmp_br_op [TYPE_MAX][TYPE_MAX] = {
2150 {TYPE_I4, TYPE_INV, TYPE_I4, TYPE_INV, TYPE_INV, TYPE_INV},
2151 {TYPE_INV, TYPE_I4, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
2152 {TYPE_I4, TYPE_INV, TYPE_I4, TYPE_INV, TYPE_INV, TYPE_INV},
2153 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_I4, TYPE_INV, TYPE_INV},
2154 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_I4, TYPE_INV},
2155 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
2158 static const unsigned char cmp_br_eq_op [TYPE_MAX][TYPE_MAX] = {
2159 {TYPE_I4, TYPE_INV, TYPE_I4, TYPE_INV, TYPE_INV, TYPE_INV},
2160 {TYPE_INV, TYPE_I4, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
2161 {TYPE_I4, TYPE_INV, TYPE_I4, TYPE_INV, TYPE_I4 | NON_VERIFIABLE_RESULT, TYPE_INV},
2162 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_I4, TYPE_INV, TYPE_INV},
2163 {TYPE_INV, TYPE_INV, TYPE_I4 | NON_VERIFIABLE_RESULT, TYPE_INV, TYPE_I4, TYPE_INV},
2164 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_I4},
2167 static const unsigned char add_ovf_un_table [TYPE_MAX][TYPE_MAX] = {
2168 {TYPE_I4, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV},
2169 {TYPE_INV, TYPE_I8, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
2170 {TYPE_NATIVE_INT, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV},
2171 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
2172 {TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV, TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV, TYPE_INV, TYPE_INV},
2173 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
2176 static const unsigned char sub_ovf_un_table [TYPE_MAX][TYPE_MAX] = {
2177 {TYPE_I4, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV},
2178 {TYPE_INV, TYPE_I8, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
2179 {TYPE_NATIVE_INT, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV},
2180 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
2181 {TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV, TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV, TYPE_NATIVE_INT | NON_VERIFIABLE_RESULT, TYPE_INV},
2182 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
2185 static const unsigned char bin_ovf_table [TYPE_MAX][TYPE_MAX] = {
2186 {TYPE_I4, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV},
2187 {TYPE_INV, TYPE_I8, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
2188 {TYPE_NATIVE_INT, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV},
2189 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
2190 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
2191 {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
2194 #ifdef MONO_VERIFIER_DEBUG
2196 /*debug helpers */
2197 static void
2198 dump_stack_value (ILStackDesc *value)
2200 printf ("[(%x)(%x)", value->type->type, value->stype);
2202 if (stack_slot_is_this_pointer (value))
2203 printf ("[this] ");
2205 if (stack_slot_is_boxed_value (value))
2206 printf ("[boxed] ");
2208 if (stack_slot_is_null_literal (value))
2209 printf ("[null] ");
2211 if (stack_slot_is_managed_mutability_pointer (value))
2212 printf ("Controled Mutability MP: ");
2214 if (stack_slot_is_managed_pointer (value))
2215 printf ("Managed Pointer to: ");
2217 switch (stack_slot_get_underlying_type (value)) {
2218 case TYPE_INV:
2219 printf ("invalid type]");
2220 return;
2221 case TYPE_I4:
2222 printf ("int32]");
2223 return;
2224 case TYPE_I8:
2225 printf ("int64]");
2226 return;
2227 case TYPE_NATIVE_INT:
2228 printf ("native int]");
2229 return;
2230 case TYPE_R8:
2231 printf ("float64]");
2232 return;
2233 case TYPE_PTR:
2234 printf ("unmanaged pointer]");
2235 return;
2236 case TYPE_COMPLEX:
2237 switch (value->type->type) {
2238 case MONO_TYPE_CLASS:
2239 case MONO_TYPE_VALUETYPE:
2240 printf ("complex] (%s)", value->type->data.klass->name);
2241 return;
2242 case MONO_TYPE_STRING:
2243 printf ("complex] (string)");
2244 return;
2245 case MONO_TYPE_OBJECT:
2246 printf ("complex] (object)");
2247 return;
2248 case MONO_TYPE_SZARRAY:
2249 printf ("complex] (%s [])", value->type->data.klass->name);
2250 return;
2251 case MONO_TYPE_ARRAY:
2252 printf ("complex] (%s [%d %d %d])",
2253 value->type->data.array->eklass->name,
2254 value->type->data.array->rank,
2255 value->type->data.array->numsizes,
2256 value->type->data.array->numlobounds);
2257 return;
2258 case MONO_TYPE_GENERICINST:
2259 printf ("complex] (inst of %s )", value->type->data.generic_class->container_class->name);
2260 return;
2261 case MONO_TYPE_VAR:
2262 printf ("complex] (type generic param !%d - %s) ", value->type->data.generic_param->num, mono_generic_param_info (value->type->data.generic_param)->name);
2263 return;
2264 case MONO_TYPE_MVAR:
2265 printf ("complex] (method generic param !!%d - %s) ", value->type->data.generic_param->num, mono_generic_param_info (value->type->data.generic_param)->name);
2266 return;
2267 default: {
2268 //should be a boxed value
2269 char * name = mono_type_full_name (value->type);
2270 printf ("complex] %s", name);
2271 g_free (name);
2272 return;
2275 default:
2276 printf ("unknown stack %x type]\n", value->stype);
2277 g_assert_not_reached ();
2281 static void
2282 dump_stack_state (ILCodeDesc *state)
2284 int i;
2286 printf ("(%d) ", state->size);
2287 for (i = 0; i < state->size; ++i)
2288 dump_stack_value (state->stack + i);
2289 printf ("\n");
2291 #endif
2293 /*Returns TRUE if candidate array type can be assigned to target.
2294 *Both parameters MUST be of type MONO_TYPE_ARRAY (target->type == MONO_TYPE_ARRAY)
2296 static gboolean
2297 is_array_type_compatible (MonoType *target, MonoType *candidate)
2299 MonoArrayType *left = target->data.array;
2300 MonoArrayType *right = candidate->data.array;
2302 g_assert (target->type == MONO_TYPE_ARRAY);
2303 g_assert (candidate->type == MONO_TYPE_ARRAY);
2305 if (left->rank != right->rank)
2306 return FALSE;
2308 return mono_class_is_assignable_from (left->eklass, right->eklass);
2311 static int
2312 get_stack_type (MonoType *type)
2314 int mask = 0;
2315 int type_kind = type->type;
2316 if (type->byref)
2317 mask = POINTER_MASK;
2318 /*TODO handle CMMP_MASK */
2320 handle_enum:
2321 switch (type_kind) {
2322 case MONO_TYPE_I1:
2323 case MONO_TYPE_U1:
2324 case MONO_TYPE_BOOLEAN:
2325 case MONO_TYPE_I2:
2326 case MONO_TYPE_U2:
2327 case MONO_TYPE_CHAR:
2328 case MONO_TYPE_I4:
2329 case MONO_TYPE_U4:
2330 return TYPE_I4 | mask;
2332 case MONO_TYPE_I:
2333 case MONO_TYPE_U:
2334 return TYPE_NATIVE_INT | mask;
2336 /* FIXME: the spec says that you cannot have a pointer to method pointer, do we need to check this here? */
2337 case MONO_TYPE_FNPTR:
2338 case MONO_TYPE_PTR:
2339 case MONO_TYPE_TYPEDBYREF:
2340 return TYPE_PTR | mask;
2342 case MONO_TYPE_VAR:
2343 case MONO_TYPE_MVAR:
2345 case MONO_TYPE_CLASS:
2346 case MONO_TYPE_STRING:
2347 case MONO_TYPE_OBJECT:
2348 case MONO_TYPE_SZARRAY:
2349 case MONO_TYPE_ARRAY:
2350 return TYPE_COMPLEX | mask;
2352 case MONO_TYPE_GENERICINST:
2353 if (mono_type_is_enum_type (type)) {
2354 type = mono_type_get_underlying_type_any (type);
2355 type_kind = type->type;
2356 goto handle_enum;
2357 } else {
2358 return TYPE_COMPLEX | mask;
2361 case MONO_TYPE_I8:
2362 case MONO_TYPE_U8:
2363 return TYPE_I8 | mask;
2365 case MONO_TYPE_R4:
2366 case MONO_TYPE_R8:
2367 return TYPE_R8 | mask;
2369 case MONO_TYPE_VALUETYPE:
2370 if (mono_type_is_enum_type (type)) {
2371 type = mono_type_get_underlying_type_any (type);
2372 type_kind = type->type;
2373 goto handle_enum;
2374 } else {
2375 return TYPE_COMPLEX | mask;
2378 default:
2379 VERIFIER_DEBUG ( printf ("unknown type %02x in eval stack type\n", type->type); );
2380 g_assert_not_reached ();
2381 return 0;
2385 /* convert MonoType to ILStackDesc format (stype) */
2386 static gboolean
2387 set_stack_value (VerifyContext *ctx, ILStackDesc *stack, MonoType *type, int take_addr)
2389 int mask = 0;
2390 int type_kind = type->type;
2392 if (type->byref || take_addr)
2393 mask = POINTER_MASK;
2394 /* TODO handle CMMP_MASK */
2396 handle_enum:
2397 stack->type = type;
2399 switch (type_kind) {
2400 case MONO_TYPE_I1:
2401 case MONO_TYPE_U1:
2402 case MONO_TYPE_BOOLEAN:
2403 case MONO_TYPE_I2:
2404 case MONO_TYPE_U2:
2405 case MONO_TYPE_CHAR:
2406 case MONO_TYPE_I4:
2407 case MONO_TYPE_U4:
2408 stack->stype = TYPE_I4 | mask;
2409 break;
2410 case MONO_TYPE_I:
2411 case MONO_TYPE_U:
2412 stack->stype = TYPE_NATIVE_INT | mask;
2413 break;
2415 /*FIXME: Do we need to check if it's a pointer to the method pointer? The spec says it' illegal to have that.*/
2416 case MONO_TYPE_FNPTR:
2417 case MONO_TYPE_PTR:
2418 case MONO_TYPE_TYPEDBYREF:
2419 stack->stype = TYPE_PTR | mask;
2420 break;
2422 case MONO_TYPE_CLASS:
2423 case MONO_TYPE_STRING:
2424 case MONO_TYPE_OBJECT:
2425 case MONO_TYPE_SZARRAY:
2426 case MONO_TYPE_ARRAY:
2428 case MONO_TYPE_VAR:
2429 case MONO_TYPE_MVAR:
2430 stack->stype = TYPE_COMPLEX | mask;
2431 break;
2433 case MONO_TYPE_GENERICINST:
2434 if (mono_type_is_enum_type (type)) {
2435 type = mono_type_get_underlying_type_any (type);
2436 type_kind = type->type;
2437 goto handle_enum;
2438 } else {
2439 stack->stype = TYPE_COMPLEX | mask;
2440 break;
2443 case MONO_TYPE_I8:
2444 case MONO_TYPE_U8:
2445 stack->stype = TYPE_I8 | mask;
2446 break;
2447 case MONO_TYPE_R4:
2448 case MONO_TYPE_R8:
2449 stack->stype = TYPE_R8 | mask;
2450 break;
2451 case MONO_TYPE_VALUETYPE:
2452 if (mono_type_is_enum_type (type)) {
2453 type = mono_type_get_underlying_type_any (type);
2454 type_kind = type->type;
2455 goto handle_enum;
2456 } else {
2457 stack->stype = TYPE_COMPLEX | mask;
2458 break;
2460 default:
2461 VERIFIER_DEBUG ( printf ("unknown type 0x%02x in eval stack type\n", type->type); );
2462 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Illegal value set on stack 0x%02x at %d", type->type, ctx->ip_offset));
2463 return FALSE;
2465 return TRUE;
2469 * init_stack_with_value_at_exception_boundary:
2471 * Initialize the stack and push a given type.
2472 * The instruction is marked as been on the exception boundary.
2474 static void
2475 init_stack_with_value_at_exception_boundary (VerifyContext *ctx, ILCodeDesc *code, MonoClass *klass)
2477 MonoError error;
2478 MonoType *type = mono_class_inflate_generic_type_checked (&klass->byval_arg, ctx->generic_context, &error);
2480 if (!mono_error_ok (&error)) {
2481 char *name = mono_type_get_full_name (klass);
2482 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid class %s used for exception", name));
2483 g_free (name);
2484 mono_error_cleanup (&error);
2485 return;
2488 stack_init (ctx, code);
2489 set_stack_value (ctx, code->stack, type, FALSE);
2490 ctx->exception_types = g_slist_prepend (ctx->exception_types, type);
2491 code->size = 1;
2492 code->flags |= IL_CODE_FLAG_WAS_TARGET;
2493 if (mono_type_is_generic_argument (type))
2494 code->stack->stype |= BOXED_MASK;
2497 /*Verify if type 'candidate' can be stored in type 'target'.
2499 * If strict, check for the underlying type and not the verification stack types
2501 static gboolean
2502 verify_type_compatibility_full (VerifyContext *ctx, MonoType *target, MonoType *candidate, gboolean strict)
2504 #define IS_ONE_OF3(T, A, B, C) (T == A || T == B || T == C)
2505 #define IS_ONE_OF2(T, A, B) (T == A || T == B)
2507 MonoType *original_candidate = candidate;
2508 VERIFIER_DEBUG ( printf ("checking type compatibility %s x %s strict %d\n", mono_type_full_name (target), mono_type_full_name (candidate), strict); );
2510 /*only one is byref */
2511 if (candidate->byref ^ target->byref) {
2512 /* converting from native int to byref*/
2513 if (get_stack_type (candidate) == TYPE_NATIVE_INT && target->byref) {
2514 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("using byref native int at 0x%04x", ctx->ip_offset));
2515 return TRUE;
2517 return FALSE;
2519 strict |= target->byref;
2520 /*From now on we don't care about byref anymore, so it's ok to discard it here*/
2521 candidate = mono_type_get_underlying_type_any (candidate);
2523 handle_enum:
2524 switch (target->type) {
2525 case MONO_TYPE_VOID:
2526 return candidate->type == MONO_TYPE_VOID;
2527 case MONO_TYPE_I1:
2528 case MONO_TYPE_U1:
2529 case MONO_TYPE_BOOLEAN:
2530 if (strict)
2531 return IS_ONE_OF3 (candidate->type, MONO_TYPE_I1, MONO_TYPE_U1, MONO_TYPE_BOOLEAN);
2532 case MONO_TYPE_I2:
2533 case MONO_TYPE_U2:
2534 case MONO_TYPE_CHAR:
2535 if (strict)
2536 return IS_ONE_OF3 (candidate->type, MONO_TYPE_I2, MONO_TYPE_U2, MONO_TYPE_CHAR);
2537 case MONO_TYPE_I4:
2538 case MONO_TYPE_U4: {
2539 gboolean is_native_int = IS_ONE_OF2 (candidate->type, MONO_TYPE_I, MONO_TYPE_U);
2540 gboolean is_int4 = IS_ONE_OF2 (candidate->type, MONO_TYPE_I4, MONO_TYPE_U4);
2541 if (strict)
2542 return is_native_int || is_int4;
2543 return is_native_int || get_stack_type (candidate) == TYPE_I4;
2546 case MONO_TYPE_I8:
2547 case MONO_TYPE_U8:
2548 return IS_ONE_OF2 (candidate->type, MONO_TYPE_I8, MONO_TYPE_U8);
2550 case MONO_TYPE_R4:
2551 case MONO_TYPE_R8:
2552 if (strict)
2553 return candidate->type == target->type;
2554 return IS_ONE_OF2 (candidate->type, MONO_TYPE_R4, MONO_TYPE_R8);
2556 case MONO_TYPE_I:
2557 case MONO_TYPE_U: {
2558 gboolean is_native_int = IS_ONE_OF2 (candidate->type, MONO_TYPE_I, MONO_TYPE_U);
2559 gboolean is_int4 = IS_ONE_OF2 (candidate->type, MONO_TYPE_I4, MONO_TYPE_U4);
2560 if (strict)
2561 return is_native_int || is_int4;
2562 return is_native_int || get_stack_type (candidate) == TYPE_I4;
2565 case MONO_TYPE_PTR:
2566 if (candidate->type != MONO_TYPE_PTR)
2567 return FALSE;
2568 /* check the underlying type */
2569 return verify_type_compatibility_full (ctx, target->data.type, candidate->data.type, TRUE);
2571 case MONO_TYPE_FNPTR: {
2572 MonoMethodSignature *left, *right;
2573 if (candidate->type != MONO_TYPE_FNPTR)
2574 return FALSE;
2576 left = mono_type_get_signature (target);
2577 right = mono_type_get_signature (candidate);
2578 return mono_metadata_signature_equal (left, right) && left->call_convention == right->call_convention;
2581 case MONO_TYPE_GENERICINST: {
2582 MonoClass *target_klass;
2583 MonoClass *candidate_klass;
2584 if (mono_type_is_enum_type (target)) {
2585 target = mono_type_get_underlying_type_any (target);
2586 goto handle_enum;
2588 target_klass = mono_class_from_mono_type (target);
2589 candidate_klass = mono_class_from_mono_type (candidate);
2590 if (mono_class_is_nullable (target_klass)) {
2591 if (!mono_class_is_nullable (candidate_klass))
2592 return FALSE;
2593 return target_klass == candidate_klass;
2596 return mono_class_is_assignable_from (target_klass, candidate_klass);
2599 case MONO_TYPE_STRING:
2600 return candidate->type == MONO_TYPE_STRING;
2602 case MONO_TYPE_CLASS:
2604 * VAR / MVAR compatibility must be checked by verify_stack_type_compatibility
2605 * to take boxing status into account.
2607 if (mono_type_is_generic_argument (original_candidate))
2608 return FALSE;
2609 /* If candidate is an enum it should return true for System.Enum and supertypes.
2610 * That's why here we use the original type and not the underlying type.
2612 return mono_class_is_assignable_from (target->data.klass, mono_class_from_mono_type (original_candidate));
2614 case MONO_TYPE_OBJECT:
2615 return MONO_TYPE_IS_REFERENCE (candidate);
2617 case MONO_TYPE_SZARRAY: {
2618 MonoClass *left;
2619 MonoClass *right;
2620 if (candidate->type != MONO_TYPE_SZARRAY)
2621 return FALSE;
2623 left = mono_class_from_mono_type (target)->element_class;
2624 right = mono_class_from_mono_type (candidate)->element_class;
2625 return mono_class_is_assignable_from (left, right);
2628 case MONO_TYPE_ARRAY:
2629 if (candidate->type != MONO_TYPE_ARRAY)
2630 return FALSE;
2631 return is_array_type_compatible (target, candidate);
2633 case MONO_TYPE_TYPEDBYREF:
2634 return candidate->type == MONO_TYPE_TYPEDBYREF;
2636 case MONO_TYPE_VALUETYPE: {
2637 MonoClass *target_klass = mono_class_from_mono_type (target);
2638 MonoClass *candidate_klass = mono_class_from_mono_type (candidate);
2640 if (target_klass == candidate_klass)
2641 return TRUE;
2642 if (mono_type_is_enum_type (target)) {
2643 target = mono_type_get_underlying_type_any (target);
2644 goto handle_enum;
2646 return FALSE;
2649 case MONO_TYPE_VAR:
2650 if (candidate->type != MONO_TYPE_VAR)
2651 return FALSE;
2652 return mono_type_get_generic_param_num (candidate) == mono_type_get_generic_param_num (target);
2654 case MONO_TYPE_MVAR:
2655 if (candidate->type != MONO_TYPE_MVAR)
2656 return FALSE;
2657 return mono_type_get_generic_param_num (candidate) == mono_type_get_generic_param_num (target);
2659 default:
2660 VERIFIER_DEBUG ( printf ("unknown store type %d\n", target->type); );
2661 g_assert_not_reached ();
2662 return FALSE;
2664 return 1;
2665 #undef IS_ONE_OF3
2666 #undef IS_ONE_OF2
2669 static gboolean
2670 verify_type_compatibility (VerifyContext *ctx, MonoType *target, MonoType *candidate)
2672 return verify_type_compatibility_full (ctx, target, candidate, FALSE);
2676 * Returns the generic param bound to the context been verified.
2679 static MonoGenericParam*
2680 get_generic_param (VerifyContext *ctx, MonoType *param)
2682 guint16 param_num = mono_type_get_generic_param_num (param);
2683 if (param->type == MONO_TYPE_VAR) {
2684 if (!ctx->generic_context->class_inst || ctx->generic_context->class_inst->type_argc <= param_num) {
2685 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid generic type argument %d", param_num));
2686 return NULL;
2688 return ctx->generic_context->class_inst->type_argv [param_num]->data.generic_param;
2691 /*param must be a MVAR */
2692 if (!ctx->generic_context->method_inst || ctx->generic_context->method_inst->type_argc <= param_num) {
2693 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid generic method argument %d", param_num));
2694 return NULL;
2696 return ctx->generic_context->method_inst->type_argv [param_num]->data.generic_param;
2700 * is_compatible_boxed_valuetype:
2702 * Returns TRUE if @candidate / @stack is a valid boxed valuetype.
2704 * @type The source type. It it tested to be of the proper type.
2705 * @candidate type of the boxed valuetype.
2706 * @stack stack slot of the boxed valuetype, separate from @candidade since one could be changed before calling this function
2707 * @strict if TRUE candidate must be boxed compatible to the target type
2710 static gboolean
2711 is_compatible_boxed_valuetype (VerifyContext *ctx, MonoType *type, MonoType *candidate, ILStackDesc *stack, gboolean strict)
2713 if (!stack_slot_is_boxed_value (stack))
2714 return FALSE;
2715 if (type->byref || candidate->byref)
2716 return FALSE;
2718 if (mono_type_is_generic_argument (candidate)) {
2719 MonoGenericParam *param = get_generic_param (ctx, candidate);
2720 MonoClass **class;
2721 for (class = mono_generic_param_info (param)->constraints; class && *class; ++class) {
2722 if (verify_type_compatibility_full (ctx, type, mono_type_get_type_byval (& (*class)->byval_arg), FALSE))
2723 return TRUE;
2727 if (mono_type_is_generic_argument (type))
2728 return FALSE;
2730 if (!strict)
2731 return TRUE;
2733 return MONO_TYPE_IS_REFERENCE (type) && mono_class_is_assignable_from (mono_class_from_mono_type (type), mono_class_from_mono_type (candidate));
2736 static int
2737 verify_stack_type_compatibility_full (VerifyContext *ctx, MonoType *type, ILStackDesc *stack, gboolean drop_byref, gboolean valuetype_must_be_boxed)
2739 MonoType *candidate = mono_type_from_stack_slot (stack);
2740 if (MONO_TYPE_IS_REFERENCE (type) && !type->byref && stack_slot_is_null_literal (stack))
2741 return TRUE;
2743 if (is_compatible_boxed_valuetype (ctx, type, candidate, stack, TRUE))
2744 return TRUE;
2746 if (valuetype_must_be_boxed && !stack_slot_is_boxed_value (stack) && !MONO_TYPE_IS_REFERENCE (candidate))
2747 return FALSE;
2749 if (!valuetype_must_be_boxed && stack_slot_is_boxed_value (stack))
2750 return FALSE;
2752 if (drop_byref)
2753 return verify_type_compatibility_full (ctx, type, mono_type_get_type_byval (candidate), FALSE);
2755 return verify_type_compatibility_full (ctx, type, candidate, FALSE);
2758 static int
2759 verify_stack_type_compatibility (VerifyContext *ctx, MonoType *type, ILStackDesc *stack)
2761 return verify_stack_type_compatibility_full (ctx, type, stack, FALSE, FALSE);
2764 static gboolean
2765 mono_delegate_type_equal (MonoType *target, MonoType *candidate)
2767 if (candidate->byref ^ target->byref)
2768 return FALSE;
2770 switch (target->type) {
2771 case MONO_TYPE_VOID:
2772 case MONO_TYPE_I1:
2773 case MONO_TYPE_U1:
2774 case MONO_TYPE_BOOLEAN:
2775 case MONO_TYPE_I2:
2776 case MONO_TYPE_U2:
2777 case MONO_TYPE_CHAR:
2778 case MONO_TYPE_I4:
2779 case MONO_TYPE_U4:
2780 case MONO_TYPE_I8:
2781 case MONO_TYPE_U8:
2782 case MONO_TYPE_R4:
2783 case MONO_TYPE_R8:
2784 case MONO_TYPE_I:
2785 case MONO_TYPE_U:
2786 case MONO_TYPE_STRING:
2787 case MONO_TYPE_TYPEDBYREF:
2788 return candidate->type == target->type;
2790 case MONO_TYPE_PTR:
2791 return mono_delegate_type_equal (target->data.type, candidate->data.type);
2793 case MONO_TYPE_FNPTR:
2794 if (candidate->type != MONO_TYPE_FNPTR)
2795 return FALSE;
2796 return mono_delegate_signature_equal (mono_type_get_signature (target), mono_type_get_signature (candidate), FALSE);
2798 case MONO_TYPE_GENERICINST: {
2799 MonoClass *target_klass;
2800 MonoClass *candidate_klass;
2801 target_klass = mono_class_from_mono_type (target);
2802 candidate_klass = mono_class_from_mono_type (candidate);
2803 /*FIXME handle nullables and enum*/
2804 return mono_class_is_assignable_from (target_klass, candidate_klass);
2806 case MONO_TYPE_OBJECT:
2807 return MONO_TYPE_IS_REFERENCE (candidate);
2809 case MONO_TYPE_CLASS:
2810 return mono_class_is_assignable_from(target->data.klass, mono_class_from_mono_type (candidate));
2812 case MONO_TYPE_SZARRAY:
2813 if (candidate->type != MONO_TYPE_SZARRAY)
2814 return FALSE;
2815 return mono_class_is_assignable_from (mono_class_from_mono_type (target)->element_class, mono_class_from_mono_type (candidate)->element_class);
2817 case MONO_TYPE_ARRAY:
2818 if (candidate->type != MONO_TYPE_ARRAY)
2819 return FALSE;
2820 return is_array_type_compatible (target, candidate);
2822 case MONO_TYPE_VALUETYPE:
2823 /*FIXME handle nullables and enum*/
2824 return mono_class_from_mono_type (candidate) == mono_class_from_mono_type (target);
2826 case MONO_TYPE_VAR:
2827 return candidate->type == MONO_TYPE_VAR && mono_type_get_generic_param_num (target) == mono_type_get_generic_param_num (candidate);
2828 return FALSE;
2830 case MONO_TYPE_MVAR:
2831 return candidate->type == MONO_TYPE_MVAR && mono_type_get_generic_param_num (target) == mono_type_get_generic_param_num (candidate);
2832 return FALSE;
2834 default:
2835 VERIFIER_DEBUG ( printf ("Unknown type %d. Implement me!\n", target->type); );
2836 g_assert_not_reached ();
2837 return FALSE;
2841 static gboolean
2842 mono_delegate_param_equal (MonoType *delegate, MonoType *method)
2844 if (mono_metadata_type_equal_full (delegate, method, TRUE))
2845 return TRUE;
2847 return mono_delegate_type_equal (method, delegate);
2850 static gboolean
2851 mono_delegate_ret_equal (MonoType *delegate, MonoType *method)
2853 if (mono_metadata_type_equal_full (delegate, method, TRUE))
2854 return TRUE;
2856 return mono_delegate_type_equal (delegate, method);
2860 * mono_delegate_signature_equal:
2862 * Compare two signatures in the way expected by delegates.
2864 * This function only exists due to the fact that it should ignore the 'has_this' part of the signature.
2866 * FIXME can this function be eliminated and proper metadata functionality be used?
2868 static gboolean
2869 mono_delegate_signature_equal (MonoMethodSignature *delegate_sig, MonoMethodSignature *method_sig, gboolean is_static_ldftn)
2871 int i;
2872 int method_offset = is_static_ldftn ? 1 : 0;
2874 if (delegate_sig->param_count + method_offset != method_sig->param_count)
2875 return FALSE;
2877 if (delegate_sig->call_convention != method_sig->call_convention)
2878 return FALSE;
2880 for (i = 0; i < delegate_sig->param_count; i++) {
2881 MonoType *p1 = delegate_sig->params [i];
2882 MonoType *p2 = method_sig->params [i + method_offset];
2884 if (!mono_delegate_param_equal (p1, p2))
2885 return FALSE;
2888 if (!mono_delegate_ret_equal (delegate_sig->ret, method_sig->ret))
2889 return FALSE;
2891 return TRUE;
2895 * verify_ldftn_delegate:
2897 * Verify properties of ldftn based delegates.
2899 static void
2900 verify_ldftn_delegate (VerifyContext *ctx, MonoClass *delegate, ILStackDesc *value, ILStackDesc *funptr)
2902 MonoMethod *method = funptr->method;
2904 /*ldftn non-final virtuals only allowed if method is not static,
2905 * the object is a this arg (comes from a ldarg.0), and there is no starg.0.
2906 * This rules doesn't apply if the object on stack is a boxed valuetype.
2908 if ((method->flags & METHOD_ATTRIBUTE_VIRTUAL) && !(method->flags & METHOD_ATTRIBUTE_FINAL) && !(method->klass->flags & TYPE_ATTRIBUTE_SEALED) && !stack_slot_is_boxed_value (value)) {
2909 /*A stdarg 0 must not happen, we fail here only in fail fast mode to avoid double error reports*/
2910 if (IS_FAIL_FAST_MODE (ctx) && ctx->has_this_store)
2911 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid ldftn with virtual function in method with stdarg 0 at 0x%04x", ctx->ip_offset));
2913 /*current method must not be static*/
2914 if (ctx->method->flags & METHOD_ATTRIBUTE_STATIC)
2915 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid ldftn with virtual function at 0x%04x", ctx->ip_offset));
2917 /*value is the this pointer, loaded using ldarg.0 */
2918 if (!stack_slot_is_this_pointer (value))
2919 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));
2921 ctx->code [ctx->ip_offset].flags |= IL_CODE_LDFTN_DELEGATE_NONFINAL_VIRTUAL;
2926 * verify_delegate_compatibility:
2928 * Verify delegate creation sequence.
2931 static void
2932 verify_delegate_compatibility (VerifyContext *ctx, MonoClass *delegate, ILStackDesc *value, ILStackDesc *funptr)
2934 #define IS_VALID_OPCODE(offset, opcode) (ip [ip_offset - offset] == opcode && (ctx->code [ip_offset - offset].flags & IL_CODE_FLAG_SEEN))
2935 #define IS_LOAD_FUN_PTR(kind) (IS_VALID_OPCODE (6, CEE_PREFIX1) && ip [ip_offset - 5] == kind)
2937 MonoMethod *invoke, *method;
2938 const guint8 *ip = ctx->header->code;
2939 guint32 ip_offset = ctx->ip_offset;
2940 gboolean is_static_ldftn = FALSE, is_first_arg_bound = FALSE;
2942 if (stack_slot_get_type (funptr) != TYPE_PTR || !funptr->method) {
2943 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid function pointer parameter for delegate constructor at 0x%04x", ctx->ip_offset));
2944 return;
2947 invoke = mono_get_delegate_invoke (delegate);
2948 method = funptr->method;
2950 is_static_ldftn = (ip_offset > 5 && IS_LOAD_FUN_PTR (CEE_LDFTN)) && method->flags & METHOD_ATTRIBUTE_STATIC;
2952 if (is_static_ldftn)
2953 is_first_arg_bound = mono_method_signature (invoke)->param_count + 1 == mono_method_signature (method)->param_count;
2955 if (!mono_delegate_signature_equal (mono_method_signature (invoke), mono_method_signature (method), is_first_arg_bound)) {
2956 char *fun_sig = mono_signature_get_desc (mono_method_signature (method), FALSE);
2957 char *invoke_sig = mono_signature_get_desc (mono_method_signature (invoke), FALSE);
2958 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));
2959 g_free (fun_sig);
2960 g_free (invoke_sig);
2964 * Delegate code sequences:
2965 * [-6] ldftn token
2966 * newobj ...
2969 * [-7] dup
2970 * [-6] ldvirtftn token
2971 * newobj ...
2973 * ldftn sequence:*/
2974 if (ip_offset > 5 && IS_LOAD_FUN_PTR (CEE_LDFTN)) {
2975 verify_ldftn_delegate (ctx, delegate, value, funptr);
2976 } else if (ip_offset > 6 && IS_VALID_OPCODE (7, CEE_DUP) && IS_LOAD_FUN_PTR (CEE_LDVIRTFTN)) {
2977 ctx->code [ip_offset - 6].flags |= IL_CODE_DELEGATE_SEQUENCE;
2978 }else {
2979 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid code sequence for delegate creation at 0x%04x", ctx->ip_offset));
2981 ctx->code [ip_offset].flags |= IL_CODE_DELEGATE_SEQUENCE;
2983 //general tests
2984 if (is_first_arg_bound) {
2985 if (mono_method_signature (method)->param_count == 0 || !verify_stack_type_compatibility_full (ctx, mono_method_signature (method)->params [0], value, FALSE, TRUE))
2986 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("This object not compatible with function pointer for delegate creation at 0x%04x", ctx->ip_offset));
2987 } else {
2988 if (method->flags & METHOD_ATTRIBUTE_STATIC) {
2989 if (!stack_slot_is_null_literal (value) && !is_first_arg_bound)
2990 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Non-null this args used with static function for delegate creation at 0x%04x", ctx->ip_offset));
2991 } else {
2992 if (!verify_stack_type_compatibility_full (ctx, &method->klass->byval_arg, value, FALSE, TRUE) && !stack_slot_is_null_literal (value))
2993 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("This object not compatible with function pointer for delegate creation at 0x%04x", ctx->ip_offset));
2997 if (stack_slot_get_type (value) != TYPE_COMPLEX)
2998 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid first parameter for delegate creation at 0x%04x", ctx->ip_offset));
3000 #undef IS_VALID_OPCODE
3001 #undef IS_LOAD_FUN_PTR
3004 /* implement the opcode checks*/
3005 static void
3006 push_arg (VerifyContext *ctx, unsigned int arg, int take_addr)
3008 ILStackDesc *top;
3010 if (arg >= ctx->max_args) {
3011 if (take_addr)
3012 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Method doesn't have argument %d", arg + 1));
3013 else {
3014 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Method doesn't have argument %d", arg + 1));
3015 if (check_overflow (ctx)) //FIXME: what sane value could we ever push?
3016 stack_push_val (ctx, TYPE_I4, &mono_defaults.int32_class->byval_arg);
3018 } else if (check_overflow (ctx)) {
3019 /*We must let the value be pushed, otherwise we would get an underflow error*/
3020 check_unverifiable_type (ctx, ctx->params [arg]);
3021 if (ctx->params [arg]->byref && take_addr)
3022 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("ByRef of ByRef at 0x%04x", ctx->ip_offset));
3023 top = stack_push (ctx);
3024 if (!set_stack_value (ctx, top, ctx->params [arg], take_addr))
3025 return;
3027 if (arg == 0 && !(ctx->method->flags & METHOD_ATTRIBUTE_STATIC)) {
3028 if (take_addr)
3029 ctx->has_this_store = TRUE;
3030 else
3031 top->stype |= THIS_POINTER_MASK;
3032 if (mono_method_is_constructor (ctx->method) && !ctx->super_ctor_called && !ctx->method->klass->valuetype)
3033 top->stype |= UNINIT_THIS_MASK;
3038 static void
3039 push_local (VerifyContext *ctx, guint32 arg, int take_addr)
3041 if (arg >= ctx->num_locals) {
3042 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Method doesn't have local %d", arg + 1));
3043 } else if (check_overflow (ctx)) {
3044 /*We must let the value be pushed, otherwise we would get an underflow error*/
3045 check_unverifiable_type (ctx, ctx->locals [arg]);
3046 if (ctx->locals [arg]->byref && take_addr)
3047 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("ByRef of ByRef at 0x%04x", ctx->ip_offset));
3049 set_stack_value (ctx, stack_push (ctx), ctx->locals [arg], take_addr);
3053 static void
3054 store_arg (VerifyContext *ctx, guint32 arg)
3056 ILStackDesc *value;
3058 if (arg >= ctx->max_args) {
3059 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Method doesn't have argument %d at 0x%04x", arg + 1, ctx->ip_offset));
3060 if (check_underflow (ctx, 1))
3061 stack_pop (ctx);
3062 return;
3065 if (check_underflow (ctx, 1)) {
3066 value = stack_pop (ctx);
3067 if (!verify_stack_type_compatibility (ctx, ctx->params [arg], value)) {
3068 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Incompatible type %s in argument store at 0x%04x", stack_slot_get_name (value), ctx->ip_offset));
3071 if (arg == 0 && !(ctx->method->flags & METHOD_ATTRIBUTE_STATIC))
3072 ctx->has_this_store = 1;
3075 static void
3076 store_local (VerifyContext *ctx, guint32 arg)
3078 ILStackDesc *value;
3079 if (arg >= ctx->num_locals) {
3080 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Method doesn't have local var %d at 0x%04x", arg + 1, ctx->ip_offset));
3081 return;
3084 /*TODO verify definite assigment */
3085 if (check_underflow (ctx, 1)) {
3086 value = stack_pop(ctx);
3087 if (!verify_stack_type_compatibility (ctx, ctx->locals [arg], value)) {
3088 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Incompatible type [%s], type [%s] was expected in local store at 0x%04x",
3089 stack_slot_get_name (value),
3090 mono_type_get_stack_name (ctx->locals [arg]),
3091 ctx->ip_offset));
3096 /*FIXME add and sub needs special care here*/
3097 static void
3098 do_binop (VerifyContext *ctx, unsigned int opcode, const unsigned char table [TYPE_MAX][TYPE_MAX])
3100 ILStackDesc *a, *b, *top;
3101 int idxa, idxb, complexMerge = 0;
3102 unsigned char res;
3104 if (!check_underflow (ctx, 2))
3105 return;
3106 b = stack_pop (ctx);
3107 a = stack_pop (ctx);
3109 idxa = stack_slot_get_underlying_type (a);
3110 if (stack_slot_is_managed_pointer (a)) {
3111 idxa = TYPE_PTR;
3112 complexMerge = 1;
3115 idxb = stack_slot_get_underlying_type (b);
3116 if (stack_slot_is_managed_pointer (b)) {
3117 idxb = TYPE_PTR;
3118 complexMerge = 2;
3121 --idxa;
3122 --idxb;
3123 res = table [idxa][idxb];
3125 VERIFIER_DEBUG ( printf ("binop res %d\n", res); );
3126 VERIFIER_DEBUG ( printf ("idxa %d idxb %d\n", idxa, idxb); );
3128 top = stack_push (ctx);
3129 if (res == TYPE_INV) {
3130 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)));
3131 copy_stack_value (top, a);
3132 return;
3135 if (res & NON_VERIFIABLE_RESULT) {
3136 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)));
3138 res = res & ~NON_VERIFIABLE_RESULT;
3141 if (complexMerge && res == TYPE_PTR) {
3142 if (complexMerge == 1)
3143 copy_stack_value (top, a);
3144 else if (complexMerge == 2)
3145 copy_stack_value (top, b);
3147 * There is no need to merge the type of two pointers.
3148 * The only valid operation is subtraction, that returns a native
3149 * int as result and can be used with any 2 pointer kinds.
3150 * This is valid acording to Patition III 1.1.4
3152 } else
3153 top->stype = res;
3158 static void
3159 do_boolean_branch_op (VerifyContext *ctx, int delta)
3161 int target = ctx->ip_offset + delta;
3162 ILStackDesc *top;
3164 VERIFIER_DEBUG ( printf ("boolean branch offset %d delta %d target %d\n", ctx->ip_offset, delta, target); );
3166 if (target < 0 || target >= ctx->code_size) {
3167 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Boolean branch target out of code at 0x%04x", ctx->ip_offset));
3168 return;
3171 switch (is_valid_branch_instruction (ctx->header, ctx->ip_offset, target)) {
3172 case 1:
3173 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Branch target escapes out of exception block at 0x%04x", ctx->ip_offset));
3174 break;
3175 case 2:
3176 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Branch target escapes out of exception block at 0x%04x", ctx->ip_offset));
3177 return;
3180 ctx->target = target;
3182 if (!check_underflow (ctx, 1))
3183 return;
3185 top = stack_pop (ctx);
3186 if (!is_valid_bool_arg (top))
3187 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));
3189 check_unmanaged_pointer (ctx, top);
3192 static gboolean
3193 stack_slot_is_complex_type_not_reference_type (ILStackDesc *slot)
3195 return stack_slot_get_type (slot) == TYPE_COMPLEX && !MONO_TYPE_IS_REFERENCE (slot->type) && !stack_slot_is_boxed_value (slot);
3198 static void
3199 do_branch_op (VerifyContext *ctx, signed int delta, const unsigned char table [TYPE_MAX][TYPE_MAX])
3201 ILStackDesc *a, *b;
3202 int idxa, idxb;
3203 unsigned char res;
3204 int target = ctx->ip_offset + delta;
3206 VERIFIER_DEBUG ( printf ("branch offset %d delta %d target %d\n", ctx->ip_offset, delta, target); );
3208 if (target < 0 || target >= ctx->code_size) {
3209 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Branch target out of code at 0x%04x", ctx->ip_offset));
3210 return;
3213 switch (is_valid_cmp_branch_instruction (ctx->header, ctx->ip_offset, target)) {
3214 case 1: /*FIXME use constants and not magic numbers.*/
3215 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Branch target escapes out of exception block at 0x%04x", ctx->ip_offset));
3216 break;
3217 case 2:
3218 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Branch target escapes out of exception block at 0x%04x", ctx->ip_offset));
3219 return;
3222 ctx->target = target;
3224 if (!check_underflow (ctx, 2))
3225 return;
3227 b = stack_pop (ctx);
3228 a = stack_pop (ctx);
3230 idxa = stack_slot_get_underlying_type (a);
3231 if (stack_slot_is_managed_pointer (a))
3232 idxa = TYPE_PTR;
3234 idxb = stack_slot_get_underlying_type (b);
3235 if (stack_slot_is_managed_pointer (b))
3236 idxb = TYPE_PTR;
3238 if (stack_slot_is_complex_type_not_reference_type (a) || stack_slot_is_complex_type_not_reference_type (b)) {
3239 res = TYPE_INV;
3240 } else {
3241 --idxa;
3242 --idxb;
3243 res = table [idxa][idxb];
3246 VERIFIER_DEBUG ( printf ("branch res %d\n", res); );
3247 VERIFIER_DEBUG ( printf ("idxa %d idxb %d\n", idxa, idxb); );
3249 if (res == TYPE_INV) {
3250 CODE_NOT_VERIFIABLE (ctx,
3251 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));
3252 } else if (res & NON_VERIFIABLE_RESULT) {
3253 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));
3254 res = res & ~NON_VERIFIABLE_RESULT;
3258 static void
3259 do_cmp_op (VerifyContext *ctx, const unsigned char table [TYPE_MAX][TYPE_MAX], guint32 opcode)
3261 ILStackDesc *a, *b;
3262 int idxa, idxb;
3263 unsigned char res;
3265 if (!check_underflow (ctx, 2))
3266 return;
3267 b = stack_pop (ctx);
3268 a = stack_pop (ctx);
3270 if (opcode == CEE_CGT_UN) {
3271 if (stack_slot_get_type (a) == TYPE_COMPLEX && stack_slot_get_type (b) == TYPE_COMPLEX) {
3272 stack_push_val (ctx, TYPE_I4, &mono_defaults.int32_class->byval_arg);
3273 return;
3277 idxa = stack_slot_get_underlying_type (a);
3278 if (stack_slot_is_managed_pointer (a))
3279 idxa = TYPE_PTR;
3281 idxb = stack_slot_get_underlying_type (b);
3282 if (stack_slot_is_managed_pointer (b))
3283 idxb = TYPE_PTR;
3285 if (stack_slot_is_complex_type_not_reference_type (a) || stack_slot_is_complex_type_not_reference_type (b)) {
3286 res = TYPE_INV;
3287 } else {
3288 --idxa;
3289 --idxb;
3290 res = table [idxa][idxb];
3293 if(res == TYPE_INV) {
3294 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));
3295 } else if (res & NON_VERIFIABLE_RESULT) {
3296 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));
3297 res = res & ~NON_VERIFIABLE_RESULT;
3299 stack_push_val (ctx, TYPE_I4, &mono_defaults.int32_class->byval_arg);
3302 static void
3303 do_ret (VerifyContext *ctx)
3305 MonoType *ret = ctx->signature->ret;
3306 VERIFIER_DEBUG ( printf ("checking ret\n"); );
3307 if (ret->type != MONO_TYPE_VOID) {
3308 ILStackDesc *top;
3309 if (!check_underflow (ctx, 1))
3310 return;
3312 top = stack_pop(ctx);
3314 if (!verify_stack_type_compatibility (ctx, ctx->signature->ret, top)) {
3315 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Incompatible return value on stack with method signature ret at 0x%04x", ctx->ip_offset));
3316 return;
3319 if (ret->byref || ret->type == MONO_TYPE_TYPEDBYREF || mono_type_is_value_type (ret, "System", "ArgIterator") || mono_type_is_value_type (ret, "System", "RuntimeArgumentHandle"))
3320 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Method returns byref, TypedReference, ArgIterator or RuntimeArgumentHandle at 0x%04x", ctx->ip_offset));
3323 if (ctx->eval.size > 0) {
3324 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Stack not empty (%d) after ret at 0x%04x", ctx->eval.size, ctx->ip_offset));
3326 if (in_any_block (ctx->header, ctx->ip_offset))
3327 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("ret cannot escape exception blocks at 0x%04x", ctx->ip_offset));
3331 * 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.
3332 * This is illegal but mono_get_method_full decoded it.
3333 * TODO handle calling .ctor outside one or calling the .ctor for other class but super
3335 static void
3336 do_invoke_method (VerifyContext *ctx, int method_token, gboolean virtual)
3338 int param_count, i;
3339 MonoMethodSignature *sig;
3340 ILStackDesc *value;
3341 MonoMethod *method;
3342 gboolean virt_check_this = FALSE;
3343 gboolean constrained = ctx->prefix_set & PREFIX_CONSTRAINED;
3345 if (!(method = verifier_load_method (ctx, method_token, virtual ? "callvirt" : "call")))
3346 return;
3348 if (virtual) {
3349 CLEAR_PREFIX (ctx, PREFIX_CONSTRAINED);
3351 if (method->klass->valuetype) // && !constrained ???
3352 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use callvirtual with valuetype method at 0x%04x", ctx->ip_offset));
3354 if ((method->flags & METHOD_ATTRIBUTE_STATIC))
3355 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use callvirtual with static method at 0x%04x", ctx->ip_offset));
3357 } else {
3358 if (method->flags & METHOD_ATTRIBUTE_ABSTRACT)
3359 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use call with an abstract method at 0x%04x", ctx->ip_offset));
3361 if ((method->flags & METHOD_ATTRIBUTE_VIRTUAL) && !(method->flags & METHOD_ATTRIBUTE_FINAL)) {
3362 virt_check_this = TRUE;
3363 ctx->code [ctx->ip_offset].flags |= IL_CODE_CALL_NONFINAL_VIRTUAL;
3367 if (!(sig = mono_method_get_signature_full (method, ctx->image, method_token, ctx->generic_context)))
3368 sig = mono_method_get_signature (method, ctx->image, method_token);
3370 param_count = sig->param_count + sig->hasthis;
3371 if (!check_underflow (ctx, param_count))
3372 return;
3374 for (i = sig->param_count - 1; i >= 0; --i) {
3375 VERIFIER_DEBUG ( printf ("verifying argument %d\n", i); );
3376 value = stack_pop (ctx);
3377 if (!verify_stack_type_compatibility (ctx, sig->params[i], value)) {
3378 char *stack_name = stack_slot_full_name (value);
3379 char *sig_name = mono_type_full_name (sig->params [i]);
3380 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));
3381 g_free (stack_name);
3382 g_free (sig_name);
3385 if (stack_slot_is_managed_mutability_pointer (value))
3386 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));
3388 if ((ctx->prefix_set & PREFIX_TAIL) && stack_slot_is_managed_pointer (value)) {
3389 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));
3390 return;
3394 if (sig->hasthis) {
3395 MonoType *type = &method->klass->byval_arg;
3396 ILStackDesc copy;
3398 if (mono_method_is_constructor (method) && !method->klass->valuetype) {
3399 if (!mono_method_is_constructor (ctx->method))
3400 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot call a constructor outside one at 0x%04x", ctx->ip_offset));
3401 if (method->klass != ctx->method->klass->parent && method->klass != ctx->method->klass)
3402 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));
3404 ctx->super_ctor_called = TRUE;
3405 value = stack_pop_safe (ctx);
3406 if ((value->stype & THIS_POINTER_MASK) != THIS_POINTER_MASK)
3407 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid 'this ptr' argument for constructor at 0x%04x", ctx->ip_offset));
3408 } else {
3409 value = stack_pop (ctx);
3412 copy_stack_value (&copy, value);
3413 //TODO we should extract this to a 'drop_byref_argument' and use everywhere
3414 //Other parts of the code suffer from the same issue of
3415 copy.type = mono_type_get_type_byval (copy.type);
3416 copy.stype &= ~POINTER_MASK;
3418 if (virt_check_this && !stack_slot_is_this_pointer (value) && !(method->klass->valuetype || stack_slot_is_boxed_value (value)))
3419 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));
3421 if (constrained && virtual) {
3422 if (!stack_slot_is_managed_pointer (value))
3423 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Object is not a managed pointer for a constrained call at 0x%04x", ctx->ip_offset));
3424 if (!mono_metadata_type_equal_full (mono_type_get_type_byval (value->type), ctx->constrained_type, TRUE))
3425 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Object not compatible with constrained type at 0x%04x", ctx->ip_offset));
3426 copy.stype |= BOXED_MASK;
3427 } else {
3428 if (stack_slot_is_managed_pointer (value) && !mono_class_from_mono_type (value->type)->valuetype)
3429 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));
3431 if (!virtual && mono_class_from_mono_type (value->type)->valuetype && !method->klass->valuetype && !stack_slot_is_boxed_value (value))
3432 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot call a valuetype baseclass at 0x%04x", ctx->ip_offset));
3434 if (virtual && mono_class_from_mono_type (value->type)->valuetype && !stack_slot_is_boxed_value (value))
3435 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use a valuetype with callvirt at 0x%04x", ctx->ip_offset));
3437 if (method->klass->valuetype && (stack_slot_is_boxed_value (value) || !stack_slot_is_managed_pointer (value)))
3438 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));
3440 if (!verify_stack_type_compatibility (ctx, type, &copy))
3441 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Incompatible this argument on stack with method signature at 0x%04x", ctx->ip_offset));
3443 if (!IS_SKIP_VISIBILITY (ctx) && !mono_method_can_access_method_full (ctx->method, method, mono_class_from_mono_type (value->type))) {
3444 char *name = mono_method_full_name (method, TRUE);
3445 CODE_NOT_VERIFIABLE2 (ctx, g_strdup_printf ("Method %s is not accessible at 0x%04x", name, ctx->ip_offset), MONO_EXCEPTION_METHOD_ACCESS);
3446 g_free (name);
3449 } else if (!IS_SKIP_VISIBILITY (ctx) && !mono_method_can_access_method_full (ctx->method, method, NULL)) {
3450 char *name = mono_method_full_name (method, TRUE);
3451 CODE_NOT_VERIFIABLE2 (ctx, g_strdup_printf ("Method %s is not accessible at 0x%04x", name, ctx->ip_offset), MONO_EXCEPTION_METHOD_ACCESS);
3452 g_free (name);
3455 if (sig->ret->type != MONO_TYPE_VOID) {
3456 if (check_overflow (ctx)) {
3457 value = stack_push (ctx);
3458 set_stack_value (ctx, value, sig->ret, FALSE);
3459 if ((ctx->prefix_set & PREFIX_READONLY) && method->klass->rank && !strcmp (method->name, "Address")) {
3460 ctx->prefix_set &= ~PREFIX_READONLY;
3461 value->stype |= CMMP_MASK;
3466 if ((ctx->prefix_set & PREFIX_TAIL)) {
3467 if (!mono_delegate_ret_equal (mono_method_signature (ctx->method)->ret, sig->ret))
3468 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Tail call with incompatible return type at 0x%04x", ctx->ip_offset));
3469 if (ctx->header->code [ctx->ip_offset + 5] != CEE_RET)
3470 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Tail call not followed by ret at 0x%04x", ctx->ip_offset));
3475 static void
3476 do_push_static_field (VerifyContext *ctx, int token, gboolean take_addr)
3478 MonoClassField *field;
3479 MonoClass *klass;
3480 if (!check_overflow (ctx))
3481 return;
3482 if (!take_addr)
3483 CLEAR_PREFIX (ctx, PREFIX_VOLATILE);
3485 if (!(field = verifier_load_field (ctx, token, &klass, take_addr ? "ldsflda" : "ldsfld")))
3486 return;
3488 if (!(field->type->attrs & FIELD_ATTRIBUTE_STATIC)) {
3489 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Cannot load non static field at 0x%04x", ctx->ip_offset));
3490 return;
3492 /*taking the address of initonly field only works from the static constructor */
3493 if (take_addr && (field->type->attrs & FIELD_ATTRIBUTE_INIT_ONLY) &&
3494 !(field->parent == ctx->method->klass && (ctx->method->flags & (METHOD_ATTRIBUTE_SPECIAL_NAME | METHOD_ATTRIBUTE_STATIC)) && !strcmp (".cctor", ctx->method->name)))
3495 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot take the address of a init-only field at 0x%04x", ctx->ip_offset));
3497 if (!IS_SKIP_VISIBILITY (ctx) && !mono_method_can_access_field_full (ctx->method, field, NULL))
3498 CODE_NOT_VERIFIABLE2 (ctx, g_strdup_printf ("Type at stack is not accessible at 0x%04x", ctx->ip_offset), MONO_EXCEPTION_FIELD_ACCESS);
3500 set_stack_value (ctx, stack_push (ctx), field->type, take_addr);
3503 static void
3504 do_store_static_field (VerifyContext *ctx, int token) {
3505 MonoClassField *field;
3506 MonoClass *klass;
3507 ILStackDesc *value;
3508 CLEAR_PREFIX (ctx, PREFIX_VOLATILE);
3510 if (!check_underflow (ctx, 1))
3511 return;
3513 value = stack_pop (ctx);
3515 if (!(field = verifier_load_field (ctx, token, &klass, "stsfld")))
3516 return;
3518 if (!(field->type->attrs & FIELD_ATTRIBUTE_STATIC)) {
3519 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Cannot store non static field at 0x%04x", ctx->ip_offset));
3520 return;
3523 if (field->type->type == MONO_TYPE_TYPEDBYREF) {
3524 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Typedbyref field is an unverfiable type in store static field at 0x%04x", ctx->ip_offset));
3525 return;
3528 if (!IS_SKIP_VISIBILITY (ctx) && !mono_method_can_access_field_full (ctx->method, field, NULL))
3529 CODE_NOT_VERIFIABLE2 (ctx, g_strdup_printf ("Type at stack is not accessible at 0x%04x", ctx->ip_offset), MONO_EXCEPTION_FIELD_ACCESS);
3531 if (!verify_stack_type_compatibility (ctx, field->type, value))
3532 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));
3535 static gboolean
3536 check_is_valid_type_for_field_ops (VerifyContext *ctx, int token, ILStackDesc *obj, MonoClassField **ret_field, const char *opcode)
3538 MonoClassField *field;
3539 MonoClass *klass;
3540 gboolean is_pointer;
3542 /*must be a reference type, a managed pointer, an unamanaged pointer, or a valuetype*/
3543 if (!(field = verifier_load_field (ctx, token, &klass, opcode)))
3544 return FALSE;
3546 *ret_field = field;
3547 //the value on stack is going to be used as a pointer
3548 is_pointer = stack_slot_get_type (obj) == TYPE_PTR || (stack_slot_get_type (obj) == TYPE_NATIVE_INT && !get_stack_type (&field->parent->byval_arg));
3550 if (field->type->type == MONO_TYPE_TYPEDBYREF) {
3551 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Typedbyref field is an unverfiable type at 0x%04x", ctx->ip_offset));
3552 return FALSE;
3554 g_assert (obj->type);
3556 /*The value on the stack must be a subclass of the defining type of the field*/
3557 /* we need to check if we can load the field from the stack value*/
3558 if (is_pointer) {
3559 if (stack_slot_get_underlying_type (obj) == TYPE_NATIVE_INT)
3560 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Native int is not a verifiable type to reference a field at 0x%04x", ctx->ip_offset));
3562 if (!IS_SKIP_VISIBILITY (ctx) && !mono_method_can_access_field_full (ctx->method, field, NULL))
3563 CODE_NOT_VERIFIABLE2 (ctx, g_strdup_printf ("Type at stack is not accessible at 0x%04x", ctx->ip_offset), MONO_EXCEPTION_FIELD_ACCESS);
3564 } else {
3565 if (!field->parent->valuetype && stack_slot_is_managed_pointer (obj))
3566 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));
3568 /*a value type can be loaded from a value or a managed pointer, but not a boxed object*/
3569 if (field->parent->valuetype && stack_slot_is_boxed_value (obj))
3570 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));
3572 if (!stack_slot_is_null_literal (obj) && !verify_stack_type_compatibility_full (ctx, &field->parent->byval_arg, obj, TRUE, FALSE))
3573 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Type at stack is not compatible to reference the field at 0x%04x", ctx->ip_offset));
3575 if (!IS_SKIP_VISIBILITY (ctx) && !mono_method_can_access_field_full (ctx->method, field, mono_class_from_mono_type (obj->type)))
3576 CODE_NOT_VERIFIABLE2 (ctx, g_strdup_printf ("Type at stack is not accessible at 0x%04x", ctx->ip_offset), MONO_EXCEPTION_FIELD_ACCESS);
3579 check_unmanaged_pointer (ctx, obj);
3580 return TRUE;
3583 static void
3584 do_push_field (VerifyContext *ctx, int token, gboolean take_addr)
3586 ILStackDesc *obj;
3587 MonoClassField *field;
3589 if (!take_addr)
3590 CLEAR_PREFIX (ctx, PREFIX_UNALIGNED | PREFIX_VOLATILE);
3592 if (!check_underflow (ctx, 1))
3593 return;
3594 obj = stack_pop_safe (ctx);
3596 if (!check_is_valid_type_for_field_ops (ctx, token, obj, &field, take_addr ? "ldflda" : "ldfld"))
3597 return;
3599 if (take_addr && field->parent->valuetype && !stack_slot_is_managed_pointer (obj))
3600 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot take the address of a temporary value-type at 0x%04x", ctx->ip_offset));
3602 if (take_addr && (field->type->attrs & FIELD_ATTRIBUTE_INIT_ONLY) &&
3603 !(field->parent == ctx->method->klass && mono_method_is_constructor (ctx->method)))
3604 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot take the address of a init-only field at 0x%04x", ctx->ip_offset));
3606 set_stack_value (ctx, stack_push (ctx), field->type, take_addr);
3609 static void
3610 do_store_field (VerifyContext *ctx, int token)
3612 ILStackDesc *value, *obj;
3613 MonoClassField *field;
3614 CLEAR_PREFIX (ctx, PREFIX_UNALIGNED | PREFIX_VOLATILE);
3616 if (!check_underflow (ctx, 2))
3617 return;
3619 value = stack_pop (ctx);
3620 obj = stack_pop_safe (ctx);
3622 if (!check_is_valid_type_for_field_ops (ctx, token, obj, &field, "stfld"))
3623 return;
3625 if (!verify_stack_type_compatibility (ctx, field->type, value))
3626 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Incompatible type %s in field store at 0x%04x", stack_slot_get_name (value), ctx->ip_offset));
3629 /*TODO proper handle for Nullable<T>*/
3630 static void
3631 do_box_value (VerifyContext *ctx, int klass_token)
3633 ILStackDesc *value;
3634 MonoType *type = get_boxable_mono_type (ctx, klass_token, "box");
3635 MonoClass *klass;
3637 if (!type)
3638 return;
3640 if (!check_underflow (ctx, 1))
3641 return;
3643 value = stack_pop (ctx);
3644 /*box is a nop for reference types*/
3646 if (stack_slot_get_underlying_type (value) == TYPE_COMPLEX && MONO_TYPE_IS_REFERENCE (value->type) && MONO_TYPE_IS_REFERENCE (type)) {
3647 stack_push_stack_val (ctx, value)->stype |= BOXED_MASK;
3648 return;
3652 if (!verify_stack_type_compatibility (ctx, type, value))
3653 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid type at stack for boxing operation at 0x%04x", ctx->ip_offset));
3655 klass = mono_class_from_mono_type (type);
3656 if (mono_class_is_nullable (klass))
3657 type = &mono_class_get_nullable_param (klass)->byval_arg;
3658 stack_push_val (ctx, TYPE_COMPLEX | BOXED_MASK, type);
3661 static void
3662 do_unbox_value (VerifyContext *ctx, int klass_token)
3664 ILStackDesc *value;
3665 MonoType *type = get_boxable_mono_type (ctx, klass_token, "unbox");
3667 if (!type)
3668 return;
3670 if (!check_underflow (ctx, 1))
3671 return;
3673 if (!mono_class_from_mono_type (type)->valuetype)
3674 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid reference type for unbox at 0x%04x", ctx->ip_offset));
3676 value = stack_pop (ctx);
3678 /*Value should be: a boxed valuetype or a reference type*/
3679 if (!(stack_slot_get_type (value) == TYPE_COMPLEX &&
3680 (stack_slot_is_boxed_value (value) || !mono_class_from_mono_type (value->type)->valuetype)))
3681 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));
3683 set_stack_value (ctx, value = stack_push (ctx), mono_type_get_type_byref (type), FALSE);
3684 value->stype |= CMMP_MASK;
3687 static void
3688 do_unbox_any (VerifyContext *ctx, int klass_token)
3690 ILStackDesc *value;
3691 MonoType *type = get_boxable_mono_type (ctx, klass_token, "unbox.any");
3693 if (!type)
3694 return;
3696 if (!check_underflow (ctx, 1))
3697 return;
3699 value = stack_pop (ctx);
3701 /*Value should be: a boxed valuetype or a reference type*/
3702 if (!(stack_slot_get_type (value) == TYPE_COMPLEX &&
3703 (stack_slot_is_boxed_value (value) || !mono_class_from_mono_type (value->type)->valuetype)))
3704 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));
3706 set_stack_value (ctx, stack_push (ctx), type, FALSE);
3709 static void
3710 do_unary_math_op (VerifyContext *ctx, int op)
3712 ILStackDesc *value;
3713 if (!check_underflow (ctx, 1))
3714 return;
3715 value = stack_pop (ctx);
3716 switch (stack_slot_get_type (value)) {
3717 case TYPE_I4:
3718 case TYPE_I8:
3719 case TYPE_NATIVE_INT:
3720 break;
3721 case TYPE_R8:
3722 if (op == CEE_NEG)
3723 break;
3724 case TYPE_COMPLEX: /*only enums are ok*/
3725 if (mono_type_is_enum_type (value->type))
3726 break;
3727 default:
3728 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid type at stack for unary not at 0x%04x", ctx->ip_offset));
3730 stack_push_stack_val (ctx, value);
3733 static void
3734 do_conversion (VerifyContext *ctx, int kind)
3736 ILStackDesc *value;
3737 if (!check_underflow (ctx, 1))
3738 return;
3739 value = stack_pop (ctx);
3741 switch (stack_slot_get_type (value)) {
3742 case TYPE_I4:
3743 case TYPE_I8:
3744 case TYPE_NATIVE_INT:
3745 case TYPE_R8:
3746 break;
3747 default:
3748 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));
3751 switch (kind) {
3752 case TYPE_I4:
3753 stack_push_val (ctx, TYPE_I4, &mono_defaults.int32_class->byval_arg);
3754 break;
3755 case TYPE_I8:
3756 stack_push_val (ctx,TYPE_I8, &mono_defaults.int64_class->byval_arg);
3757 break;
3758 case TYPE_R8:
3759 stack_push_val (ctx, TYPE_R8, &mono_defaults.double_class->byval_arg);
3760 break;
3761 case TYPE_NATIVE_INT:
3762 stack_push_val (ctx, TYPE_NATIVE_INT, &mono_defaults.int_class->byval_arg);
3763 break;
3764 default:
3765 g_error ("unknown type %02x in conversion", kind);
3770 static void
3771 do_load_token (VerifyContext *ctx, int token)
3773 gpointer handle;
3774 MonoClass *handle_class;
3775 if (!check_overflow (ctx))
3776 return;
3777 handle = mono_ldtoken (ctx->image, token, &handle_class, ctx->generic_context);
3778 if (!handle) {
3779 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid token 0x%x for ldtoken at 0x%04x", token, ctx->ip_offset));
3780 return;
3782 if (handle_class == mono_defaults.typehandle_class) {
3783 mono_type_is_valid_in_context (ctx, (MonoType*)handle);
3784 } else if (handle_class == mono_defaults.methodhandle_class) {
3785 mono_method_is_valid_in_context (ctx, (MonoMethod*)handle);
3786 } else if (handle_class == mono_defaults.fieldhandle_class) {
3787 mono_type_is_valid_in_context (ctx, &((MonoClassField*)handle)->parent->byval_arg);
3788 } else {
3789 ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid ldtoken type %x at 0x%04x", token, ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE);
3791 stack_push_val (ctx, TYPE_COMPLEX, mono_class_get_type (handle_class));
3794 static void
3795 do_ldobj_value (VerifyContext *ctx, int token)
3797 ILStackDesc *value;
3798 MonoType *type = get_boxable_mono_type (ctx, token, "ldobj");
3799 CLEAR_PREFIX (ctx, PREFIX_UNALIGNED | PREFIX_VOLATILE);
3801 if (!type)
3802 return;
3804 if (!check_underflow (ctx, 1))
3805 return;
3807 value = stack_pop (ctx);
3808 if (!stack_slot_is_managed_pointer (value)
3809 && stack_slot_get_type (value) != TYPE_NATIVE_INT
3810 && !(stack_slot_get_type (value) == TYPE_PTR && value->type->type != MONO_TYPE_FNPTR)) {
3811 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid argument %s to ldobj at 0x%04x", stack_slot_get_name (value), ctx->ip_offset));
3812 return;
3815 if (stack_slot_get_type (value) == TYPE_NATIVE_INT)
3816 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Using native pointer to ldobj at 0x%04x", ctx->ip_offset));
3818 /*We have a byval on the stack, but the comparison must be strict. */
3819 if (!verify_type_compatibility_full (ctx, type, mono_type_get_type_byval (value->type), TRUE))
3820 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid type at stack for ldojb operation at 0x%04x", ctx->ip_offset));
3822 set_stack_value (ctx, stack_push (ctx), type, FALSE);
3825 static void
3826 do_stobj (VerifyContext *ctx, int token)
3828 ILStackDesc *dest, *src;
3829 MonoType *type = get_boxable_mono_type (ctx, token, "stobj");
3830 CLEAR_PREFIX (ctx, PREFIX_UNALIGNED | PREFIX_VOLATILE);
3832 if (!type)
3833 return;
3835 if (!check_underflow (ctx, 2))
3836 return;
3838 src = stack_pop (ctx);
3839 dest = stack_pop (ctx);
3841 if (stack_slot_is_managed_mutability_pointer (dest))
3842 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use a readonly pointer with stobj at 0x%04x", ctx->ip_offset));
3844 if (!stack_slot_is_managed_pointer (dest))
3845 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid destination of stobj operation at 0x%04x", ctx->ip_offset));
3847 if (stack_slot_is_boxed_value (src) && !MONO_TYPE_IS_REFERENCE (src->type) && !MONO_TYPE_IS_REFERENCE (type))
3848 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));
3850 if (!verify_stack_type_compatibility (ctx, type, src))
3851 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Token and source types of stobj don't match at 0x%04x", ctx->ip_offset));
3853 if (!verify_type_compatibility (ctx, mono_type_get_type_byval (dest->type), type))
3854 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Destination and token types of stobj don't match at 0x%04x", ctx->ip_offset));
3857 static void
3858 do_cpobj (VerifyContext *ctx, int token)
3860 ILStackDesc *dest, *src;
3861 MonoType *type = get_boxable_mono_type (ctx, token, "cpobj");
3862 if (!type)
3863 return;
3865 if (!check_underflow (ctx, 2))
3866 return;
3868 src = stack_pop (ctx);
3869 dest = stack_pop (ctx);
3871 if (!stack_slot_is_managed_pointer (src))
3872 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid source of cpobj operation at 0x%04x", ctx->ip_offset));
3874 if (!stack_slot_is_managed_pointer (dest))
3875 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid destination of cpobj operation at 0x%04x", ctx->ip_offset));
3877 if (stack_slot_is_managed_mutability_pointer (dest))
3878 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use a readonly pointer with cpobj at 0x%04x", ctx->ip_offset));
3880 if (!verify_type_compatibility (ctx, type, mono_type_get_type_byval (src->type)))
3881 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Token and source types of cpobj don't match at 0x%04x", ctx->ip_offset));
3883 if (!verify_type_compatibility (ctx, mono_type_get_type_byval (dest->type), type))
3884 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Destination and token types of cpobj don't match at 0x%04x", ctx->ip_offset));
3887 static void
3888 do_initobj (VerifyContext *ctx, int token)
3890 ILStackDesc *obj;
3891 MonoType *stack, *type = get_boxable_mono_type (ctx, token, "initobj");
3892 if (!type)
3893 return;
3895 if (!check_underflow (ctx, 1))
3896 return;
3898 obj = stack_pop (ctx);
3900 if (!stack_slot_is_managed_pointer (obj))
3901 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid object address for initobj at 0x%04x", ctx->ip_offset));
3903 if (stack_slot_is_managed_mutability_pointer (obj))
3904 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use a readonly pointer with initobj at 0x%04x", ctx->ip_offset));
3906 stack = mono_type_get_type_byval (obj->type);
3907 if (MONO_TYPE_IS_REFERENCE (stack)) {
3908 if (!verify_type_compatibility (ctx, stack, type))
3909 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Type token of initobj not compatible with value on stack at 0x%04x", ctx->ip_offset));
3910 else if (IS_STRICT_MODE (ctx) && !mono_metadata_type_equal (type, stack))
3911 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Type token of initobj not compatible with value on stack at 0x%04x", ctx->ip_offset));
3912 } else if (!verify_type_compatibility (ctx, stack, type)) {
3913 char *expected_name = mono_type_full_name (type);
3914 char *stack_name = mono_type_full_name (stack);
3916 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));
3917 g_free (expected_name);
3918 g_free (stack_name);
3922 static void
3923 do_newobj (VerifyContext *ctx, int token)
3925 ILStackDesc *value;
3926 int i;
3927 MonoMethodSignature *sig;
3928 MonoMethod *method;
3929 gboolean is_delegate = FALSE;
3931 if (!(method = verifier_load_method (ctx, token, "newobj")))
3932 return;
3934 if (!mono_method_is_constructor (method)) {
3935 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Method from token 0x%08x not a constructor at 0x%04x", token, ctx->ip_offset));
3936 return;
3939 if (method->klass->flags & (TYPE_ATTRIBUTE_ABSTRACT | TYPE_ATTRIBUTE_INTERFACE))
3940 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Trying to instantiate an abstract or interface type at 0x%04x", ctx->ip_offset));
3942 if (!mono_method_can_access_method_full (ctx->method, method, NULL)) {
3943 char *from = mono_method_full_name (ctx->method, TRUE);
3944 char *to = mono_method_full_name (method, TRUE);
3945 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);
3946 g_free (from);
3947 g_free (to);
3950 //FIXME use mono_method_get_signature_full
3951 sig = mono_method_signature (method);
3952 if (!check_underflow (ctx, sig->param_count))
3953 return;
3955 is_delegate = method->klass->parent == mono_defaults.multicastdelegate_class;
3957 if (is_delegate) {
3958 ILStackDesc *funptr;
3959 //first arg is object, second arg is fun ptr
3960 if (sig->param_count != 2) {
3961 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid delegate constructor at 0x%04x", ctx->ip_offset));
3962 return;
3964 funptr = stack_pop (ctx);
3965 value = stack_pop (ctx);
3966 verify_delegate_compatibility (ctx, method->klass, value, funptr);
3967 } else {
3968 for (i = sig->param_count - 1; i >= 0; --i) {
3969 VERIFIER_DEBUG ( printf ("verifying constructor argument %d\n", i); );
3970 value = stack_pop (ctx);
3971 if (!verify_stack_type_compatibility (ctx, sig->params [i], value)) {
3972 char *stack_name = stack_slot_full_name (value);
3973 char *sig_name = mono_type_full_name (sig->params [i]);
3974 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));
3975 g_free (stack_name);
3976 g_free (sig_name);
3979 if (stack_slot_is_managed_mutability_pointer (value))
3980 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use a readonly pointer as argument of newobj at 0x%04x", ctx->ip_offset));
3984 if (check_overflow (ctx))
3985 set_stack_value (ctx, stack_push (ctx), &method->klass->byval_arg, FALSE);
3988 static void
3989 do_cast (VerifyContext *ctx, int token, const char *opcode) {
3990 ILStackDesc *value;
3991 MonoType *type;
3992 gboolean is_boxed;
3993 gboolean do_box;
3995 if (!check_underflow (ctx, 1))
3996 return;
3998 if (!(type = verifier_load_type (ctx, token, opcode)))
3999 return;
4001 if (type->byref) {
4002 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid %s type at 0x%04x", opcode, ctx->ip_offset));
4003 return;
4006 value = stack_pop (ctx);
4007 is_boxed = stack_slot_is_boxed_value (value);
4009 if (stack_slot_is_managed_pointer (value))
4010 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid value for %s at 0x%04x", opcode, ctx->ip_offset));
4011 else if (!MONO_TYPE_IS_REFERENCE (value->type) && !is_boxed) {
4012 char *name = stack_slot_full_name (value);
4013 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));
4014 g_free (name);
4017 switch (value->type->type) {
4018 case MONO_TYPE_FNPTR:
4019 case MONO_TYPE_PTR:
4020 case MONO_TYPE_TYPEDBYREF:
4021 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid value for %s at 0x%04x", opcode, ctx->ip_offset));
4024 do_box = is_boxed || mono_type_is_generic_argument(type) || mono_class_from_mono_type (type)->valuetype;
4025 stack_push_val (ctx, TYPE_COMPLEX | (do_box ? BOXED_MASK : 0), type);
4028 static MonoType *
4029 mono_type_from_opcode (int opcode) {
4030 switch (opcode) {
4031 case CEE_LDIND_I1:
4032 case CEE_LDIND_U1:
4033 case CEE_STIND_I1:
4034 case CEE_LDELEM_I1:
4035 case CEE_LDELEM_U1:
4036 case CEE_STELEM_I1:
4037 return &mono_defaults.sbyte_class->byval_arg;
4039 case CEE_LDIND_I2:
4040 case CEE_LDIND_U2:
4041 case CEE_STIND_I2:
4042 case CEE_LDELEM_I2:
4043 case CEE_LDELEM_U2:
4044 case CEE_STELEM_I2:
4045 return &mono_defaults.int16_class->byval_arg;
4047 case CEE_LDIND_I4:
4048 case CEE_LDIND_U4:
4049 case CEE_STIND_I4:
4050 case CEE_LDELEM_I4:
4051 case CEE_LDELEM_U4:
4052 case CEE_STELEM_I4:
4053 return &mono_defaults.int32_class->byval_arg;
4055 case CEE_LDIND_I8:
4056 case CEE_STIND_I8:
4057 case CEE_LDELEM_I8:
4058 case CEE_STELEM_I8:
4059 return &mono_defaults.int64_class->byval_arg;
4061 case CEE_LDIND_R4:
4062 case CEE_STIND_R4:
4063 case CEE_LDELEM_R4:
4064 case CEE_STELEM_R4:
4065 return &mono_defaults.single_class->byval_arg;
4067 case CEE_LDIND_R8:
4068 case CEE_STIND_R8:
4069 case CEE_LDELEM_R8:
4070 case CEE_STELEM_R8:
4071 return &mono_defaults.double_class->byval_arg;
4073 case CEE_LDIND_I:
4074 case CEE_STIND_I:
4075 case CEE_LDELEM_I:
4076 case CEE_STELEM_I:
4077 return &mono_defaults.int_class->byval_arg;
4079 case CEE_LDIND_REF:
4080 case CEE_STIND_REF:
4081 case CEE_LDELEM_REF:
4082 case CEE_STELEM_REF:
4083 return &mono_defaults.object_class->byval_arg;
4085 default:
4086 g_error ("unknown opcode %02x in mono_type_from_opcode ", opcode);
4087 return NULL;
4091 static void
4092 do_load_indirect (VerifyContext *ctx, int opcode)
4094 ILStackDesc *value;
4095 CLEAR_PREFIX (ctx, PREFIX_UNALIGNED | PREFIX_VOLATILE);
4097 if (!check_underflow (ctx, 1))
4098 return;
4100 value = stack_pop (ctx);
4101 if (!stack_slot_is_managed_pointer (value)) {
4102 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Load indirect not using a manager pointer at 0x%04x", ctx->ip_offset));
4103 set_stack_value (ctx, stack_push (ctx), mono_type_from_opcode (opcode), FALSE);
4104 return;
4107 if (opcode == CEE_LDIND_REF) {
4108 if (stack_slot_get_underlying_type (value) != TYPE_COMPLEX || mono_class_from_mono_type (value->type)->valuetype)
4109 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid type at stack for ldind_ref expected object byref operation at 0x%04x", ctx->ip_offset));
4110 set_stack_value (ctx, stack_push (ctx), mono_type_get_type_byval (value->type), FALSE);
4111 } else {
4112 if (!verify_type_compatibility_full (ctx, mono_type_from_opcode (opcode), mono_type_get_type_byval (value->type), TRUE))
4113 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid type at stack for ldind 0x%x operation at 0x%04x", opcode, ctx->ip_offset));
4114 set_stack_value (ctx, stack_push (ctx), mono_type_from_opcode (opcode), FALSE);
4118 static void
4119 do_store_indirect (VerifyContext *ctx, int opcode)
4121 ILStackDesc *addr, *val;
4122 CLEAR_PREFIX (ctx, PREFIX_UNALIGNED | PREFIX_VOLATILE);
4124 if (!check_underflow (ctx, 2))
4125 return;
4127 val = stack_pop (ctx);
4128 addr = stack_pop (ctx);
4130 check_unmanaged_pointer (ctx, addr);
4132 if (!stack_slot_is_managed_pointer (addr) && stack_slot_get_type (addr) != TYPE_PTR) {
4133 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid non-pointer argument to stind at 0x%04x", ctx->ip_offset));
4134 return;
4137 if (stack_slot_is_managed_mutability_pointer (addr)) {
4138 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use a readonly pointer with stind at 0x%04x", ctx->ip_offset));
4139 return;
4142 if (!verify_type_compatibility_full (ctx, mono_type_from_opcode (opcode), mono_type_get_type_byval (addr->type), TRUE))
4143 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid addr type at stack for stind 0x%x operation at 0x%04x", opcode, ctx->ip_offset));
4145 if (!verify_stack_type_compatibility (ctx, mono_type_from_opcode (opcode), val))
4146 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid value type at stack for stind 0x%x operation at 0x%04x", opcode, ctx->ip_offset));
4149 static void
4150 do_newarr (VerifyContext *ctx, int token)
4152 ILStackDesc *value;
4153 MonoType *type = get_boxable_mono_type (ctx, token, "newarr");
4155 if (!type)
4156 return;
4158 if (!check_underflow (ctx, 1))
4159 return;
4161 value = stack_pop (ctx);
4162 if (stack_slot_get_type (value) != TYPE_I4 && stack_slot_get_type (value) != TYPE_NATIVE_INT)
4163 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));
4165 set_stack_value (ctx, stack_push (ctx), mono_class_get_type (mono_array_class_get (mono_class_from_mono_type (type), 1)), FALSE);
4168 /*FIXME handle arrays that are not 0-indexed*/
4169 static void
4170 do_ldlen (VerifyContext *ctx)
4172 ILStackDesc *value;
4174 if (!check_underflow (ctx, 1))
4175 return;
4177 value = stack_pop (ctx);
4179 if (stack_slot_get_type (value) != TYPE_COMPLEX || value->type->type != MONO_TYPE_SZARRAY)
4180 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type for ldlen at 0x%04x", ctx->ip_offset));
4182 stack_push_val (ctx, TYPE_NATIVE_INT, &mono_defaults.int_class->byval_arg);
4185 /*FIXME handle arrays that are not 0-indexed*/
4186 /*FIXME handle readonly prefix and CMMP*/
4187 static void
4188 do_ldelema (VerifyContext *ctx, int klass_token)
4190 ILStackDesc *index, *array, *res;
4191 MonoType *type = get_boxable_mono_type (ctx, klass_token, "ldelema");
4192 gboolean valid;
4194 if (!type)
4195 return;
4197 if (!check_underflow (ctx, 2))
4198 return;
4200 index = stack_pop (ctx);
4201 array = stack_pop (ctx);
4203 if (stack_slot_get_type (index) != TYPE_I4 && stack_slot_get_type (index) != TYPE_NATIVE_INT)
4204 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));
4206 if (!stack_slot_is_null_literal (array)) {
4207 if (stack_slot_get_type (array) != TYPE_COMPLEX || array->type->type != MONO_TYPE_SZARRAY)
4208 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type(%s) for ldelema at 0x%04x", stack_slot_get_name (array), ctx->ip_offset));
4209 else {
4210 if (get_stack_type (type) == TYPE_I4 || get_stack_type (type) == TYPE_NATIVE_INT) {
4211 valid = verify_type_compatibility_full (ctx, type, &array->type->data.klass->byval_arg, TRUE);
4212 } else {
4213 valid = mono_metadata_type_equal (type, &array->type->data.klass->byval_arg);
4215 if (!valid)
4216 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type on stack for ldelema at 0x%04x", ctx->ip_offset));
4220 res = stack_push (ctx);
4221 set_stack_value (ctx, res, type, TRUE);
4222 if (ctx->prefix_set & PREFIX_READONLY) {
4223 ctx->prefix_set &= ~PREFIX_READONLY;
4224 res->stype |= CMMP_MASK;
4229 * FIXME handle arrays that are not 0-indexed
4230 * FIXME handle readonly prefix and CMMP
4232 static void
4233 do_ldelem (VerifyContext *ctx, int opcode, int token)
4235 #define IS_ONE_OF2(T, A, B) (T == A || T == B)
4236 ILStackDesc *index, *array;
4237 MonoType *type;
4238 if (!check_underflow (ctx, 2))
4239 return;
4241 if (opcode == CEE_LDELEM) {
4242 if (!(type = verifier_load_type (ctx, token, "ldelem.any"))) {
4243 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Type (0x%08x) not found at 0x%04x", token, ctx->ip_offset));
4244 return;
4246 } else {
4247 type = mono_type_from_opcode (opcode);
4250 index = stack_pop (ctx);
4251 array = stack_pop (ctx);
4253 if (stack_slot_get_type (index) != TYPE_I4 && stack_slot_get_type (index) != TYPE_NATIVE_INT)
4254 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));
4256 if (!stack_slot_is_null_literal (array)) {
4257 if (stack_slot_get_type (array) != TYPE_COMPLEX || array->type->type != MONO_TYPE_SZARRAY)
4258 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));
4259 else {
4260 if (opcode == CEE_LDELEM_REF) {
4261 if (array->type->data.klass->valuetype)
4262 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type is not a reference type for ldelem.ref 0x%04x", ctx->ip_offset));
4263 type = &array->type->data.klass->byval_arg;
4264 } else {
4265 MonoType *candidate = &array->type->data.klass->byval_arg;
4266 if (IS_STRICT_MODE (ctx)) {
4267 MonoType *underlying_type = mono_type_get_underlying_type_any (type);
4268 MonoType *underlying_candidate = mono_type_get_underlying_type_any (candidate);
4269 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)) ||
4270 (IS_ONE_OF2 (underlying_candidate->type, MONO_TYPE_I4, MONO_TYPE_U4) && IS_ONE_OF2 (underlying_type->type, MONO_TYPE_I, MONO_TYPE_U)))
4271 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type on stack for ldelem.X at 0x%04x", ctx->ip_offset));
4273 if (!verify_type_compatibility_full (ctx, type, candidate, TRUE))
4274 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type on stack for ldelem.X at 0x%04x", ctx->ip_offset));
4279 set_stack_value (ctx, stack_push (ctx), type, FALSE);
4280 #undef IS_ONE_OF2
4284 * FIXME handle arrays that are not 0-indexed
4286 static void
4287 do_stelem (VerifyContext *ctx, int opcode, int token)
4289 ILStackDesc *index, *array, *value;
4290 MonoType *type;
4291 if (!check_underflow (ctx, 3))
4292 return;
4294 if (opcode == CEE_STELEM) {
4295 if (!(type = verifier_load_type (ctx, token, "stelem.any"))) {
4296 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Type (0x%08x) not found at 0x%04x", token, ctx->ip_offset));
4297 return;
4299 } else {
4300 type = mono_type_from_opcode (opcode);
4303 value = stack_pop (ctx);
4304 index = stack_pop (ctx);
4305 array = stack_pop (ctx);
4307 if (stack_slot_get_type (index) != TYPE_I4 && stack_slot_get_type (index) != TYPE_NATIVE_INT)
4308 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));
4310 if (!stack_slot_is_null_literal (array)) {
4311 if (stack_slot_get_type (array) != TYPE_COMPLEX || array->type->type != MONO_TYPE_SZARRAY) {
4312 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));
4313 } else {
4314 if (opcode == CEE_STELEM_REF) {
4315 if (array->type->data.klass->valuetype)
4316 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type is not a reference type for stelem.ref 0x%04x", ctx->ip_offset));
4317 } else if (!verify_type_compatibility_full (ctx, &array->type->data.klass->byval_arg, type, TRUE)) {
4318 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type on stack for stdelem.X at 0x%04x", ctx->ip_offset));
4322 if (opcode == CEE_STELEM_REF) {
4323 if (!stack_slot_is_boxed_value (value) && mono_class_from_mono_type (value->type)->valuetype)
4324 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid value is not a reference type for stelem.ref 0x%04x", ctx->ip_offset));
4325 } else if (opcode != CEE_STELEM_REF) {
4326 if (!verify_stack_type_compatibility (ctx, type, value))
4327 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid value on stack for stdelem.X at 0x%04x", ctx->ip_offset));
4329 if (stack_slot_is_boxed_value (value) && !MONO_TYPE_IS_REFERENCE (value->type) && !MONO_TYPE_IS_REFERENCE (type))
4330 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));
4335 static void
4336 do_throw (VerifyContext *ctx)
4338 ILStackDesc *exception;
4339 if (!check_underflow (ctx, 1))
4340 return;
4341 exception = stack_pop (ctx);
4343 if (!stack_slot_is_null_literal (exception) && !(stack_slot_get_type (exception) == TYPE_COMPLEX && !mono_class_from_mono_type (exception->type)->valuetype))
4344 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid type on stack for throw, expected reference type at 0x%04x", ctx->ip_offset));
4346 if (mono_type_is_generic_argument (exception->type) && !stack_slot_is_boxed_value (exception)) {
4347 char *name = mono_type_full_name (exception->type);
4348 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));
4349 g_free (name);
4351 /*The stack is left empty after a throw*/
4352 ctx->eval.size = 0;
4356 static void
4357 do_endfilter (VerifyContext *ctx)
4359 MonoExceptionClause *clause;
4361 if (IS_STRICT_MODE (ctx)) {
4362 if (ctx->eval.size != 1)
4363 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Stack size must have one item for endfilter at 0x%04x", ctx->ip_offset));
4365 if (ctx->eval.size >= 1 && stack_slot_get_type (stack_pop (ctx)) != TYPE_I4)
4366 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Stack item type is not an int32 for endfilter at 0x%04x", ctx->ip_offset));
4369 if ((clause = is_correct_endfilter (ctx, ctx->ip_offset))) {
4370 if (IS_STRICT_MODE (ctx)) {
4371 if (ctx->ip_offset != clause->handler_offset - 2)
4372 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("endfilter is not the last instruction of the filter clause at 0x%04x", ctx->ip_offset));
4373 } else {
4374 if ((ctx->ip_offset != clause->handler_offset - 2) && !MONO_OFFSET_IN_HANDLER (clause, ctx->ip_offset))
4375 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("endfilter is not the last instruction of the filter clause at 0x%04x", ctx->ip_offset));
4377 } else {
4378 if (IS_STRICT_MODE (ctx) && !is_unverifiable_endfilter (ctx, ctx->ip_offset))
4379 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("endfilter outside filter clause at 0x%04x", ctx->ip_offset));
4380 else
4381 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("endfilter outside filter clause at 0x%04x", ctx->ip_offset));
4384 ctx->eval.size = 0;
4387 static void
4388 do_leave (VerifyContext *ctx, int delta)
4390 int target = ((gint32)ctx->ip_offset) + delta;
4391 if (target >= ctx->code_size || target < 0)
4392 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Branch target out of code at 0x%04x", ctx->ip_offset));
4394 if (!is_correct_leave (ctx->header, ctx->ip_offset, target))
4395 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Leave not allowed in finally block at 0x%04x", ctx->ip_offset));
4396 ctx->eval.size = 0;
4400 * do_static_branch:
4402 * Verify br and br.s opcodes.
4404 static void
4405 do_static_branch (VerifyContext *ctx, int delta)
4407 int target = ctx->ip_offset + delta;
4408 if (target < 0 || target >= ctx->code_size) {
4409 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("branch target out of code at 0x%04x", ctx->ip_offset));
4410 return;
4413 switch (is_valid_branch_instruction (ctx->header, ctx->ip_offset, target)) {
4414 case 1:
4415 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Branch target escapes out of exception block at 0x%04x", ctx->ip_offset));
4416 break;
4417 case 2:
4418 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Branch target escapes out of exception block at 0x%04x", ctx->ip_offset));
4419 break;
4422 ctx->target = target;
4425 static void
4426 do_switch (VerifyContext *ctx, int count, const unsigned char *data)
4428 int i, base = ctx->ip_offset + 5 + count * 4;
4429 ILStackDesc *value;
4431 if (!check_underflow (ctx, 1))
4432 return;
4434 value = stack_pop (ctx);
4436 if (stack_slot_get_type (value) != TYPE_I4 && stack_slot_get_type (value) != TYPE_NATIVE_INT)
4437 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid argument to switch at 0x%04x", ctx->ip_offset));
4439 for (i = 0; i < count; ++i) {
4440 int target = base + read32 (data + i * 4);
4442 if (target < 0 || target >= ctx->code_size) {
4443 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Switch target %x out of code at 0x%04x", i, ctx->ip_offset));
4444 return;
4447 switch (is_valid_branch_instruction (ctx->header, ctx->ip_offset, target)) {
4448 case 1:
4449 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Switch target %x escapes out of exception block at 0x%04x", i, ctx->ip_offset));
4450 break;
4451 case 2:
4452 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Switch target %x escapes out of exception block at 0x%04x", i, ctx->ip_offset));
4453 return;
4455 merge_stacks (ctx, &ctx->eval, &ctx->code [target], FALSE, TRUE);
4459 static void
4460 do_load_function_ptr (VerifyContext *ctx, guint32 token, gboolean virtual)
4462 ILStackDesc *top;
4463 MonoMethod *method;
4465 if (virtual && !check_underflow (ctx, 1))
4466 return;
4468 if (!virtual && !check_overflow (ctx))
4469 return;
4471 if (!IS_METHOD_DEF_OR_REF_OR_SPEC (token) || !token_bounds_check (ctx->image, token)) {
4472 ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid token %x for ldftn at 0x%04x", token, ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE);
4473 return;
4476 if (!(method = verifier_load_method (ctx, token, virtual ? "ldvirtfrn" : "ldftn")))
4477 return;
4479 if (mono_method_is_constructor (method))
4480 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use ldftn with a constructor at 0x%04x", ctx->ip_offset));
4482 if (virtual) {
4483 ILStackDesc *top = stack_pop (ctx);
4485 if (stack_slot_get_type (top) != TYPE_COMPLEX || top->type->type == MONO_TYPE_VALUETYPE)
4486 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid argument to ldvirtftn at 0x%04x", ctx->ip_offset));
4488 if (method->flags & METHOD_ATTRIBUTE_STATIC)
4489 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use ldvirtftn with a constructor at 0x%04x", ctx->ip_offset));
4491 if (!verify_stack_type_compatibility (ctx, &method->klass->byval_arg, top))
4492 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Unexpected object for ldvirtftn at 0x%04x", ctx->ip_offset));
4495 if (!mono_method_can_access_method_full (ctx->method, method, NULL))
4496 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);
4498 top = stack_push_val(ctx, TYPE_PTR, mono_type_create_fnptr_from_mono_method (ctx, method));
4499 top->method = method;
4502 static void
4503 do_sizeof (VerifyContext *ctx, int token)
4505 MonoType *type;
4507 if (!IS_TYPE_DEF_OR_REF_OR_SPEC (token) || !token_bounds_check (ctx->image, token)) {
4508 ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid type token %x at 0x%04x", token, ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE);
4509 return;
4512 if (!(type = verifier_load_type (ctx, token, "sizeof")))
4513 return;
4515 if (type->byref && type->type != MONO_TYPE_TYPEDBYREF) {
4516 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid use of byref type at 0x%04x", ctx->ip_offset));
4517 return;
4520 if (type->type == MONO_TYPE_VOID) {
4521 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid use of void type at 0x%04x", ctx->ip_offset));
4522 return;
4525 if (check_overflow (ctx))
4526 set_stack_value (ctx, stack_push (ctx), &mono_defaults.uint32_class->byval_arg, FALSE);
4529 /* Stack top can be of any type, the runtime doesn't care and treat everything as an int. */
4530 static void
4531 do_localloc (VerifyContext *ctx)
4533 ILStackDesc *top;
4535 if (ctx->eval.size != 1) {
4536 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Stack must have only size item in localloc at 0x%04x", ctx->ip_offset));
4537 return;
4540 if (in_any_exception_block (ctx->header, ctx->ip_offset)) {
4541 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Stack must have only size item in localloc at 0x%04x", ctx->ip_offset));
4542 return;
4545 /*TODO verify top type*/
4546 top = stack_pop (ctx);
4548 set_stack_value (ctx, stack_push (ctx), &mono_defaults.int_class->byval_arg, FALSE);
4549 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Instruction localloc in never verifiable at 0x%04x", ctx->ip_offset));
4552 static void
4553 do_ldstr (VerifyContext *ctx, guint32 token)
4555 if (mono_metadata_token_code (token) != MONO_TOKEN_STRING) {
4556 ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid string token %x at 0x%04x", token, ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE);
4557 return;
4560 if (!ctx->image->dynamic && mono_metadata_token_index (token) >= ctx->image->heap_us.size) {
4561 ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid string index %x at 0x%04x", token, ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE);
4562 return;
4565 if (check_overflow (ctx))
4566 stack_push_val (ctx, TYPE_COMPLEX, &mono_defaults.string_class->byval_arg);
4569 static void
4570 do_refanyval (VerifyContext *ctx, int token)
4572 ILStackDesc *top;
4573 MonoType *type;
4574 if (!check_underflow (ctx, 1))
4575 return;
4577 if (!(type = get_boxable_mono_type (ctx, token, "refanyval")))
4578 return;
4580 top = stack_pop (ctx);
4582 if (top->stype != TYPE_PTR || top->type->type != MONO_TYPE_TYPEDBYREF)
4583 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));
4585 set_stack_value (ctx, stack_push (ctx), type, TRUE);
4588 static void
4589 do_refanytype (VerifyContext *ctx)
4591 ILStackDesc *top;
4593 if (!check_underflow (ctx, 1))
4594 return;
4596 top = stack_pop (ctx);
4598 if (top->stype != TYPE_PTR || top->type->type != MONO_TYPE_TYPEDBYREF)
4599 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));
4601 set_stack_value (ctx, stack_push (ctx), &mono_defaults.typehandle_class->byval_arg, FALSE);
4605 static void
4606 do_mkrefany (VerifyContext *ctx, int token)
4608 ILStackDesc *top;
4609 MonoType *type;
4610 if (!check_underflow (ctx, 1))
4611 return;
4613 if (!(type = get_boxable_mono_type (ctx, token, "refanyval")))
4614 return;
4616 top = stack_pop (ctx);
4618 if (stack_slot_is_managed_mutability_pointer (top))
4619 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use a readonly pointer with mkrefany at 0x%04x", ctx->ip_offset));
4621 if (!stack_slot_is_managed_pointer (top)) {
4622 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));
4623 }else {
4624 MonoType *stack_type = mono_type_get_type_byval (top->type);
4625 if (MONO_TYPE_IS_REFERENCE (type) && !mono_metadata_type_equal (type, stack_type))
4626 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Type not compatible for mkrefany at 0x%04x", ctx->ip_offset));
4628 if (!MONO_TYPE_IS_REFERENCE (type) && !verify_type_compatibility_full (ctx, type, stack_type, TRUE))
4629 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Type not compatible for mkrefany at 0x%04x", ctx->ip_offset));
4632 set_stack_value (ctx, stack_push (ctx), &mono_defaults.typed_reference_class->byval_arg, FALSE);
4635 static void
4636 do_ckfinite (VerifyContext *ctx)
4638 ILStackDesc *top;
4639 if (!check_underflow (ctx, 1))
4640 return;
4642 top = stack_pop (ctx);
4644 if (stack_slot_get_underlying_type (top) != TYPE_R8)
4645 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));
4646 stack_push_stack_val (ctx, top);
4649 * merge_stacks:
4650 * Merge the stacks and perform compat checks. The merge check if types of @from are mergeable with type of @to
4652 * @from holds new values for a given control path
4653 * @to holds the current values of a given control path
4655 * TODO we can eliminate the from argument as all callers pass &ctx->eval
4657 static void
4658 merge_stacks (VerifyContext *ctx, ILCodeDesc *from, ILCodeDesc *to, gboolean start, gboolean external)
4660 int i, j, k;
4661 stack_init (ctx, to);
4663 if (start) {
4664 if (to->flags == IL_CODE_FLAG_NOT_PROCESSED)
4665 from->size = 0;
4666 else
4667 stack_copy (&ctx->eval, to);
4668 goto end_verify;
4669 } else if (!(to->flags & IL_CODE_STACK_MERGED)) {
4670 stack_copy (to, &ctx->eval);
4671 goto end_verify;
4673 VERIFIER_DEBUG ( printf ("performing stack merge %d x %d\n", from->size, to->size); );
4675 if (from->size != to->size) {
4676 VERIFIER_DEBUG ( printf ("different stack sizes %d x %d at 0x%04x\n", from->size, to->size, ctx->ip_offset); );
4677 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));
4678 goto end_verify;
4681 //FIXME we need to preserve CMMP attributes
4682 //FIXME we must take null literals into consideration.
4683 for (i = 0; i < from->size; ++i) {
4684 ILStackDesc *new_slot = from->stack + i;
4685 ILStackDesc *old_slot = to->stack + i;
4686 MonoType *new_type = mono_type_from_stack_slot (new_slot);
4687 MonoType *old_type = mono_type_from_stack_slot (old_slot);
4688 MonoClass *old_class = mono_class_from_mono_type (old_type);
4689 MonoClass *new_class = mono_class_from_mono_type (new_type);
4690 MonoClass *match_class = NULL;
4692 // S := T then U = S (new value is compatible with current value, keep current)
4693 if (verify_stack_type_compatibility (ctx, old_type, new_slot)) {
4694 copy_stack_value (new_slot, old_slot);
4695 continue;
4698 // T := S then U = T (old value is compatible with current value, use new)
4699 if (verify_stack_type_compatibility (ctx, new_type, old_slot)) {
4700 copy_stack_value (old_slot, new_slot);
4701 continue;
4704 if (mono_type_is_generic_argument (old_type) || mono_type_is_generic_argument (new_type)) {
4705 char *old_name = stack_slot_full_name (old_slot);
4706 char *new_name = stack_slot_full_name (new_slot);
4707 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));
4708 g_free (old_name);
4709 g_free (new_name);
4710 goto end_verify;
4713 //both are reference types, use closest common super type
4714 if (!mono_class_from_mono_type (old_type)->valuetype
4715 && !mono_class_from_mono_type (new_type)->valuetype
4716 && !stack_slot_is_managed_pointer (old_slot)
4717 && !stack_slot_is_managed_pointer (new_slot)) {
4719 for (j = MIN (old_class->idepth, new_class->idepth) - 1; j > 0; --j) {
4720 if (mono_metadata_type_equal (&old_class->supertypes [j]->byval_arg, &new_class->supertypes [j]->byval_arg)) {
4721 match_class = old_class->supertypes [j];
4722 goto match_found;
4726 mono_class_setup_interfaces (old_class);
4727 for (j = 0; j < old_class->interface_count; ++j) {
4728 for (k = 0; k < new_class->interface_count; ++k) {
4729 if (mono_metadata_type_equal (&old_class->interfaces [j]->byval_arg, &new_class->interfaces [k]->byval_arg)) {
4730 match_class = old_class->interfaces [j];
4731 goto match_found;
4736 //No decent super type found, use object
4737 match_class = mono_defaults.object_class;
4738 goto match_found;
4739 } 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)) {
4740 match_class = mono_defaults.object_class;
4741 goto match_found;
4745 char *old_name = stack_slot_full_name (old_slot);
4746 char *new_name = stack_slot_full_name (new_slot);
4747 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));
4748 g_free (old_name);
4749 g_free (new_name);
4751 set_stack_value (ctx, old_slot, &new_class->byval_arg, stack_slot_is_managed_pointer (old_slot));
4752 goto end_verify;
4754 match_found:
4755 g_assert (match_class);
4756 set_stack_value (ctx, old_slot, &match_class->byval_arg, stack_slot_is_managed_pointer (old_slot));
4757 set_stack_value (ctx, new_slot, &match_class->byval_arg, stack_slot_is_managed_pointer (old_slot));
4758 continue;
4761 end_verify:
4762 if (external)
4763 to->flags |= IL_CODE_FLAG_WAS_TARGET;
4764 to->flags |= IL_CODE_STACK_MERGED;
4767 #define HANDLER_START(clause) ((clause)->flags == MONO_EXCEPTION_CLAUSE_FILTER ? (clause)->data.filter_offset : clause->handler_offset)
4768 #define IS_CATCH_OR_FILTER(clause) ((clause)->flags == MONO_EXCEPTION_CLAUSE_FILTER || (clause)->flags == MONO_EXCEPTION_CLAUSE_NONE)
4771 * is_clause_in_range :
4773 * Returns TRUE if either the protected block or the handler of @clause is in the @start - @end range.
4775 static gboolean
4776 is_clause_in_range (MonoExceptionClause *clause, guint32 start, guint32 end)
4778 if (clause->try_offset >= start && clause->try_offset < end)
4779 return TRUE;
4780 if (HANDLER_START (clause) >= start && HANDLER_START (clause) < end)
4781 return TRUE;
4782 return FALSE;
4786 * is_clause_inside_range :
4788 * Returns TRUE if @clause lies completely inside the @start - @end range.
4790 static gboolean
4791 is_clause_inside_range (MonoExceptionClause *clause, guint32 start, guint32 end)
4793 if (clause->try_offset < start || (clause->try_offset + clause->try_len) > end)
4794 return FALSE;
4795 if (HANDLER_START (clause) < start || (clause->handler_offset + clause->handler_len) > end)
4796 return FALSE;
4797 return TRUE;
4801 * is_clause_nested :
4803 * Returns TRUE if @nested is nested in @clause.
4805 static gboolean
4806 is_clause_nested (MonoExceptionClause *clause, MonoExceptionClause *nested)
4808 if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER && is_clause_inside_range (nested, clause->data.filter_offset, clause->handler_offset))
4809 return TRUE;
4810 return is_clause_inside_range (nested, clause->try_offset, clause->try_offset + clause->try_len) ||
4811 is_clause_inside_range (nested, clause->handler_offset, clause->handler_offset + clause->handler_len);
4814 /* Test the relationship between 2 exception clauses. Follow P.1 12.4.2.7 of ECMA
4815 * the each pair of exception must have the following properties:
4816 * - one is fully nested on another (the outer must not be a filter clause) (the nested one must come earlier)
4817 * - completely disjoin (none of the 3 regions of each entry overlap with the other 3)
4818 * - mutual protection (protected block is EXACT the same, handlers are disjoin and all handler are catch or all handler are filter)
4820 static void
4821 verify_clause_relationship (VerifyContext *ctx, MonoExceptionClause *clause, MonoExceptionClause *to_test)
4823 /*clause is nested*/
4824 if (to_test->flags == MONO_EXCEPTION_CLAUSE_FILTER && is_clause_inside_range (clause, to_test->data.filter_offset, to_test->handler_offset)) {
4825 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Exception clause inside filter"));
4826 return;
4829 /*wrong nesting order.*/
4830 if (is_clause_nested (clause, to_test)) {
4831 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Nested exception clause appears after enclosing clause"));
4832 return;
4835 /*mutual protection*/
4836 if (clause->try_offset == to_test->try_offset && clause->try_len == to_test->try_len) {
4837 /*handlers are not disjoint*/
4838 if (is_clause_in_range (to_test, HANDLER_START (clause), clause->handler_offset + clause->handler_len)) {
4839 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Exception handlers overlap"));
4840 return;
4842 /* handlers are not catch or filter */
4843 if (!IS_CATCH_OR_FILTER (clause) || !IS_CATCH_OR_FILTER (to_test)) {
4844 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Exception clauses with shared protected block are neither catch or filter"));
4845 return;
4847 /*OK*/
4848 return;
4851 /*not completelly disjoint*/
4852 if ((is_clause_in_range (to_test, clause->try_offset, clause->try_offset + clause->try_len) ||
4853 is_clause_in_range (to_test, HANDLER_START (clause), clause->handler_offset + clause->handler_len)) && !is_clause_nested (to_test, clause))
4854 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Exception clauses overlap"));
4857 #define code_bounds_check(size) \
4858 if (ip + size > end) {\
4859 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Code overrun starting with 0x%x at 0x%04x", *ip, ctx.ip_offset)); \
4860 break; \
4864 * FIXME: need to distinguish between valid and verifiable.
4865 * Need to keep track of types on the stack.
4866 * Verify types for opcodes.
4868 GSList*
4869 mono_method_verify (MonoMethod *method, int level)
4871 MonoError error;
4872 const unsigned char *ip;
4873 const unsigned char *end;
4874 int i, n, need_merge = 0, start = 0;
4875 guint token, ip_offset = 0, prefix = 0;
4876 MonoGenericContext *generic_context = NULL;
4877 MonoImage *image;
4878 VerifyContext ctx;
4879 GSList *tmp;
4880 VERIFIER_DEBUG ( printf ("Verify IL for method %s %s %s\n", method->klass->name_space, method->klass->name, method->name); );
4882 if (method->iflags & (METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL | METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
4883 (method->flags & (METHOD_ATTRIBUTE_PINVOKE_IMPL | METHOD_ATTRIBUTE_ABSTRACT))) {
4884 return NULL;
4887 memset (&ctx, 0, sizeof (VerifyContext));
4889 //FIXME use mono_method_get_signature_full
4890 ctx.signature = mono_method_signature (method);
4891 if (!ctx.signature) {
4892 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Could not decode method signature"));
4893 return ctx.list;
4895 ctx.header = mono_method_get_header (method);
4896 if (!ctx.header) {
4897 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Could not decode method header"));
4898 return ctx.list;
4900 ctx.method = method;
4901 ip = ctx.header->code;
4902 end = ip + ctx.header->code_size;
4903 ctx.image = image = method->klass->image;
4906 ctx.max_args = ctx.signature->param_count + ctx.signature->hasthis;
4907 ctx.max_stack = ctx.header->max_stack;
4908 ctx.verifiable = ctx.valid = 1;
4909 ctx.level = level;
4911 ctx.code = g_new (ILCodeDesc, ctx.header->code_size);
4912 ctx.code_size = ctx.header->code_size;
4914 memset(ctx.code, 0, sizeof (ILCodeDesc) * ctx.header->code_size);
4917 ctx.num_locals = ctx.header->num_locals;
4918 ctx.locals = g_memdup (ctx.header->locals, sizeof (MonoType*) * ctx.header->num_locals);
4920 if (ctx.num_locals > 0 && !ctx.header->init_locals)
4921 CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Method with locals variable but without init locals set"));
4923 ctx.params = g_new (MonoType*, ctx.max_args);
4924 if (ctx.signature->hasthis)
4925 ctx.params [0] = method->klass->valuetype ? &method->klass->this_arg : &method->klass->byval_arg;
4926 memcpy (ctx.params + ctx.signature->hasthis, ctx.signature->params, sizeof (MonoType *) * ctx.signature->param_count);
4928 if (ctx.signature->is_inflated)
4929 ctx.generic_context = generic_context = mono_method_get_context (method);
4931 if (!generic_context && (method->klass->generic_container || method->is_generic)) {
4932 if (method->is_generic)
4933 ctx.generic_context = generic_context = &(mono_method_get_generic_container (method)->context);
4934 else
4935 ctx.generic_context = generic_context = &method->klass->generic_container->context;
4938 for (i = 0; i < ctx.num_locals; ++i) {
4939 MonoType *uninflated = ctx.locals [i];
4940 ctx.locals [i] = mono_class_inflate_generic_type_checked (ctx.locals [i], ctx.generic_context, &error);
4941 if (!mono_error_ok (&error)) {
4942 char *name = mono_type_full_name (ctx.locals [i] ? ctx.locals [i] : uninflated);
4943 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid local %d of type %s", i, name));
4944 g_free (name);
4945 mono_error_cleanup (&error);
4946 /* we must not free (in cleanup) what was not yet allocated (but only copied) */
4947 ctx.num_locals = i;
4948 ctx.max_args = 0;
4949 goto cleanup;
4952 for (i = 0; i < ctx.max_args; ++i) {
4953 MonoType *uninflated = ctx.params [i];
4954 ctx.params [i] = mono_class_inflate_generic_type_checked (ctx.params [i], ctx.generic_context, &error);
4955 if (!mono_error_ok (&error)) {
4956 char *name = mono_type_full_name (ctx.params [i] ? ctx.params [i] : uninflated);
4957 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid parameter %d of type %s", i, name));
4958 g_free (name);
4959 mono_error_cleanup (&error);
4960 /* we must not free (in cleanup) what was not yet allocated (but only copied) */
4961 ctx.max_args = i;
4962 goto cleanup;
4965 stack_init (&ctx, &ctx.eval);
4967 for (i = 0; i < ctx.num_locals; ++i) {
4968 if (!mono_type_is_valid_in_context (&ctx, ctx.locals [i]))
4969 break;
4972 for (i = 0; i < ctx.max_args; ++i) {
4973 if (!mono_type_is_valid_in_context (&ctx, ctx.params [i]))
4974 break;
4977 if (!ctx.valid)
4978 goto cleanup;
4980 for (i = 0; i < ctx.header->num_clauses && ctx.valid; ++i) {
4981 MonoExceptionClause *clause = ctx.header->clauses + i;
4982 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); );
4984 if (clause->try_offset > ctx.code_size || clause->try_offset + clause->try_len > ctx.code_size)
4985 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("try clause out of bounds at 0x%04x", clause->try_offset));
4987 if (clause->try_len <= 0)
4988 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("try clause len <= 0 at 0x%04x", clause->try_offset));
4990 if (clause->handler_offset > ctx.code_size || clause->handler_offset + clause->handler_len > ctx.code_size)
4991 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("handler clause out of bounds at 0x%04x", clause->try_offset));
4993 if (clause->handler_len <= 0)
4994 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("try clause len <= 0 at 0x%04x", clause->try_offset));
4996 if (clause->try_offset < clause->handler_offset && clause->try_offset + clause->try_len > HANDLER_START (clause))
4997 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("try block (at 0x%04x) includes handler block (at 0x%04x)", clause->try_offset, clause->handler_offset));
4999 for (n = i + 1; n < ctx.header->num_clauses && ctx.valid; ++n)
5000 verify_clause_relationship (&ctx, clause, ctx.header->clauses + n);
5002 if (!ctx.valid)
5003 break;
5005 ctx.code [clause->try_offset].flags |= IL_CODE_FLAG_WAS_TARGET;
5006 if (clause->try_offset + clause->try_len < ctx.code_size)
5007 ctx.code [clause->try_offset + clause->try_len].flags |= IL_CODE_FLAG_WAS_TARGET;
5008 if (clause->handler_offset + clause->handler_len < ctx.code_size)
5009 ctx.code [clause->handler_offset + clause->handler_len].flags |= IL_CODE_FLAG_WAS_TARGET;
5011 if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE) {
5012 init_stack_with_value_at_exception_boundary (&ctx, ctx.code + clause->handler_offset, clause->data.catch_class);
5014 else if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
5015 init_stack_with_value_at_exception_boundary (&ctx, ctx.code + clause->data.filter_offset, mono_defaults.exception_class);
5016 init_stack_with_value_at_exception_boundary (&ctx, ctx.code + clause->handler_offset, mono_defaults.exception_class);
5020 while (ip < end && ctx.valid) {
5021 ctx.ip_offset = ip_offset = ip - ctx.header->code;
5023 /*We need to check against fallthrou in and out of protected blocks.
5024 * For fallout we check the once a protected block ends, if the start flag is not set.
5025 * Likewise for fallthru in, we check if ip is the start of a protected block and start is not set
5026 * TODO convert these checks to be done using flags and not this loop
5028 for (i = 0; i < ctx.header->num_clauses && ctx.valid; ++i) {
5029 MonoExceptionClause *clause = ctx.header->clauses + i;
5031 if ((clause->try_offset + clause->try_len == ip_offset) && start == 0) {
5032 CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("fallthru off try block at 0x%04x", ip_offset));
5033 start = 1;
5036 if ((clause->handler_offset + clause->handler_len == ip_offset) && start == 0) {
5037 if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER)
5038 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("fallout of handler block at 0x%04x", ip_offset));
5039 else
5040 CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("fallout of handler block at 0x%04x", ip_offset));
5041 start = 1;
5044 if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER && clause->handler_offset == ip_offset && start == 0) {
5045 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("fallout of filter block at 0x%04x", ip_offset));
5046 start = 1;
5049 if (clause->handler_offset == ip_offset && start == 0) {
5050 CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("fallthru handler block at 0x%04x", ip_offset));
5051 start = 1;
5054 if (clause->try_offset == ip_offset && ctx.eval.size > 0 && start == 0) {
5055 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Try to enter try block with a non-empty stack at 0x%04x", ip_offset));
5056 start = 1;
5060 if (!ctx.valid)
5061 break;
5063 if (need_merge) {
5064 VERIFIER_DEBUG ( printf ("extra merge needed! 0x%04x \n", ctx.target); );
5065 merge_stacks (&ctx, &ctx.eval, &ctx.code [ctx.target], FALSE, TRUE);
5066 need_merge = 0;
5068 merge_stacks (&ctx, &ctx.eval, &ctx.code[ip_offset], start, FALSE);
5069 start = 0;
5071 /*TODO we can fast detect a forward branch or exception block targeting code after prefix, we should fail fast*/
5072 #ifdef MONO_VERIFIER_DEBUG
5074 char *discode;
5075 discode = mono_disasm_code_one (NULL, method, ip, NULL);
5076 discode [strlen (discode) - 1] = 0; /* no \n */
5077 g_print ("[%d] %-29s (%d)\n", ip_offset, discode, ctx.eval.size);
5078 g_free (discode);
5080 dump_stack_state (&ctx.code [ip_offset]);
5081 dump_stack_state (&ctx.eval);
5082 #endif
5084 switch (*ip) {
5085 case CEE_NOP:
5086 case CEE_BREAK:
5087 ++ip;
5088 break;
5090 case CEE_LDARG_0:
5091 case CEE_LDARG_1:
5092 case CEE_LDARG_2:
5093 case CEE_LDARG_3:
5094 push_arg (&ctx, *ip - CEE_LDARG_0, FALSE);
5095 ++ip;
5096 break;
5098 case CEE_LDARG_S:
5099 case CEE_LDARGA_S:
5100 code_bounds_check (2);
5101 push_arg (&ctx, ip [1], *ip == CEE_LDARGA_S);
5102 ip += 2;
5103 break;
5105 case CEE_ADD_OVF_UN:
5106 do_binop (&ctx, *ip, add_ovf_un_table);
5107 ++ip;
5108 break;
5110 case CEE_SUB_OVF_UN:
5111 do_binop (&ctx, *ip, sub_ovf_un_table);
5112 ++ip;
5113 break;
5115 case CEE_ADD_OVF:
5116 case CEE_SUB_OVF:
5117 case CEE_MUL_OVF:
5118 case CEE_MUL_OVF_UN:
5119 do_binop (&ctx, *ip, bin_ovf_table);
5120 ++ip;
5121 break;
5123 case CEE_ADD:
5124 do_binop (&ctx, *ip, add_table);
5125 ++ip;
5126 break;
5128 case CEE_SUB:
5129 do_binop (&ctx, *ip, sub_table);
5130 ++ip;
5131 break;
5133 case CEE_MUL:
5134 case CEE_DIV:
5135 case CEE_REM:
5136 do_binop (&ctx, *ip, bin_op_table);
5137 ++ip;
5138 break;
5140 case CEE_AND:
5141 case CEE_DIV_UN:
5142 case CEE_OR:
5143 case CEE_REM_UN:
5144 case CEE_XOR:
5145 do_binop (&ctx, *ip, int_bin_op_table);
5146 ++ip;
5147 break;
5149 case CEE_SHL:
5150 case CEE_SHR:
5151 case CEE_SHR_UN:
5152 do_binop (&ctx, *ip, shift_op_table);
5153 ++ip;
5154 break;
5156 case CEE_POP:
5157 if (!check_underflow (&ctx, 1))
5158 break;
5159 stack_pop_safe (&ctx);
5160 ++ip;
5161 break;
5163 case CEE_RET:
5164 do_ret (&ctx);
5165 ++ip;
5166 start = 1;
5167 break;
5169 case CEE_LDLOC_0:
5170 case CEE_LDLOC_1:
5171 case CEE_LDLOC_2:
5172 case CEE_LDLOC_3:
5173 /*TODO support definite assignment verification? */
5174 push_local (&ctx, *ip - CEE_LDLOC_0, FALSE);
5175 ++ip;
5176 break;
5178 case CEE_STLOC_0:
5179 case CEE_STLOC_1:
5180 case CEE_STLOC_2:
5181 case CEE_STLOC_3:
5182 store_local (&ctx, *ip - CEE_STLOC_0);
5183 ++ip;
5184 break;
5186 case CEE_STLOC_S:
5187 code_bounds_check (2);
5188 store_local (&ctx, ip [1]);
5189 ip += 2;
5190 break;
5192 case CEE_STARG_S:
5193 code_bounds_check (2);
5194 store_arg (&ctx, ip [1]);
5195 ip += 2;
5196 break;
5198 case CEE_LDC_I4_M1:
5199 case CEE_LDC_I4_0:
5200 case CEE_LDC_I4_1:
5201 case CEE_LDC_I4_2:
5202 case CEE_LDC_I4_3:
5203 case CEE_LDC_I4_4:
5204 case CEE_LDC_I4_5:
5205 case CEE_LDC_I4_6:
5206 case CEE_LDC_I4_7:
5207 case CEE_LDC_I4_8:
5208 if (check_overflow (&ctx))
5209 stack_push_val (&ctx, TYPE_I4, &mono_defaults.int32_class->byval_arg);
5210 ++ip;
5211 break;
5213 case CEE_LDC_I4_S:
5214 code_bounds_check (2);
5215 if (check_overflow (&ctx))
5216 stack_push_val (&ctx, TYPE_I4, &mono_defaults.int32_class->byval_arg);
5217 ip += 2;
5218 break;
5220 case CEE_LDC_I4:
5221 code_bounds_check (5);
5222 if (check_overflow (&ctx))
5223 stack_push_val (&ctx,TYPE_I4, &mono_defaults.int32_class->byval_arg);
5224 ip += 5;
5225 break;
5227 case CEE_LDC_I8:
5228 code_bounds_check (9);
5229 if (check_overflow (&ctx))
5230 stack_push_val (&ctx,TYPE_I8, &mono_defaults.int64_class->byval_arg);
5231 ip += 9;
5232 break;
5234 case CEE_LDC_R4:
5235 code_bounds_check (5);
5236 if (check_overflow (&ctx))
5237 stack_push_val (&ctx, TYPE_R8, &mono_defaults.double_class->byval_arg);
5238 ip += 5;
5239 break;
5241 case CEE_LDC_R8:
5242 code_bounds_check (9);
5243 if (check_overflow (&ctx))
5244 stack_push_val (&ctx, TYPE_R8, &mono_defaults.double_class->byval_arg);
5245 ip += 9;
5246 break;
5248 case CEE_LDNULL:
5249 if (check_overflow (&ctx))
5250 stack_push_val (&ctx, TYPE_COMPLEX | NULL_LITERAL_MASK, &mono_defaults.object_class->byval_arg);
5251 ++ip;
5252 break;
5254 case CEE_BEQ_S:
5255 case CEE_BNE_UN_S:
5256 code_bounds_check (2);
5257 do_branch_op (&ctx, (signed char)ip [1] + 2, cmp_br_eq_op);
5258 ip += 2;
5259 need_merge = 1;
5260 break;
5262 case CEE_BGE_S:
5263 case CEE_BGT_S:
5264 case CEE_BLE_S:
5265 case CEE_BLT_S:
5266 case CEE_BGE_UN_S:
5267 case CEE_BGT_UN_S:
5268 case CEE_BLE_UN_S:
5269 case CEE_BLT_UN_S:
5270 code_bounds_check (2);
5271 do_branch_op (&ctx, (signed char)ip [1] + 2, cmp_br_op);
5272 ip += 2;
5273 need_merge = 1;
5274 break;
5276 case CEE_BEQ:
5277 case CEE_BNE_UN:
5278 code_bounds_check (5);
5279 do_branch_op (&ctx, (gint32)read32 (ip + 1) + 5, cmp_br_eq_op);
5280 ip += 5;
5281 need_merge = 1;
5282 break;
5284 case CEE_BGE:
5285 case CEE_BGT:
5286 case CEE_BLE:
5287 case CEE_BLT:
5288 case CEE_BGE_UN:
5289 case CEE_BGT_UN:
5290 case CEE_BLE_UN:
5291 case CEE_BLT_UN:
5292 code_bounds_check (5);
5293 do_branch_op (&ctx, (gint32)read32 (ip + 1) + 5, cmp_br_op);
5294 ip += 5;
5295 need_merge = 1;
5296 break;
5298 case CEE_LDLOC_S:
5299 case CEE_LDLOCA_S:
5300 code_bounds_check (2);
5301 push_local (&ctx, ip[1], *ip == CEE_LDLOCA_S);
5302 ip += 2;
5303 break;
5305 /* FIXME: warn/error instead? */
5306 case CEE_UNUSED99:
5307 ++ip;
5308 break;
5310 case CEE_DUP: {
5311 ILStackDesc * top;
5312 if (!check_underflow (&ctx, 1))
5313 break;
5314 if (!check_overflow (&ctx))
5315 break;
5316 top = stack_pop_safe (&ctx);
5317 copy_stack_value (stack_push (&ctx), top);
5318 copy_stack_value (stack_push (&ctx), top);
5319 ++ip;
5320 break;
5323 case CEE_JMP:
5324 code_bounds_check (5);
5325 if (ctx.eval.size)
5326 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Eval stack must be empty in jmp at 0x%04x", ip_offset));
5327 token = read32 (ip + 1);
5328 if (in_any_block (ctx.header, ip_offset))
5329 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("jmp cannot escape exception blocks at 0x%04x", ip_offset));
5331 CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Intruction jmp is not verifiable at 0x%04x", ctx.ip_offset));
5333 * FIXME: check signature, retval, arguments etc.
5335 ip += 5;
5336 break;
5337 case CEE_CALL:
5338 case CEE_CALLVIRT:
5339 code_bounds_check (5);
5340 do_invoke_method (&ctx, read32 (ip + 1), *ip == CEE_CALLVIRT);
5341 ip += 5;
5342 break;
5344 case CEE_CALLI:
5345 code_bounds_check (5);
5346 token = read32 (ip + 1);
5348 * FIXME: check signature, retval, arguments etc.
5349 * FIXME: check requirements for tail call
5351 CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Intruction calli is not verifiable at 0x%04x", ctx.ip_offset));
5352 ip += 5;
5353 break;
5354 case CEE_BR_S:
5355 code_bounds_check (2);
5356 do_static_branch (&ctx, (signed char)ip [1] + 2);
5357 need_merge = 1;
5358 ip += 2;
5359 start = 1;
5360 break;
5362 case CEE_BRFALSE_S:
5363 case CEE_BRTRUE_S:
5364 code_bounds_check (2);
5365 do_boolean_branch_op (&ctx, (signed char)ip [1] + 2);
5366 ip += 2;
5367 need_merge = 1;
5368 break;
5370 case CEE_BR:
5371 code_bounds_check (5);
5372 do_static_branch (&ctx, (gint32)read32 (ip + 1) + 5);
5373 need_merge = 1;
5374 ip += 5;
5375 start = 1;
5376 break;
5378 case CEE_BRFALSE:
5379 case CEE_BRTRUE:
5380 code_bounds_check (5);
5381 do_boolean_branch_op (&ctx, (gint32)read32 (ip + 1) + 5);
5382 ip += 5;
5383 need_merge = 1;
5384 break;
5386 case CEE_SWITCH:
5387 code_bounds_check (5);
5388 n = read32 (ip + 1);
5389 code_bounds_check (5 + sizeof (guint32) * n);
5391 do_switch (&ctx, n, (ip + 5));
5392 start = 1;
5393 ip += 5 + sizeof (guint32) * n;
5394 break;
5396 case CEE_LDIND_I1:
5397 case CEE_LDIND_U1:
5398 case CEE_LDIND_I2:
5399 case CEE_LDIND_U2:
5400 case CEE_LDIND_I4:
5401 case CEE_LDIND_U4:
5402 case CEE_LDIND_I8:
5403 case CEE_LDIND_I:
5404 case CEE_LDIND_R4:
5405 case CEE_LDIND_R8:
5406 case CEE_LDIND_REF:
5407 do_load_indirect (&ctx, *ip);
5408 ++ip;
5409 break;
5411 case CEE_STIND_REF:
5412 case CEE_STIND_I1:
5413 case CEE_STIND_I2:
5414 case CEE_STIND_I4:
5415 case CEE_STIND_I8:
5416 case CEE_STIND_R4:
5417 case CEE_STIND_R8:
5418 case CEE_STIND_I:
5419 do_store_indirect (&ctx, *ip);
5420 ++ip;
5421 break;
5423 case CEE_NOT:
5424 case CEE_NEG:
5425 do_unary_math_op (&ctx, *ip);
5426 ++ip;
5427 break;
5429 case CEE_CONV_I1:
5430 case CEE_CONV_I2:
5431 case CEE_CONV_I4:
5432 case CEE_CONV_U1:
5433 case CEE_CONV_U2:
5434 case CEE_CONV_U4:
5435 do_conversion (&ctx, TYPE_I4);
5436 ++ip;
5437 break;
5439 case CEE_CONV_I8:
5440 case CEE_CONV_U8:
5441 do_conversion (&ctx, TYPE_I8);
5442 ++ip;
5443 break;
5445 case CEE_CONV_R4:
5446 case CEE_CONV_R8:
5447 case CEE_CONV_R_UN:
5448 do_conversion (&ctx, TYPE_R8);
5449 ++ip;
5450 break;
5452 case CEE_CONV_I:
5453 case CEE_CONV_U:
5454 do_conversion (&ctx, TYPE_NATIVE_INT);
5455 ++ip;
5456 break;
5458 case CEE_CPOBJ:
5459 code_bounds_check (5);
5460 do_cpobj (&ctx, read32 (ip + 1));
5461 ip += 5;
5462 break;
5464 case CEE_LDOBJ:
5465 code_bounds_check (5);
5466 do_ldobj_value (&ctx, read32 (ip + 1));
5467 ip += 5;
5468 break;
5470 case CEE_LDSTR:
5471 code_bounds_check (5);
5472 do_ldstr (&ctx, read32 (ip + 1));
5473 ip += 5;
5474 break;
5476 case CEE_NEWOBJ:
5477 code_bounds_check (5);
5478 do_newobj (&ctx, read32 (ip + 1));
5479 ip += 5;
5480 break;
5482 case CEE_CASTCLASS:
5483 case CEE_ISINST:
5484 code_bounds_check (5);
5485 do_cast (&ctx, read32 (ip + 1), *ip == CEE_CASTCLASS ? "castclass" : "isinst");
5486 ip += 5;
5487 break;
5489 case CEE_UNUSED58:
5490 case CEE_UNUSED1:
5491 ++ip; /* warn, error ? */
5492 break;
5494 case CEE_UNBOX:
5495 code_bounds_check (5);
5496 do_unbox_value (&ctx, read32 (ip + 1));
5497 ip += 5;
5498 break;
5500 case CEE_THROW:
5501 do_throw (&ctx);
5502 start = 1;
5503 ++ip;
5504 break;
5506 case CEE_LDFLD:
5507 case CEE_LDFLDA:
5508 code_bounds_check (5);
5509 do_push_field (&ctx, read32 (ip + 1), *ip == CEE_LDFLDA);
5510 ip += 5;
5511 break;
5513 case CEE_LDSFLD:
5514 case CEE_LDSFLDA:
5515 code_bounds_check (5);
5516 do_push_static_field (&ctx, read32 (ip + 1), *ip == CEE_LDSFLDA);
5517 ip += 5;
5518 break;
5520 case CEE_STFLD:
5521 code_bounds_check (5);
5522 do_store_field (&ctx, read32 (ip + 1));
5523 ip += 5;
5524 break;
5526 case CEE_STSFLD:
5527 code_bounds_check (5);
5528 do_store_static_field (&ctx, read32 (ip + 1));
5529 ip += 5;
5530 break;
5532 case CEE_STOBJ:
5533 code_bounds_check (5);
5534 do_stobj (&ctx, read32 (ip + 1));
5535 ip += 5;
5536 break;
5538 case CEE_CONV_OVF_I1_UN:
5539 case CEE_CONV_OVF_I2_UN:
5540 case CEE_CONV_OVF_I4_UN:
5541 case CEE_CONV_OVF_U1_UN:
5542 case CEE_CONV_OVF_U2_UN:
5543 case CEE_CONV_OVF_U4_UN:
5544 do_conversion (&ctx, TYPE_I4);
5545 ++ip;
5546 break;
5548 case CEE_CONV_OVF_I8_UN:
5549 case CEE_CONV_OVF_U8_UN:
5550 do_conversion (&ctx, TYPE_I8);
5551 ++ip;
5552 break;
5554 case CEE_CONV_OVF_I_UN:
5555 case CEE_CONV_OVF_U_UN:
5556 do_conversion (&ctx, TYPE_NATIVE_INT);
5557 ++ip;
5558 break;
5560 case CEE_BOX:
5561 code_bounds_check (5);
5562 do_box_value (&ctx, read32 (ip + 1));
5563 ip += 5;
5564 break;
5566 case CEE_NEWARR:
5567 code_bounds_check (5);
5568 do_newarr (&ctx, read32 (ip + 1));
5569 ip += 5;
5570 break;
5572 case CEE_LDLEN:
5573 do_ldlen (&ctx);
5574 ++ip;
5575 break;
5577 case CEE_LDELEMA:
5578 code_bounds_check (5);
5579 do_ldelema (&ctx, read32 (ip + 1));
5580 ip += 5;
5581 break;
5583 case CEE_LDELEM_I1:
5584 case CEE_LDELEM_U1:
5585 case CEE_LDELEM_I2:
5586 case CEE_LDELEM_U2:
5587 case CEE_LDELEM_I4:
5588 case CEE_LDELEM_U4:
5589 case CEE_LDELEM_I8:
5590 case CEE_LDELEM_I:
5591 case CEE_LDELEM_R4:
5592 case CEE_LDELEM_R8:
5593 case CEE_LDELEM_REF:
5594 do_ldelem (&ctx, *ip, 0);
5595 ++ip;
5596 break;
5598 case CEE_STELEM_I:
5599 case CEE_STELEM_I1:
5600 case CEE_STELEM_I2:
5601 case CEE_STELEM_I4:
5602 case CEE_STELEM_I8:
5603 case CEE_STELEM_R4:
5604 case CEE_STELEM_R8:
5605 case CEE_STELEM_REF:
5606 do_stelem (&ctx, *ip, 0);
5607 ++ip;
5608 break;
5610 case CEE_LDELEM:
5611 code_bounds_check (5);
5612 do_ldelem (&ctx, *ip, read32 (ip + 1));
5613 ip += 5;
5614 break;
5616 case CEE_STELEM:
5617 code_bounds_check (5);
5618 do_stelem (&ctx, *ip, read32 (ip + 1));
5619 ip += 5;
5620 break;
5622 case CEE_UNBOX_ANY:
5623 code_bounds_check (5);
5624 do_unbox_any (&ctx, read32 (ip + 1));
5625 ip += 5;
5626 break;
5628 case CEE_CONV_OVF_I1:
5629 case CEE_CONV_OVF_U1:
5630 case CEE_CONV_OVF_I2:
5631 case CEE_CONV_OVF_U2:
5632 case CEE_CONV_OVF_I4:
5633 case CEE_CONV_OVF_U4:
5634 do_conversion (&ctx, TYPE_I4);
5635 ++ip;
5636 break;
5638 case CEE_CONV_OVF_I8:
5639 case CEE_CONV_OVF_U8:
5640 do_conversion (&ctx, TYPE_I8);
5641 ++ip;
5642 break;
5644 case CEE_CONV_OVF_I:
5645 case CEE_CONV_OVF_U:
5646 do_conversion (&ctx, TYPE_NATIVE_INT);
5647 ++ip;
5648 break;
5650 case CEE_REFANYVAL:
5651 code_bounds_check (5);
5652 do_refanyval (&ctx, read32 (ip + 1));
5653 ip += 5;
5654 break;
5656 case CEE_CKFINITE:
5657 do_ckfinite (&ctx);
5658 ++ip;
5659 break;
5661 case CEE_MKREFANY:
5662 code_bounds_check (5);
5663 do_mkrefany (&ctx, read32 (ip + 1));
5664 ip += 5;
5665 break;
5667 case CEE_LDTOKEN:
5668 code_bounds_check (5);
5669 do_load_token (&ctx, read32 (ip + 1));
5670 ip += 5;
5671 break;
5673 case CEE_ENDFINALLY:
5674 if (!is_correct_endfinally (ctx.header, ip_offset))
5675 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("endfinally must be used inside a finally/fault handler at 0x%04x", ctx.ip_offset));
5676 ctx.eval.size = 0;
5677 start = 1;
5678 ++ip;
5679 break;
5681 case CEE_LEAVE:
5682 code_bounds_check (5);
5683 do_leave (&ctx, read32 (ip + 1) + 5);
5684 ip += 5;
5685 start = 1;
5686 break;
5688 case CEE_LEAVE_S:
5689 code_bounds_check (2);
5690 do_leave (&ctx, (signed char)ip [1] + 2);
5691 ip += 2;
5692 start = 1;
5693 break;
5695 case CEE_PREFIX1:
5696 code_bounds_check (2);
5697 ++ip;
5698 switch (*ip) {
5699 case CEE_STLOC:
5700 code_bounds_check (3);
5701 store_local (&ctx, read16 (ip + 1));
5702 ip += 3;
5703 break;
5705 case CEE_CEQ:
5706 do_cmp_op (&ctx, cmp_br_eq_op, *ip);
5707 ++ip;
5708 break;
5710 case CEE_CGT:
5711 case CEE_CGT_UN:
5712 case CEE_CLT:
5713 case CEE_CLT_UN:
5714 do_cmp_op (&ctx, cmp_br_op, *ip);
5715 ++ip;
5716 break;
5718 case CEE_STARG:
5719 code_bounds_check (3);
5720 store_arg (&ctx, read16 (ip + 1) );
5721 ip += 3;
5722 break;
5725 case CEE_ARGLIST:
5726 check_overflow (&ctx);
5727 if (ctx.signature->call_convention != MONO_CALL_VARARG)
5728 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Cannot use arglist on method without VARGARG calling convention at 0x%04x", ctx.ip_offset));
5729 set_stack_value (&ctx, stack_push (&ctx), &mono_defaults.argumenthandle_class->byval_arg, FALSE);
5730 ++ip;
5731 break;
5733 case CEE_LDFTN:
5734 code_bounds_check (5);
5735 do_load_function_ptr (&ctx, read32 (ip + 1), FALSE);
5736 ip += 5;
5737 break;
5739 case CEE_LDVIRTFTN:
5740 code_bounds_check (5);
5741 do_load_function_ptr (&ctx, read32 (ip + 1), TRUE);
5742 ip += 5;
5743 break;
5745 case CEE_UNUSED56:
5746 ++ip;
5747 break;
5749 case CEE_LDARG:
5750 case CEE_LDARGA:
5751 code_bounds_check (3);
5752 push_arg (&ctx, read16 (ip + 1), *ip == CEE_LDARGA);
5753 ip += 3;
5754 break;
5756 case CEE_LDLOC:
5757 case CEE_LDLOCA:
5758 code_bounds_check (3);
5759 push_local (&ctx, read16 (ip + 1), *ip == CEE_LDLOCA);
5760 ip += 3;
5761 break;
5763 case CEE_LOCALLOC:
5764 do_localloc (&ctx);
5765 ++ip;
5766 break;
5768 case CEE_UNUSED57:
5769 ++ip;
5770 break;
5771 case CEE_ENDFILTER:
5772 do_endfilter (&ctx);
5773 start = 1;
5774 ++ip;
5775 break;
5776 case CEE_UNALIGNED_:
5777 code_bounds_check (2);
5778 prefix |= PREFIX_UNALIGNED;
5779 ip += 2;
5780 break;
5781 case CEE_VOLATILE_:
5782 prefix |= PREFIX_VOLATILE;
5783 ++ip;
5784 break;
5785 case CEE_TAIL_:
5786 prefix |= PREFIX_TAIL;
5787 ++ip;
5788 if (ip < end && (*ip != CEE_CALL && *ip != CEE_CALLI && *ip != CEE_CALLVIRT))
5789 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("tail prefix must be used only with call opcodes at 0x%04x", ip_offset));
5790 break;
5792 case CEE_INITOBJ:
5793 code_bounds_check (5);
5794 do_initobj (&ctx, read32 (ip + 1));
5795 ip += 5;
5796 break;
5798 case CEE_CONSTRAINED_:
5799 code_bounds_check (5);
5800 ctx.constrained_type = get_boxable_mono_type (&ctx, read32 (ip + 1), "constrained.");
5801 prefix |= PREFIX_CONSTRAINED;
5802 ip += 5;
5803 break;
5805 case CEE_READONLY_:
5806 prefix |= PREFIX_READONLY;
5807 ip++;
5808 break;
5810 case CEE_CPBLK:
5811 CLEAR_PREFIX (&ctx, PREFIX_UNALIGNED | PREFIX_VOLATILE);
5812 if (!check_underflow (&ctx, 3))
5813 break;
5814 CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Instruction cpblk is not verifiable at 0x%04x", ctx.ip_offset));
5815 ip++;
5816 break;
5818 case CEE_INITBLK:
5819 CLEAR_PREFIX (&ctx, PREFIX_UNALIGNED | PREFIX_VOLATILE);
5820 if (!check_underflow (&ctx, 3))
5821 break;
5822 CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Instruction initblk is not verifiable at 0x%04x", ctx.ip_offset));
5823 ip++;
5824 break;
5826 case CEE_NO_:
5827 ip += 2;
5828 break;
5829 case CEE_RETHROW:
5830 if (!is_correct_rethrow (ctx.header, ip_offset))
5831 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("rethrow must be used inside a catch handler at 0x%04x", ctx.ip_offset));
5832 ctx.eval.size = 0;
5833 start = 1;
5834 ++ip;
5835 break;
5836 case CEE_UNUSED:
5837 ++ip;
5838 break;
5840 case CEE_SIZEOF:
5841 code_bounds_check (5);
5842 do_sizeof (&ctx, read32 (ip + 1));
5843 ip += 5;
5844 break;
5846 case CEE_REFANYTYPE:
5847 do_refanytype (&ctx);
5848 ++ip;
5849 break;
5851 default:
5852 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid instruction FE %x at 0x%04x", *ip, ctx.ip_offset));
5853 ++ip;
5855 break;
5857 default:
5858 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid instruction %x at 0x%04x", *ip, ctx.ip_offset));
5859 ++ip;
5862 /*TODO we can fast detect a forward branch or exception block targeting code after prefix, we should fail fast*/
5863 if (prefix) {
5864 if (!ctx.prefix_set) //first prefix
5865 ctx.code [ctx.ip_offset].flags |= IL_CODE_FLAG_SEEN;
5866 ctx.prefix_set |= prefix;
5867 ctx.has_flags = TRUE;
5868 prefix = 0;
5869 } else {
5870 if (!ctx.has_flags)
5871 ctx.code [ctx.ip_offset].flags |= IL_CODE_FLAG_SEEN;
5873 if (ctx.prefix_set & PREFIX_CONSTRAINED)
5874 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid instruction after constrained prefix at 0x%04x", ctx.ip_offset));
5875 if (ctx.prefix_set & PREFIX_READONLY)
5876 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid instruction after readonly prefix at 0x%04x", ctx.ip_offset));
5877 if (ctx.prefix_set & PREFIX_VOLATILE)
5878 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid instruction after volatile prefix at 0x%04x", ctx.ip_offset));
5879 if (ctx.prefix_set & PREFIX_UNALIGNED)
5880 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid instruction after unaligned prefix at 0x%04x", ctx.ip_offset));
5881 ctx.prefix_set = prefix = 0;
5882 ctx.has_flags = FALSE;
5886 * if ip != end we overflowed: mark as error.
5888 if ((ip != end || !start) && ctx.verifiable && !ctx.list) {
5889 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Run ahead of method code at 0x%04x", ip_offset));
5892 /*We should guard against the last decoded opcode, otherwise we might add errors that doesn't make sense.*/
5893 for (i = 0; i < ctx.code_size && i < ip_offset; ++i) {
5894 if (ctx.code [i].flags & IL_CODE_FLAG_WAS_TARGET) {
5895 if (!(ctx.code [i].flags & IL_CODE_FLAG_SEEN))
5896 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Branch or exception block target middle of intruction at 0x%04x", i));
5898 if (ctx.code [i].flags & IL_CODE_DELEGATE_SEQUENCE)
5899 CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Branch to delegate code sequence at 0x%04x", i));
5901 if ((ctx.code [i].flags & IL_CODE_LDFTN_DELEGATE_NONFINAL_VIRTUAL) && ctx.has_this_store)
5902 CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Invalid ldftn with virtual function in method with stdarg 0 at 0x%04x", i));
5904 if ((ctx.code [i].flags & IL_CODE_CALL_NONFINAL_VIRTUAL) && ctx.has_this_store)
5905 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));
5908 if (mono_method_is_constructor (ctx.method) && !ctx.super_ctor_called && !ctx.method->klass->valuetype && ctx.method->klass != mono_defaults.object_class) {
5909 char *method_name = mono_method_full_name (ctx.method, TRUE);
5910 char *type = mono_type_get_full_name (ctx.method->klass);
5911 if (ctx.method->klass->parent && ctx.method->klass->parent->exception_type != MONO_EXCEPTION_NONE)
5912 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));
5913 else
5914 CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Constructor %s for type %s not calling base type ctor.", method_name, type));
5915 g_free (method_name);
5916 g_free (type);
5919 cleanup:
5920 if (ctx.code) {
5921 for (i = 0; i < ctx.header->code_size; ++i) {
5922 if (ctx.code [i].stack)
5923 g_free (ctx.code [i].stack);
5927 for (tmp = ctx.funptrs; tmp; tmp = tmp->next)
5928 g_free (tmp->data);
5929 g_slist_free (ctx.funptrs);
5931 for (tmp = ctx.exception_types; tmp; tmp = tmp->next)
5932 mono_metadata_free_type (tmp->data);
5933 g_slist_free (ctx.exception_types);
5935 for (i = 0; i < ctx.num_locals; ++i) {
5936 if (ctx.locals [i])
5937 mono_metadata_free_type (ctx.locals [i]);
5939 for (i = 0; i < ctx.max_args; ++i) {
5940 if (ctx.params [i])
5941 mono_metadata_free_type (ctx.params [i]);
5944 if (ctx.eval.stack)
5945 g_free (ctx.eval.stack);
5946 if (ctx.code)
5947 g_free (ctx.code);
5948 g_free (ctx.locals);
5949 g_free (ctx.params);
5951 return ctx.list;
5954 char*
5955 mono_verify_corlib ()
5957 /* This is a public API function so cannot be removed */
5958 return NULL;
5962 * Returns true if @method needs to be verified.
5965 gboolean
5966 mono_verifier_is_enabled_for_method (MonoMethod *method)
5968 return mono_verifier_is_enabled_for_class (method->klass) && method->wrapper_type == MONO_WRAPPER_NONE;
5972 * Returns true if @klass need to be verified.
5975 gboolean
5976 mono_verifier_is_enabled_for_class (MonoClass *klass)
5978 return verify_all || (verifier_mode > MONO_VERIFIER_MODE_OFF && !klass->image->assembly->in_gac && klass->image != mono_defaults.corlib);
5981 gboolean
5982 mono_verifier_is_enabled_for_image (MonoImage *image)
5984 return verify_all || verifier_mode > MONO_VERIFIER_MODE_OFF;
5987 gboolean
5988 mono_verifier_is_method_full_trust (MonoMethod *method)
5990 return mono_verifier_is_class_full_trust (method->klass);
5994 * Returns if @klass is under full trust or not.
5996 * TODO This code doesn't take CAS into account.
5998 * Under verify_all all user code must be verifiable if no security option was set
6001 gboolean
6002 mono_verifier_is_class_full_trust (MonoClass *klass)
6004 /* under CoreCLR code is trusted if it is part of the "platform" otherwise all code inside the GAC is trusted */
6005 gboolean trusted_location = (mono_security_get_mode () != MONO_SECURITY_MODE_CORE_CLR) ?
6006 klass->image->assembly->in_gac : mono_security_core_clr_is_platform_image (klass->image);
6008 if (verify_all && verifier_mode == MONO_VERIFIER_MODE_OFF)
6009 return trusted_location || klass->image == mono_defaults.corlib;
6010 return verifier_mode < MONO_VERIFIER_MODE_VERIFIABLE || trusted_location || klass->image == mono_defaults.corlib;
6013 GSList*
6014 mono_method_verify_with_current_settings (MonoMethod *method, gboolean skip_visibility)
6016 return mono_method_verify (method,
6017 (verifier_mode != MONO_VERIFIER_MODE_STRICT ? MONO_VERIFY_NON_STRICT: 0)
6018 | (!mono_verifier_is_method_full_trust (method) ? MONO_VERIFY_FAIL_FAST : 0)
6019 | (skip_visibility ? MONO_VERIFY_SKIP_VISIBILITY : 0));
6022 static int
6023 get_field_end (MonoClassField *field)
6025 int align;
6026 int size = mono_type_size (field->type, &align);
6027 if (size == 0)
6028 size = 4; /*FIXME Is this a safe bet?*/
6029 return size + field->offset;
6032 static gboolean
6033 verify_class_for_overlapping_reference_fields (MonoClass *class)
6035 int i, j;
6036 gboolean is_fulltrust = mono_verifier_is_class_full_trust (class);
6037 if (!((class->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_EXPLICIT_LAYOUT) || !class->has_references)
6038 return TRUE;
6040 //we must check for stuff overlapping reference fields
6041 for (i = 0; i < class->field.count; ++i) {
6042 MonoClassField *field = &class->fields [i];
6043 int fieldEnd = get_field_end (field);
6044 gboolean is_valuetype = !MONO_TYPE_IS_REFERENCE (field->type);
6045 if (mono_field_is_deleted (field) || (field->type->attrs & FIELD_ATTRIBUTE_STATIC))
6046 continue;
6048 for (j = i + 1; j < class->field.count; ++j) {
6049 MonoClassField *other = &class->fields [j];
6050 int otherEnd = get_field_end (other);
6051 if (mono_field_is_deleted (other) || (is_valuetype && !MONO_TYPE_IS_REFERENCE (other->type)) || (other->type->attrs & FIELD_ATTRIBUTE_STATIC))
6052 continue;
6054 if (!is_valuetype && MONO_TYPE_IS_REFERENCE (other->type) && field->offset == other->offset && is_fulltrust)
6055 continue;
6057 if ((otherEnd > field->offset && otherEnd <= fieldEnd) || (other->offset >= field->offset && other->offset < fieldEnd))
6058 return FALSE;
6061 return TRUE;
6064 static guint
6065 field_hash (gconstpointer key)
6067 const MonoClassField *field = key;
6068 return g_str_hash (field->name) ^ mono_metadata_type_hash (field->type); /**/
6071 static gboolean
6072 field_equals (gconstpointer _a, gconstpointer _b)
6074 const MonoClassField *a = _a;
6075 const MonoClassField *b = _b;
6076 return !strcmp (a->name, b->name) && mono_metadata_type_equal (a->type, b->type);
6080 static gboolean
6081 verify_class_fields (MonoClass *class)
6083 gpointer iter = NULL;
6084 MonoClassField *field;
6085 MonoGenericContext *context = mono_class_get_context (class);
6086 GHashTable *unique_fields = g_hash_table_new_full (&field_hash, &field_equals, NULL, NULL);
6087 if (class->generic_container)
6088 context = &class->generic_container->context;
6090 while ((field = mono_class_get_fields (class, &iter)) != NULL) {
6091 if (!mono_type_is_valid_type_in_context (field->type, context)) {
6092 g_hash_table_destroy (unique_fields);
6093 return FALSE;
6095 if (g_hash_table_lookup (unique_fields, field)) {
6096 g_hash_table_destroy (unique_fields);
6097 return FALSE;
6099 g_hash_table_insert (unique_fields, field, field);
6101 g_hash_table_destroy (unique_fields);
6102 return TRUE;
6105 static gboolean
6106 verify_interfaces (MonoClass *class)
6108 int i;
6109 for (i = 0; i < class->interface_count; ++i) {
6110 MonoClass *iface = class->interfaces [i];
6111 if (!(iface->flags & TYPE_ATTRIBUTE_INTERFACE))
6112 return FALSE;
6114 return TRUE;
6117 static gboolean
6118 verify_valuetype_layout_with_target (MonoClass *class, MonoClass *target_class)
6120 int type;
6121 gpointer iter = NULL;
6122 MonoClassField *field;
6123 MonoClass *field_class;
6125 if (!class->valuetype)
6126 return TRUE;
6128 type = class->byval_arg.type;
6129 /*primitive type fields are not properly decoded*/
6130 if ((type >= MONO_TYPE_BOOLEAN && type <= MONO_TYPE_R8) || (type >= MONO_TYPE_I && type <= MONO_TYPE_U))
6131 return TRUE;
6133 while ((field = mono_class_get_fields (class, &iter)) != NULL) {
6134 if (!field->type)
6135 return FALSE;
6137 if (field->type->attrs & (FIELD_ATTRIBUTE_STATIC | FIELD_ATTRIBUTE_HAS_FIELD_RVA))
6138 continue;
6140 field_class = mono_class_get_generic_type_definition (mono_class_from_mono_type (field->type));
6142 if (field_class == target_class || !verify_valuetype_layout_with_target (field_class, target_class))
6143 return FALSE;
6146 return TRUE;
6149 static gboolean
6150 verify_valuetype_layout (MonoClass *class)
6152 gboolean res;
6153 res = verify_valuetype_layout_with_target (class, class);
6154 return res;
6158 * Check if the class is verifiable.
6160 * Right now there are no conditions that make a class a valid but not verifiable. Both overlapping reference
6161 * field and invalid generic instantiation are fatal errors.
6163 * This method must be safe to be called from mono_class_init and all code must be carefull about that.
6166 gboolean
6167 mono_verifier_verify_class (MonoClass *class)
6169 if (class->generic_container && (class->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_EXPLICIT_LAYOUT)
6170 return FALSE;
6171 if (!verify_class_for_overlapping_reference_fields (class))
6172 return FALSE;
6173 if (class->generic_class && !mono_class_is_valid_generic_instantiation (NULL, class))
6174 return FALSE;
6175 if (class->generic_class == NULL && !verify_class_fields (class))
6176 return FALSE;
6177 if (class->valuetype && !verify_valuetype_layout (class))
6178 return FALSE;
6179 if (!verify_interfaces (class))
6180 return FALSE;
6181 return TRUE;
6183 #else
6185 gboolean
6186 mono_verifier_verify_class (MonoClass *class)
6188 /* The verifier was disabled at compile time */
6189 return TRUE;
6192 GSList*
6193 mono_method_verify_with_current_settings (MonoMethod *method, gboolean skip_visibility)
6195 /* The verifier was disabled at compile time */
6196 return NULL;
6199 gboolean
6200 mono_verifier_is_class_full_trust (MonoClass *klass)
6202 /* The verifier was disabled at compile time */
6203 return TRUE;
6206 gboolean
6207 mono_verifier_is_method_full_trust (MonoMethod *method)
6209 /* The verifier was disabled at compile time */
6210 return TRUE;
6213 gboolean
6214 mono_verifier_is_enabled_for_image (MonoImage *image)
6216 /* The verifier was disabled at compile time */
6217 return FALSE;
6220 gboolean
6221 mono_verifier_is_enabled_for_class (MonoClass *klass)
6223 /* The verifier was disabled at compile time */
6224 return FALSE;
6227 gboolean
6228 mono_verifier_is_enabled_for_method (MonoMethod *method)
6230 /* The verifier was disabled at compile time */
6231 return FALSE;
6234 GSList*
6235 mono_method_verify (MonoMethod *method, int level)
6237 /* The verifier was disabled at compile time */
6238 return NULL;
6241 void
6242 mono_free_verify_list (GSList *list)
6244 /* The verifier was disabled at compile time */
6245 /* will always be null if verifier is disabled */
6248 GSList*
6249 mono_image_verify_tables (MonoImage *image, int level)
6251 /* The verifier was disabled at compile time */
6252 return NULL;
6254 #endif