2010-06-05 Mark Probst <mark.probst@gmail.com>
[mono.git] / mono / metadata / verify.c
1 /*
2  * verify.c: 
3  *
4  * Author:
5  *      Mono Project (http://www.mono-project.com)
6  *
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>
11
12 #include <mono/metadata/object-internals.h>
13 #include <mono/metadata/verify.h>
14 #include <mono/metadata/verify-internals.h>
15 #include <mono/metadata/opcodes.h>
16 #include <mono/metadata/tabledefs.h>
17 #include <mono/metadata/reflection.h>
18 #include <mono/metadata/debug-helpers.h>
19 #include <mono/metadata/mono-endian.h>
20 #include <mono/metadata/metadata.h>
21 #include <mono/metadata/metadata-internals.h>
22 #include <mono/metadata/class-internals.h>
23 #include <mono/metadata/security-manager.h>
24 #include <mono/metadata/security-core-clr.h>
25 #include <mono/metadata/tokentype.h>
26 #include <mono/metadata/mono-basic-block.h>
27 #include <mono/utils/mono-counters.h>
28 #include <mono/utils/monobitset.h>
29 #include <string.h>
30 #include <signal.h>
31 #include <ctype.h>
32
33
34 static MiniVerifierMode verifier_mode = MONO_VERIFIER_MODE_OFF;
35 static gboolean verify_all = FALSE;
36
37 /*
38  * Set the desired level of checks for the verfier.
39  * 
40  */
41 void
42 mono_verifier_set_mode (MiniVerifierMode mode)
43 {
44         verifier_mode = mode;
45 }
46
47 void
48 mono_verifier_enable_verify_all ()
49 {
50         verify_all = TRUE;
51 }
52
53 #ifndef DISABLE_VERIFIER
54 /*
55  * Pull the list of opcodes
56  */
57 #define OPDEF(a,b,c,d,e,f,g,h,i,j) \
58         a = i,
59
60 enum {
61 #include "mono/cil/opcode.def"
62         LAST = 0xff
63 };
64 #undef OPDEF
65
66 #ifdef MONO_VERIFIER_DEBUG
67 #define VERIFIER_DEBUG(code) do { code } while (0)
68 #else
69 #define VERIFIER_DEBUG(code)
70 #endif
71
72 //////////////////////////////////////////////////////////////////
73 #define IS_STRICT_MODE(ctx) (((ctx)->level & MONO_VERIFY_NON_STRICT) == 0)
74 #define IS_FAIL_FAST_MODE(ctx) (((ctx)->level & MONO_VERIFY_FAIL_FAST) == MONO_VERIFY_FAIL_FAST)
75 #define IS_SKIP_VISIBILITY(ctx) (((ctx)->level & MONO_VERIFY_SKIP_VISIBILITY) == MONO_VERIFY_SKIP_VISIBILITY)
76 #define IS_REPORT_ALL_ERRORS(ctx) (((ctx)->level & MONO_VERIFY_REPORT_ALL_ERRORS) == MONO_VERIFY_REPORT_ALL_ERRORS)
77 #define CLEAR_PREFIX(ctx, prefix) do { (ctx)->prefix_set &= ~(prefix); } while (0)
78 #define ADD_VERIFY_INFO(__ctx, __msg, __status, __exception)    \
79         do {    \
80                 MonoVerifyInfoExtended *vinfo = g_new (MonoVerifyInfoExtended, 1);      \
81                 vinfo->info.status = __status;  \
82                 vinfo->info.message = ( __msg );        \
83                 vinfo->exception_type = (__exception);  \
84                 (__ctx)->list = g_slist_prepend ((__ctx)->list, vinfo); \
85         } while (0)
86
87 //TODO support MONO_VERIFY_REPORT_ALL_ERRORS
88 #define ADD_VERIFY_ERROR(__ctx, __msg)  \
89         do {    \
90                 ADD_VERIFY_INFO(__ctx, __msg, MONO_VERIFY_ERROR, MONO_EXCEPTION_INVALID_PROGRAM); \
91                 (__ctx)->valid = 0; \
92         } while (0)
93
94 #define CODE_NOT_VERIFIABLE(__ctx, __msg) \
95         do {    \
96                 if ((__ctx)->verifiable || IS_REPORT_ALL_ERRORS (__ctx)) { \
97                         ADD_VERIFY_INFO(__ctx, __msg, MONO_VERIFY_NOT_VERIFIABLE, MONO_EXCEPTION_UNVERIFIABLE_IL); \
98                         (__ctx)->verifiable = 0; \
99                         if (IS_FAIL_FAST_MODE (__ctx)) \
100                                 (__ctx)->valid = 0; \
101                 } \
102         } while (0)
103
104 #define ADD_VERIFY_ERROR2(__ctx, __msg, __exception)    \
105         do {    \
106                 ADD_VERIFY_INFO(__ctx, __msg, MONO_VERIFY_ERROR, __exception); \
107                 (__ctx)->valid = 0; \
108         } while (0)
109
110 #define CODE_NOT_VERIFIABLE2(__ctx, __msg, __exception) \
111         do {    \
112                 if ((__ctx)->verifiable || IS_REPORT_ALL_ERRORS (__ctx)) { \
113                         ADD_VERIFY_INFO(__ctx, __msg, MONO_VERIFY_NOT_VERIFIABLE, __exception); \
114                         (__ctx)->verifiable = 0; \
115                         if (IS_FAIL_FAST_MODE (__ctx)) \
116                                 (__ctx)->valid = 0; \
117                 } \
118         } while (0)
119
120 #define CHECK_ADD4_OVERFLOW_UN(a, b) ((guint32)(0xFFFFFFFFU) - (guint32)(b) < (guint32)(a))
121 #define CHECK_ADD8_OVERFLOW_UN(a, b) ((guint64)(0xFFFFFFFFFFFFFFFFUL) - (guint64)(b) < (guint64)(a))
122
123 #if SIZEOF_VOID_P == 4
124 #define CHECK_ADDP_OVERFLOW_UN(a,b) CHECK_ADD4_OVERFLOW_UN(a, b)
125 #else
126 #define CHECK_ADDP_OVERFLOW_UN(a,b) CHECK_ADD8_OVERFLOW_UN(a, b)
127 #endif
128
129 #define ADDP_IS_GREATER_OR_OVF(a, b, c) (((a) + (b) > (c)) || CHECK_ADDP_OVERFLOW_UN (a, b))
130 #define ADD_IS_GREATER_OR_OVF(a, b, c) (((a) + (b) > (c)) || CHECK_ADD4_OVERFLOW_UN (a, b))
131
132 /*Flags to be used with ILCodeDesc::flags */
133 enum {
134         /*Instruction has not been processed.*/
135         IL_CODE_FLAG_NOT_PROCESSED  = 0,
136         /*Instruction was decoded by mono_method_verify loop.*/
137         IL_CODE_FLAG_SEEN = 1,
138         /*Instruction was target of a branch or is at a protected block boundary.*/
139         IL_CODE_FLAG_WAS_TARGET = 2,
140         /*Used by stack_init to avoid double initialize each entry.*/
141         IL_CODE_FLAG_STACK_INITED = 4,
142         /*Used by merge_stacks to decide if it should just copy the eval stack.*/
143         IL_CODE_STACK_MERGED = 8,
144         /*This instruction is part of the delegate construction sequence, it cannot be target of a branch.*/
145         IL_CODE_DELEGATE_SEQUENCE = 0x10,
146         /*This is a delegate created from a ldftn to a non final virtual method*/
147         IL_CODE_LDFTN_DELEGATE_NONFINAL_VIRTUAL = 0x20,
148         /*This is a call to a non final virtual method*/
149         IL_CODE_CALL_NONFINAL_VIRTUAL = 0x40,
150 };
151
152 typedef enum {
153         RESULT_VALID,
154         RESULT_UNVERIFIABLE,
155         RESULT_INVALID
156 } verify_result_t;
157
158 typedef struct {
159         MonoType *type;
160         int stype;
161         MonoMethod *method;
162 } ILStackDesc;
163
164
165 typedef struct {
166         ILStackDesc *stack;
167         guint16 size, max_size;
168         guint16 flags;
169 } ILCodeDesc;
170
171 typedef struct {
172         int max_args;
173         int max_stack;
174         int verifiable;
175         int valid;
176         int level;
177
178         int code_size;
179         ILCodeDesc *code;
180         ILCodeDesc eval;
181
182         MonoType **params;
183         GSList *list;
184         /*Allocated fnptr MonoType that should be freed by us.*/
185         GSList *funptrs;
186         /*Type dup'ed exception types from catch blocks.*/
187         GSList *exception_types;
188
189         int num_locals;
190         MonoType **locals;
191
192         /*TODO get rid of target here, need_merge in mono_method_verify and hoist the merging code in the branching code*/
193         int target;
194
195         guint32 ip_offset;
196         MonoMethodSignature *signature;
197         MonoMethodHeader *header;
198
199         MonoGenericContext *generic_context;
200         MonoImage *image;
201         MonoMethod *method;
202
203         /*This flag helps solving a corner case of delegate verification in that you cannot have a "starg 0" 
204          *on a method that creates a delegate for a non-final virtual method using ldftn*/
205         gboolean has_this_store;
206
207         /*This flag is used to control if the contructor of the parent class has been called.
208          *If the this pointer is pushed on the eval stack and it's a reference type constructor and
209          * super_ctor_called is false, the uninitialized flag is set on the pushed value.
210          * 
211          * Poping an uninitialized this ptr from the eval stack is an unverifiable operation unless
212          * the safe variant is used. Only a few opcodes can use it : dup, pop, ldfld, stfld and call to a constructor.
213          */
214         gboolean super_ctor_called;
215
216         guint32 prefix_set;
217         gboolean has_flags;
218         MonoType *constrained_type;
219 } VerifyContext;
220
221 static void
222 merge_stacks (VerifyContext *ctx, ILCodeDesc *from, ILCodeDesc *to, gboolean start, gboolean external);
223
224 static int
225 get_stack_type (MonoType *type);
226
227 static gboolean
228 mono_delegate_signature_equal (MonoMethodSignature *delegate_sig, MonoMethodSignature *method_sig, gboolean is_static_ldftn);
229
230 static gboolean
231 mono_class_is_valid_generic_instantiation (VerifyContext *ctx, MonoClass *klass);
232
233 static gboolean
234 mono_method_is_valid_generic_instantiation (VerifyContext *ctx, MonoMethod *method);
235 //////////////////////////////////////////////////////////////////
236
237
238
239 enum {
240         TYPE_INV = 0, /* leave at 0. */
241         TYPE_I4  = 1,
242         TYPE_I8  = 2,
243         TYPE_NATIVE_INT = 3,
244         TYPE_R8  = 4,
245         /* Used by operator tables to resolve pointer types (managed & unmanaged) and by unmanaged pointer types*/
246         TYPE_PTR  = 5,
247         /* value types and classes */
248         TYPE_COMPLEX = 6,
249         /* Number of types, used to define the size of the tables*/
250         TYPE_MAX = 6,
251
252         /* Used by tables to signal that a result is not verifiable*/
253         NON_VERIFIABLE_RESULT = 0x80,
254
255         /*Mask used to extract just the type, excluding flags */
256         TYPE_MASK = 0x0F,
257
258         /* The stack type is a managed pointer, unmask the value to res */
259         POINTER_MASK = 0x100,
260         
261         /*Stack type with the pointer mask*/
262         RAW_TYPE_MASK = 0x10F,
263
264         /* Controlled Mutability Manager Pointer */
265         CMMP_MASK = 0x200,
266
267         /* The stack type is a null literal*/
268         NULL_LITERAL_MASK = 0x400,
269         
270         /**Used by ldarg.0 and family to let delegate verification happens.*/
271         THIS_POINTER_MASK = 0x800,
272
273         /**Signals that this is a boxed value type*/
274         BOXED_MASK = 0x1000,
275
276         /*This is an unitialized this ref*/
277         UNINIT_THIS_MASK = 0x2000,
278 };
279
280 static const char* const
281 type_names [TYPE_MAX + 1] = {
282         "Invalid",
283         "Int32",
284         "Int64",
285         "Native Int",
286         "Float64",
287         "Native Pointer",
288         "Complex"       
289 };
290
291 enum {
292         PREFIX_UNALIGNED = 1,
293         PREFIX_VOLATILE  = 2,
294         PREFIX_TAIL      = 4,
295         PREFIX_CONSTRAINED = 8,
296         PREFIX_READONLY = 16
297 };
298 //////////////////////////////////////////////////////////////////
299
300 #ifdef ENABLE_VERIFIER_STATS
301
302 #define MEM_ALLOC(amt) do { allocated_memory += (amt); working_set += (amt); } while (0)
303 #define MEM_FREE(amt) do { working_set -= (amt); } while (0)
304
305 static int allocated_memory;
306 static int working_set;
307 static int max_allocated_memory;
308 static int max_working_set;
309 static int total_allocated_memory;
310
311 static void
312 finish_collect_stats (void)
313 {
314         max_allocated_memory = MAX (max_allocated_memory, allocated_memory);
315         max_working_set = MAX (max_working_set, working_set);
316         total_allocated_memory += allocated_memory;
317         allocated_memory = working_set = 0;
318 }
319
320 static void
321 init_verifier_stats (void)
322 {
323         static gboolean inited;
324         if (!inited) {
325                 inited = TRUE;
326                 mono_counters_register ("Maximum memory allocated during verification", MONO_COUNTER_METADATA | MONO_COUNTER_INT, &max_allocated_memory);
327                 mono_counters_register ("Maximum memory used during verification", MONO_COUNTER_METADATA | MONO_COUNTER_INT, &max_working_set);
328                 mono_counters_register ("Total memory allocated for verification", MONO_COUNTER_METADATA | MONO_COUNTER_INT, &total_allocated_memory);
329         }
330 }
331
332 #else
333
334 #define MEM_ALLOC(amt) do {} while (0)
335 #define MEM_FREE(amt) do { } while (0)
336
337 #define finish_collect_stats()
338 #define init_verifier_stats()
339
340 #endif
341
342
343 //////////////////////////////////////////////////////////////////
344
345
346 /*Token validation macros and functions */
347 #define IS_MEMBER_REF(token) (mono_metadata_token_table (token) == MONO_TABLE_MEMBERREF)
348 #define IS_METHOD_DEF(token) (mono_metadata_token_table (token) == MONO_TABLE_METHOD)
349 #define IS_METHOD_SPEC(token) (mono_metadata_token_table (token) == MONO_TABLE_METHODSPEC)
350 #define IS_FIELD_DEF(token) (mono_metadata_token_table (token) == MONO_TABLE_FIELD)
351
352 #define IS_TYPE_REF(token) (mono_metadata_token_table (token) == MONO_TABLE_TYPEREF)
353 #define IS_TYPE_DEF(token) (mono_metadata_token_table (token) == MONO_TABLE_TYPEDEF)
354 #define IS_TYPE_SPEC(token) (mono_metadata_token_table (token) == MONO_TABLE_TYPESPEC)
355 #define IS_METHOD_DEF_OR_REF_OR_SPEC(token) (IS_METHOD_DEF (token) || IS_MEMBER_REF (token) || IS_METHOD_SPEC (token))
356 #define IS_TYPE_DEF_OR_REF_OR_SPEC(token) (IS_TYPE_DEF (token) || IS_TYPE_REF (token) || IS_TYPE_SPEC (token))
357 #define IS_FIELD_DEF_OR_REF(token) (IS_FIELD_DEF (token) || IS_MEMBER_REF (token))
358
359 /*
360  * Verify if @token refers to a valid row on int's table.
361  */
362 static gboolean
363 token_bounds_check (MonoImage *image, guint32 token)
364 {
365         if (image->dynamic)
366                 return mono_reflection_is_valid_dynamic_token ((MonoDynamicImage*)image, token);
367         return image->tables [mono_metadata_token_table (token)].rows >= mono_metadata_token_index (token);
368 }
369
370 static MonoType *
371 mono_type_create_fnptr_from_mono_method (VerifyContext *ctx, MonoMethod *method)
372 {
373         MonoType *res = g_new0 (MonoType, 1);
374         MEM_ALLOC (sizeof (MonoType));
375
376         //FIXME use mono_method_get_signature_full
377         res->data.method = mono_method_signature (method);
378         res->type = MONO_TYPE_FNPTR;
379         ctx->funptrs = g_slist_prepend (ctx->funptrs, res);
380         return res;
381 }
382
383 /*
384  * mono_type_is_enum_type:
385  * 
386  * Returns TRUE if @type is an enum type. 
387  */
388 static gboolean
389 mono_type_is_enum_type (MonoType *type)
390 {
391         if (type->type == MONO_TYPE_VALUETYPE && type->data.klass->enumtype)
392                 return TRUE;
393         if (type->type == MONO_TYPE_GENERICINST && type->data.generic_class->container_class->enumtype)
394                 return TRUE;
395         return FALSE;
396 }
397
398 /*
399  * mono_type_is_value_type:
400  * 
401  * Returns TRUE if @type is named after @namespace.@name.
402  * 
403  */
404 static gboolean
405 mono_type_is_value_type (MonoType *type, const char *namespace, const char *name)
406 {
407         return type->type == MONO_TYPE_VALUETYPE &&
408                 !strcmp (namespace, type->data.klass->name_space) &&
409                 !strcmp (name, type->data.klass->name);
410 }
411
412 /*
413  * Returns TURE if @type is VAR or MVAR
414  */
415 static gboolean
416 mono_type_is_generic_argument (MonoType *type)
417 {
418         return type->type == MONO_TYPE_VAR || type->type == MONO_TYPE_MVAR;
419 }
420
421 /*
422  * mono_type_get_underlying_type_any:
423  * 
424  * This functions is just like mono_type_get_underlying_type but it doesn't care if the type is byref.
425  * 
426  * Returns the underlying type of @type regardless if it is byref or not.
427  */
428 static MonoType*
429 mono_type_get_underlying_type_any (MonoType *type)
430 {
431         if (type->type == MONO_TYPE_VALUETYPE && type->data.klass->enumtype)
432                 return mono_class_enum_basetype (type->data.klass);
433         if (type->type == MONO_TYPE_GENERICINST && type->data.generic_class->container_class->enumtype)
434                 return mono_class_enum_basetype (type->data.generic_class->container_class);
435         return type;
436 }
437
438 static G_GNUC_UNUSED const char*
439 mono_type_get_stack_name (MonoType *type)
440 {
441         return type_names [get_stack_type (type) & TYPE_MASK];
442 }
443
444 #define CTOR_REQUIRED_FLAGS (METHOD_ATTRIBUTE_SPECIAL_NAME | METHOD_ATTRIBUTE_RT_SPECIAL_NAME)
445 #define CTOR_INVALID_FLAGS (METHOD_ATTRIBUTE_STATIC)
446
447 static gboolean
448 mono_method_is_constructor (MonoMethod *method) 
449 {
450         return ((method->flags & CTOR_REQUIRED_FLAGS) == CTOR_REQUIRED_FLAGS &&
451                         !(method->flags & CTOR_INVALID_FLAGS) &&
452                         !strcmp (".ctor", method->name));
453 }
454
455 static gboolean
456 mono_class_has_default_constructor (MonoClass *klass)
457 {
458         MonoMethod *method;
459         int i;
460
461         mono_class_setup_methods (klass);
462         if (klass->exception_type)
463                 return FALSE;
464
465         for (i = 0; i < klass->method.count; ++i) {
466                 method = klass->methods [i];
467                 if (mono_method_is_constructor (method) &&
468                         mono_method_signature (method) &&
469                         mono_method_signature (method)->param_count == 0 &&
470                         (method->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK) == METHOD_ATTRIBUTE_PUBLIC)
471                         return TRUE;
472         }
473         return FALSE;
474 }
475
476 /*
477  * Verify if @type is valid for the given @ctx verification context.
478  * this function checks for VAR and MVAR types that are invalid under the current verifier,
479  */
480 static gboolean
481 mono_type_is_valid_type_in_context (MonoType *type, MonoGenericContext *context)
482 {
483         int i;
484         MonoGenericInst *inst;
485
486         switch (type->type) {
487         case MONO_TYPE_VAR:
488         case MONO_TYPE_MVAR:
489                 if (!context)
490                         return FALSE;
491                 inst = type->type == MONO_TYPE_VAR ? context->class_inst : context->method_inst;
492                 if (!inst || mono_type_get_generic_param_num (type) >= inst->type_argc)
493                         return FALSE;
494                 break;
495         case MONO_TYPE_SZARRAY:
496                 return mono_type_is_valid_type_in_context (&type->data.klass->byval_arg, context);
497         case MONO_TYPE_ARRAY:
498                 return mono_type_is_valid_type_in_context (&type->data.array->eklass->byval_arg, context);
499         case MONO_TYPE_PTR:
500                 return mono_type_is_valid_type_in_context (type->data.type, context);
501         case MONO_TYPE_GENERICINST:
502                 inst = type->data.generic_class->context.class_inst;
503                 if (!inst->is_open)
504                         break;
505                 for (i = 0; i < inst->type_argc; ++i)
506                         if (!mono_type_is_valid_type_in_context (inst->type_argv [i], context))
507                                 return FALSE;
508                 break;
509         }
510         return TRUE;
511 }
512
513 /*This function returns NULL if the type is not instantiatable*/
514 static MonoType*
515 verifier_inflate_type (VerifyContext *ctx, MonoType *type, MonoGenericContext *context)
516 {
517         MonoError error;
518         MonoType *result;
519
520         result = mono_class_inflate_generic_type_checked (type, context, &error);
521         if (!mono_error_ok (&error)) {
522                 mono_error_cleanup (&error);
523                 return NULL;
524         }
525         return result;
526 }
527
528
529 static gboolean
530 is_valid_generic_instantiation (MonoGenericContainer *gc, MonoGenericContext *context, MonoGenericInst *ginst)
531 {
532         MonoError error;
533         int i;
534
535         if (ginst->type_argc != gc->type_argc)
536                 return FALSE;
537
538         for (i = 0; i < gc->type_argc; ++i) {
539                 MonoGenericParamInfo *param_info = mono_generic_container_get_param_info (gc, i);
540                 MonoClass *paramClass;
541                 MonoClass **constraints;
542
543                 if (!param_info->constraints && !(param_info->flags & GENERIC_PARAMETER_ATTRIBUTE_SPECIAL_CONSTRAINTS_MASK))
544                         continue;
545                 if (mono_type_is_generic_argument (ginst->type_argv [i]))
546                         continue; //it's not our job to validate type variables
547
548                 paramClass = mono_class_from_mono_type (ginst->type_argv [i]);
549
550                 if (paramClass->exception_type != MONO_EXCEPTION_NONE)
551                         return FALSE;
552
553                 /*it's not safe to call mono_class_init from here*/
554                 if (paramClass->generic_class && !paramClass->inited) {
555                         if (!mono_class_is_valid_generic_instantiation (NULL, paramClass))
556                                 return FALSE;
557                 }
558
559                 if ((param_info->flags & GENERIC_PARAMETER_ATTRIBUTE_VALUE_TYPE_CONSTRAINT) && (!paramClass->valuetype || mono_class_is_nullable (paramClass)))
560                         return FALSE;
561
562                 if ((param_info->flags & GENERIC_PARAMETER_ATTRIBUTE_REFERENCE_TYPE_CONSTRAINT) && paramClass->valuetype)
563                         return FALSE;
564
565                 if ((param_info->flags & GENERIC_PARAMETER_ATTRIBUTE_CONSTRUCTOR_CONSTRAINT) && !paramClass->valuetype && !mono_class_has_default_constructor (paramClass))
566                         return FALSE;
567
568                 if (!param_info->constraints)
569                         continue;
570
571                 for (constraints = param_info->constraints; *constraints; ++constraints) {
572                         MonoClass *ctr = *constraints;
573                         MonoType *inflated;
574
575                         inflated = mono_class_inflate_generic_type_checked (&ctr->byval_arg, context, &error);
576                         if (!mono_error_ok (&error)) {
577                                 mono_error_cleanup (&error);
578                                 return FALSE;
579                         }
580                         ctr = mono_class_from_mono_type (inflated);
581                         mono_metadata_free_type (inflated);
582
583                         if (!mono_class_is_assignable_from_slow (ctr, paramClass))
584                                 return FALSE;
585                 }
586         }
587         return TRUE;
588 }
589
590 /*
591  * Return true if @candidate is constraint compatible with @target.
592  * 
593  * This means that @candidate constraints are a super set of @target constaints
594  */
595 static gboolean
596 mono_generic_param_is_constraint_compatible (VerifyContext *ctx, MonoGenericParam *target, MonoGenericParam *candidate, MonoGenericContext *context)
597 {
598         MonoGenericParamInfo *tinfo = mono_generic_param_info (target);
599         MonoGenericParamInfo *cinfo = mono_generic_param_info (candidate);
600
601         int tmask = tinfo->flags & GENERIC_PARAMETER_ATTRIBUTE_SPECIAL_CONSTRAINTS_MASK;
602         int cmask = cinfo->flags & GENERIC_PARAMETER_ATTRIBUTE_SPECIAL_CONSTRAINTS_MASK;
603         if ((tmask & cmask) != tmask)
604                 return FALSE;
605
606         if (tinfo->constraints) {
607                 MonoClass **target_class, **candidate_class;
608                 if (!cinfo->constraints)
609                         return FALSE;
610                 for (target_class = tinfo->constraints; *target_class; ++target_class) {
611                         MonoClass *tc;
612                         MonoType *inflated = verifier_inflate_type (ctx, &(*target_class)->byval_arg, context);
613                         if (!inflated)
614                                 return FALSE;
615                         tc = mono_class_from_mono_type (inflated);
616                         mono_metadata_free_type (inflated);
617
618                         for (candidate_class = cinfo->constraints; *candidate_class; ++candidate_class) {
619                                 MonoClass *cc;
620                                 inflated = verifier_inflate_type (ctx, &(*candidate_class)->byval_arg, ctx->generic_context);
621                                 if (!inflated)
622                                         return FALSE;
623                                 cc = mono_class_from_mono_type (inflated);
624                                 mono_metadata_free_type (inflated);
625
626                                 if (mono_class_is_assignable_from (tc, cc))
627                                         break;
628                         }
629                         if (!*candidate_class)
630                                 return FALSE;
631                 }
632         }
633         return TRUE;
634 }
635
636 static MonoGenericParam*
637 verifier_get_generic_param_from_type (VerifyContext *ctx, MonoType *type)
638 {
639         MonoGenericContainer *gc;
640         MonoMethod *method = ctx->method;
641         int num;
642
643         num = mono_type_get_generic_param_num (type);
644
645         if (type->type == MONO_TYPE_VAR) {
646                 MonoClass *gtd = method->klass;
647                 if (gtd->generic_class)
648                         gtd = gtd->generic_class->container_class;
649                 gc = gtd->generic_container;
650         } else { //MVAR
651                 MonoMethod *gmd = method;
652                 if (method->is_inflated)
653                         gmd = ((MonoMethodInflated*)method)->declaring;
654                 gc = mono_method_get_generic_container (gmd);
655         }
656         if (!gc)
657                 return FALSE;
658         return mono_generic_container_get_param (gc, num);
659 }
660
661
662
663 /*
664  * Verify if @type is valid for the given @ctx verification context.
665  * this function checks for VAR and MVAR types that are invalid under the current verifier,
666  * This means that it either 
667  */
668 static gboolean
669 is_valid_type_in_context (VerifyContext *ctx, MonoType *type)
670 {
671         return mono_type_is_valid_type_in_context (type, ctx->generic_context);
672 }
673
674 static gboolean
675 is_valid_generic_instantiation_in_context (VerifyContext *ctx, MonoGenericInst *ginst)
676 {
677         int i;
678         for (i = 0; i < ginst->type_argc; ++i) {
679                 MonoType *type = ginst->type_argv [i];
680                 if (!is_valid_type_in_context (ctx, type))
681                         return FALSE;
682         }
683         return TRUE;
684 }
685
686 static gboolean
687 generic_arguments_respect_constraints (VerifyContext *ctx, MonoGenericContainer *gc, MonoGenericContext *context, MonoGenericInst *ginst)
688 {
689         int i;
690         for (i = 0; i < ginst->type_argc; ++i) {
691                 MonoType *type = ginst->type_argv [i];
692                 MonoGenericParam *target = mono_generic_container_get_param (gc, i);
693                 MonoGenericParam *candidate;
694
695                 if (!mono_type_is_generic_argument (type))
696                         continue;
697
698                 if (!is_valid_type_in_context (ctx, type))
699                         return FALSE;
700
701                 candidate = verifier_get_generic_param_from_type (ctx, type);
702
703                 if (!mono_generic_param_is_constraint_compatible (ctx, target, candidate, context))
704                         return FALSE;
705         }
706         return TRUE;
707 }
708
709 static gboolean
710 mono_method_repect_method_constraints (VerifyContext *ctx, MonoMethod *method)
711 {
712         MonoMethodInflated *gmethod = (MonoMethodInflated *)method;
713         MonoGenericInst *ginst = gmethod->context.method_inst;
714         MonoGenericContainer *gc = mono_method_get_generic_container (gmethod->declaring);
715         return !gc || generic_arguments_respect_constraints (ctx, gc, &gmethod->context, ginst);
716 }
717
718 static gboolean
719 mono_class_repect_method_constraints (VerifyContext *ctx, MonoClass *klass)
720 {
721         MonoGenericClass *gklass = klass->generic_class;
722         MonoGenericInst *ginst = gklass->context.class_inst;
723         MonoGenericContainer *gc = gklass->container_class->generic_container;
724         return !gc || generic_arguments_respect_constraints (ctx, gc, &gklass->context, ginst);
725 }
726
727 static gboolean
728 mono_method_is_valid_generic_instantiation (VerifyContext *ctx, MonoMethod *method)
729 {
730         MonoMethodInflated *gmethod = (MonoMethodInflated *)method;
731         MonoGenericInst *ginst = gmethod->context.method_inst;
732         MonoGenericContainer *gc = mono_method_get_generic_container (gmethod->declaring);
733         if (!gc) /*non-generic inflated method - it's part of a generic type  */
734                 return TRUE;
735         if (ctx && !is_valid_generic_instantiation_in_context (ctx, ginst))
736                 return FALSE;
737         return is_valid_generic_instantiation (gc, &gmethod->context, ginst);
738
739 }
740
741 static gboolean
742 mono_class_is_valid_generic_instantiation (VerifyContext *ctx, MonoClass *klass)
743 {
744         MonoGenericClass *gklass = klass->generic_class;
745         MonoGenericInst *ginst = gklass->context.class_inst;
746         MonoGenericContainer *gc = gklass->container_class->generic_container;
747         if (ctx && !is_valid_generic_instantiation_in_context (ctx, ginst))
748                 return FALSE;
749         return is_valid_generic_instantiation (gc, &gklass->context, ginst);
750 }
751
752 static gboolean
753 mono_type_is_valid_in_context (VerifyContext *ctx, MonoType *type)
754 {
755         MonoClass *klass;
756
757         if (type == NULL) {
758                 ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid null type at 0x%04x", ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE);
759                 return FALSE;
760         }
761
762         if (!is_valid_type_in_context (ctx, type)) {
763                 char *str = mono_type_full_name (type);
764                 ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid generic type (%s%s) (argument out of range or %s is not generic) at 0x%04x",
765                         type->type == MONO_TYPE_VAR ? "!" : "!!",
766                         str,
767                         type->type == MONO_TYPE_VAR ? "class" : "method",
768                         ctx->ip_offset),
769                         MONO_EXCEPTION_BAD_IMAGE);              
770                 g_free (str);
771                 return FALSE;
772         }
773
774         klass = mono_class_from_mono_type (type);
775         mono_class_init (klass);
776         if (mono_loader_get_last_error () || klass->exception_type != MONO_EXCEPTION_NONE) {
777                 if (klass->generic_class && !mono_class_is_valid_generic_instantiation (NULL, klass))
778                         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);
779                 else
780                         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);
781                 return FALSE;
782         }
783
784         if (klass->generic_class && klass->generic_class->container_class->exception_type != MONO_EXCEPTION_NONE) {
785                 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);
786                 return FALSE;
787         }
788
789         if (!klass->generic_class)
790                 return TRUE;
791
792         if (!mono_class_is_valid_generic_instantiation (ctx, klass)) {
793                 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);
794                 return FALSE;
795         }
796
797         if (!mono_class_repect_method_constraints (ctx, klass)) {
798                 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);
799                 return FALSE;
800         }
801
802         return TRUE;
803 }
804
805 static verify_result_t
806 mono_method_is_valid_in_context (VerifyContext *ctx, MonoMethod *method)
807 {
808         if (!mono_type_is_valid_in_context (ctx, &method->klass->byval_arg))
809                 return RESULT_INVALID;
810
811         if (!method->is_inflated)
812                 return RESULT_VALID;
813
814         if (!mono_method_is_valid_generic_instantiation (ctx, method)) {
815                 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);
816                 return RESULT_INVALID;
817         }
818
819         if (!mono_method_repect_method_constraints (ctx, method)) {
820                 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));
821                 return RESULT_UNVERIFIABLE;
822         }
823         return RESULT_VALID;
824 }
825
826         
827 static MonoClassField*
828 verifier_load_field (VerifyContext *ctx, int token, MonoClass **out_klass, const char *opcode) {
829         MonoClassField *field;
830         MonoClass *klass = NULL;
831
832         if (!IS_FIELD_DEF_OR_REF (token) || !token_bounds_check (ctx->image, token)) {
833                 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);
834                 return NULL;
835         }
836
837         field = mono_field_from_token (ctx->image, token, &klass, ctx->generic_context);
838         if (!field || !field->parent || !klass) {
839                 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);
840                 return NULL;
841         }
842
843         if (!mono_type_is_valid_in_context (ctx, &klass->byval_arg))
844                 return NULL;
845
846         *out_klass = klass;
847         return field;
848 }
849
850 static MonoMethod*
851 verifier_load_method (VerifyContext *ctx, int token, const char *opcode) {
852         MonoMethod* method;
853         
854         if (!IS_METHOD_DEF_OR_REF_OR_SPEC (token) || !token_bounds_check (ctx->image, token)) {
855                 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);
856                 return NULL;
857         }
858
859         method = mono_get_method_full (ctx->image, token, NULL, ctx->generic_context);
860
861         if (!method) {
862                 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);
863                 return NULL;
864         }
865         
866         if (mono_method_is_valid_in_context (ctx, method) == RESULT_INVALID)
867                 return NULL;
868
869         return method;
870 }
871
872 static MonoType*
873 verifier_load_type (VerifyContext *ctx, int token, const char *opcode) {
874         MonoType* type;
875         
876         if (!IS_TYPE_DEF_OR_REF_OR_SPEC (token) || !token_bounds_check (ctx->image, token)) {
877                 ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid type token 0x%08x at 0x%04x", token, ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE);
878                 return NULL;
879         }
880
881         type = mono_type_get_full (ctx->image, token, ctx->generic_context);
882
883         if (!type) {
884                 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);
885                 return NULL;
886         }
887
888         if (!mono_type_is_valid_in_context (ctx, type))
889                 return NULL;
890
891         return type;
892 }
893
894
895 /* stack_slot_get_type:
896  * 
897  * Returns the stack type of @value. This value includes POINTER_MASK.
898  * 
899  * Use this function to checks that account for a managed pointer.
900  */
901 static gint32
902 stack_slot_get_type (ILStackDesc *value)
903 {
904         return value->stype & RAW_TYPE_MASK;
905 }
906
907 /* stack_slot_get_underlying_type:
908  * 
909  * Returns the stack type of @value. This value does not include POINTER_MASK.
910  * 
911  * Use this function is cases where the fact that the value could be a managed pointer is
912  * irrelevant. For example, field load doesn't care about this fact of type on stack.
913  */
914 static gint32
915 stack_slot_get_underlying_type (ILStackDesc *value)
916 {
917         return value->stype & TYPE_MASK;
918 }
919
920 /* stack_slot_is_managed_pointer:
921  * 
922  * Returns TRUE is @value is a managed pointer.
923  */
924 static gboolean
925 stack_slot_is_managed_pointer (ILStackDesc *value)
926 {
927         return (value->stype & POINTER_MASK) == POINTER_MASK;
928 }
929
930 /* stack_slot_is_managed_mutability_pointer:
931  * 
932  * Returns TRUE is @value is a managed mutability pointer.
933  */
934 static G_GNUC_UNUSED gboolean
935 stack_slot_is_managed_mutability_pointer (ILStackDesc *value)
936 {
937         return (value->stype & CMMP_MASK) == CMMP_MASK;
938 }
939
940 /* stack_slot_is_null_literal:
941  * 
942  * Returns TRUE is @value is the null literal.
943  */
944 static gboolean
945 stack_slot_is_null_literal (ILStackDesc *value)
946 {
947         return (value->stype & NULL_LITERAL_MASK) == NULL_LITERAL_MASK;
948 }
949
950
951 /* stack_slot_is_this_pointer:
952  * 
953  * Returns TRUE is @value is the this literal
954  */
955 static gboolean
956 stack_slot_is_this_pointer (ILStackDesc *value)
957 {
958         return (value->stype & THIS_POINTER_MASK) == THIS_POINTER_MASK;
959 }
960
961 /* stack_slot_is_boxed_value:
962  * 
963  * Returns TRUE is @value is a boxed value
964  */
965 static gboolean
966 stack_slot_is_boxed_value (ILStackDesc *value)
967 {
968         return (value->stype & BOXED_MASK) == BOXED_MASK;
969 }
970
971 static const char *
972 stack_slot_get_name (ILStackDesc *value)
973 {
974         return type_names [value->stype & TYPE_MASK];
975 }
976
977 #define APPEND_WITH_PREDICATE(PRED,NAME) do {\
978         if (PRED (value)) { \
979                 if (!first) \
980                         g_string_append (str, ", "); \
981                 g_string_append (str, NAME); \
982                 first = FALSE; \
983         } } while (0)
984
985 static char*
986 stack_slot_stack_type_full_name (ILStackDesc *value)
987 {
988         GString *str = g_string_new ("");
989         char *result;
990         gboolean has_pred = FALSE, first = TRUE;
991
992         if ((value->stype & TYPE_MASK) != value->stype) {
993                 g_string_append(str, "[");
994                 APPEND_WITH_PREDICATE (stack_slot_is_this_pointer, "this");
995                 APPEND_WITH_PREDICATE (stack_slot_is_boxed_value, "boxed");
996                 APPEND_WITH_PREDICATE (stack_slot_is_null_literal, "null");
997                 APPEND_WITH_PREDICATE (stack_slot_is_managed_mutability_pointer, "cmmp");
998                 APPEND_WITH_PREDICATE (stack_slot_is_managed_pointer, "mp");
999                 has_pred = TRUE;
1000         }
1001
1002         if (mono_type_is_generic_argument (value->type) && !stack_slot_is_boxed_value (value)) {
1003                 if (!has_pred)
1004                         g_string_append(str, "[");
1005                 if (!first)
1006                         g_string_append (str, ", ");
1007                 g_string_append (str, "unboxed");
1008                 has_pred = TRUE;
1009         }
1010
1011         if (has_pred)
1012                 g_string_append(str, "] ");
1013
1014         g_string_append (str, stack_slot_get_name (value));
1015         result = str->str;
1016         g_string_free (str, FALSE);
1017         return result;
1018 }
1019
1020 static char*
1021 stack_slot_full_name (ILStackDesc *value)
1022 {
1023         char *type_name = mono_type_full_name (value->type);
1024         char *stack_name = stack_slot_stack_type_full_name (value);
1025         char *res = g_strdup_printf ("%s (%s)", type_name, stack_name);
1026         g_free (type_name);
1027         g_free (stack_name);
1028         return res;
1029 }
1030
1031 //////////////////////////////////////////////////////////////////
1032 void
1033 mono_free_verify_list (GSList *list)
1034 {
1035         MonoVerifyInfoExtended *info;
1036         GSList *tmp;
1037
1038         for (tmp = list; tmp; tmp = tmp->next) {
1039                 info = tmp->data;
1040                 g_free (info->info.message);
1041                 g_free (info);
1042         }
1043         g_slist_free (list);
1044 }
1045
1046 #define ADD_ERROR(list,msg)     \
1047         do {    \
1048                 MonoVerifyInfoExtended *vinfo = g_new (MonoVerifyInfoExtended, 1);      \
1049                 vinfo->info.status = MONO_VERIFY_ERROR; \
1050                 vinfo->info.message = (msg);    \
1051                 (list) = g_slist_prepend ((list), vinfo);       \
1052         } while (0)
1053
1054 #define ADD_WARN(list,code,msg) \
1055         do {    \
1056                 MonoVerifyInfoExtended *vinfo = g_new (MonoVerifyInfoExtended, 1);      \
1057                 vinfo->info.status = (code);    \
1058                 vinfo->info.message = (msg);    \
1059                 (list) = g_slist_prepend ((list), vinfo);       \
1060         } while (0)
1061
1062 #define ADD_INVALID(list,msg)   \
1063         do {    \
1064                 MonoVerifyInfoExtended *vinfo = g_new (MonoVerifyInfoExtended, 1);      \
1065                 vinfo->status = MONO_VERIFY_ERROR;      \
1066                 vinfo->message = (msg); \
1067                 (list) = g_slist_prepend ((list), vinfo);       \
1068                 /*G_BREAKPOINT ();*/    \
1069                 goto invalid_cil;       \
1070         } while (0)
1071
1072 #define CHECK_STACK_UNDERFLOW(num)      \
1073         do {    \
1074                 if (cur_stack < (num))  \
1075                         ADD_INVALID (list, g_strdup_printf ("Stack underflow at 0x%04x (%d items instead of %d)", ip_offset, cur_stack, (num)));        \
1076         } while (0)
1077
1078 #define CHECK_STACK_OVERFLOW()  \
1079         do {    \
1080                 if (cur_stack >= max_stack)     \
1081                         ADD_INVALID (list, g_strdup_printf ("Maxstack exceeded at 0x%04x", ip_offset)); \
1082         } while (0)
1083
1084
1085 static int
1086 in_any_block (MonoMethodHeader *header, guint offset)
1087 {
1088         int i;
1089         MonoExceptionClause *clause;
1090
1091         for (i = 0; i < header->num_clauses; ++i) {
1092                 clause = &header->clauses [i];
1093                 if (MONO_OFFSET_IN_CLAUSE (clause, offset))
1094                         return 1;
1095                 if (MONO_OFFSET_IN_HANDLER (clause, offset))
1096                         return 1;
1097                 if (MONO_OFFSET_IN_FILTER (clause, offset))
1098                         return 1;
1099         }
1100         return 0;
1101 }
1102
1103 /*
1104  * in_any_exception_block:
1105  * 
1106  * Returns TRUE is @offset is part of any exception clause (filter, handler, catch, finally or fault).
1107  */
1108 static gboolean
1109 in_any_exception_block (MonoMethodHeader *header, guint offset)
1110 {
1111         int i;
1112         MonoExceptionClause *clause;
1113
1114         for (i = 0; i < header->num_clauses; ++i) {
1115                 clause = &header->clauses [i];
1116                 if (MONO_OFFSET_IN_HANDLER (clause, offset))
1117                         return TRUE;
1118                 if (MONO_OFFSET_IN_FILTER (clause, offset))
1119                         return TRUE;
1120         }
1121         return FALSE;
1122 }
1123
1124 /*
1125  * is_valid_branch_instruction:
1126  *
1127  * Verify if it's valid to perform a branch from @offset to @target.
1128  * This should be used with br and brtrue/false.
1129  * It returns 0 if valid, 1 for unverifiable and 2 for invalid.
1130  * The major diferent from other similiar functions is that branching into a
1131  * finally/fault block is invalid instead of just unverifiable.  
1132  */
1133 static int
1134 is_valid_branch_instruction (MonoMethodHeader *header, guint offset, guint target)
1135 {
1136         int i;
1137         MonoExceptionClause *clause;
1138
1139         for (i = 0; i < header->num_clauses; ++i) {
1140                 clause = &header->clauses [i];
1141                 /*branching into a finally block is invalid*/
1142                 if ((clause->flags == MONO_EXCEPTION_CLAUSE_FINALLY || clause->flags == MONO_EXCEPTION_CLAUSE_FAULT) &&
1143                         !MONO_OFFSET_IN_HANDLER (clause, offset) &&
1144                         MONO_OFFSET_IN_HANDLER (clause, target))
1145                         return 2;
1146
1147                 if (clause->try_offset != target && (MONO_OFFSET_IN_CLAUSE (clause, offset) ^ MONO_OFFSET_IN_CLAUSE (clause, target)))
1148                         return 1;
1149                 if (MONO_OFFSET_IN_HANDLER (clause, offset) ^ MONO_OFFSET_IN_HANDLER (clause, target))
1150                         return 1;
1151                 if (MONO_OFFSET_IN_FILTER (clause, offset) ^ MONO_OFFSET_IN_FILTER (clause, target))
1152                         return 1;
1153         }
1154         return 0;
1155 }
1156
1157 /*
1158  * is_valid_cmp_branch_instruction:
1159  * 
1160  * Verify if it's valid to perform a branch from @offset to @target.
1161  * This should be used with binary comparison branching instruction, like beq, bge and similars.
1162  * It returns 0 if valid, 1 for unverifiable and 2 for invalid.
1163  * 
1164  * The major diferences from other similar functions are that most errors lead to invalid
1165  * code and only branching out of finally, filter or fault clauses is unverifiable. 
1166  */
1167 static int
1168 is_valid_cmp_branch_instruction (MonoMethodHeader *header, guint offset, guint target)
1169 {
1170         int i;
1171         MonoExceptionClause *clause;
1172
1173         for (i = 0; i < header->num_clauses; ++i) {
1174                 clause = &header->clauses [i];
1175                 /*branching out of a handler or finally*/
1176                 if (clause->flags != MONO_EXCEPTION_CLAUSE_NONE &&
1177                         MONO_OFFSET_IN_HANDLER (clause, offset) &&
1178                         !MONO_OFFSET_IN_HANDLER (clause, target))
1179                         return 1;
1180
1181                 if (clause->try_offset != target && (MONO_OFFSET_IN_CLAUSE (clause, offset) ^ MONO_OFFSET_IN_CLAUSE (clause, target)))
1182                         return 2;
1183                 if (MONO_OFFSET_IN_HANDLER (clause, offset) ^ MONO_OFFSET_IN_HANDLER (clause, target))
1184                         return 2;
1185                 if (MONO_OFFSET_IN_FILTER (clause, offset) ^ MONO_OFFSET_IN_FILTER (clause, target))
1186                         return 2;
1187         }
1188         return 0;
1189 }
1190
1191 /*
1192  * A leave can't escape a finally block 
1193  */
1194 static int
1195 is_correct_leave (MonoMethodHeader *header, guint offset, guint target)
1196 {
1197         int i;
1198         MonoExceptionClause *clause;
1199
1200         for (i = 0; i < header->num_clauses; ++i) {
1201                 clause = &header->clauses [i];
1202                 if (clause->flags == MONO_EXCEPTION_CLAUSE_FINALLY && MONO_OFFSET_IN_HANDLER (clause, offset) && !MONO_OFFSET_IN_HANDLER (clause, target))
1203                         return 0;
1204                 if (MONO_OFFSET_IN_FILTER (clause, offset))
1205                         return 0;
1206         }
1207         return 1;
1208 }
1209
1210 /*
1211  * A rethrow can't happen outside of a catch handler.
1212  */
1213 static int
1214 is_correct_rethrow (MonoMethodHeader *header, guint offset)
1215 {
1216         int i;
1217         MonoExceptionClause *clause;
1218
1219         for (i = 0; i < header->num_clauses; ++i) {
1220                 clause = &header->clauses [i];
1221                 if (MONO_OFFSET_IN_HANDLER (clause, offset))
1222                         return 1;
1223                 if (MONO_OFFSET_IN_FILTER (clause, offset))
1224                         return 1;
1225         }
1226         return 0;
1227 }
1228
1229 /*
1230  * An endfinally can't happen outside of a finally/fault handler.
1231  */
1232 static int
1233 is_correct_endfinally (MonoMethodHeader *header, guint offset)
1234 {
1235         int i;
1236         MonoExceptionClause *clause;
1237
1238         for (i = 0; i < header->num_clauses; ++i) {
1239                 clause = &header->clauses [i];
1240                 if (MONO_OFFSET_IN_HANDLER (clause, offset) && (clause->flags == MONO_EXCEPTION_CLAUSE_FAULT || clause->flags == MONO_EXCEPTION_CLAUSE_FINALLY))
1241                         return 1;
1242         }
1243         return 0;
1244 }
1245
1246
1247 /*
1248  * An endfilter can only happens inside a filter clause.
1249  * In non-strict mode filter is allowed inside the handler clause too
1250  */
1251 static MonoExceptionClause *
1252 is_correct_endfilter (VerifyContext *ctx, guint offset)
1253 {
1254         int i;
1255         MonoExceptionClause *clause;
1256
1257         for (i = 0; i < ctx->header->num_clauses; ++i) {
1258                 clause = &ctx->header->clauses [i];
1259                 if (clause->flags != MONO_EXCEPTION_CLAUSE_FILTER)
1260                         continue;
1261                 if (MONO_OFFSET_IN_FILTER (clause, offset))
1262                         return clause;
1263                 if (!IS_STRICT_MODE (ctx) && MONO_OFFSET_IN_HANDLER (clause, offset))
1264                         return clause;
1265         }
1266         return NULL;
1267 }
1268
1269
1270 /*
1271  * Non-strict endfilter can happens inside a try block or any handler block
1272  */
1273 static int
1274 is_unverifiable_endfilter (VerifyContext *ctx, guint offset)
1275 {
1276         int i;
1277         MonoExceptionClause *clause;
1278
1279         for (i = 0; i < ctx->header->num_clauses; ++i) {
1280                 clause = &ctx->header->clauses [i];
1281                 if (MONO_OFFSET_IN_CLAUSE (clause, offset))
1282                         return 1;
1283         }
1284         return 0;
1285 }
1286
1287 static gboolean
1288 is_valid_bool_arg (ILStackDesc *arg)
1289 {
1290         if (stack_slot_is_managed_pointer (arg) || stack_slot_is_boxed_value (arg) || stack_slot_is_null_literal (arg))
1291                 return TRUE;
1292
1293
1294         switch (stack_slot_get_underlying_type (arg)) {
1295         case TYPE_I4:
1296         case TYPE_I8:
1297         case TYPE_NATIVE_INT:
1298         case TYPE_PTR:
1299                 return TRUE;
1300         case TYPE_COMPLEX:
1301                 g_assert (arg->type);
1302                 switch (arg->type->type) {
1303                 case MONO_TYPE_CLASS:
1304                 case MONO_TYPE_STRING:
1305                 case MONO_TYPE_OBJECT:
1306                 case MONO_TYPE_SZARRAY:
1307                 case MONO_TYPE_ARRAY:
1308                 case MONO_TYPE_FNPTR:
1309                 case MONO_TYPE_PTR:
1310                         return TRUE;
1311                 case MONO_TYPE_GENERICINST:
1312                         /*We need to check if the container class
1313                          * of the generic type is a valuetype, iow:
1314                          * is it a "class Foo<T>" or a "struct Foo<T>"?
1315                          */
1316                         return !arg->type->data.generic_class->container_class->valuetype;
1317                 }
1318         default:
1319                 return FALSE;
1320         }
1321 }
1322
1323
1324 /*Type manipulation helper*/
1325
1326 /*Returns the byref version of the supplied MonoType*/
1327 static MonoType*
1328 mono_type_get_type_byref (MonoType *type)
1329 {
1330         if (type->byref)
1331                 return type;
1332         return &mono_class_from_mono_type (type)->this_arg;
1333 }
1334
1335
1336 /*Returns the byval version of the supplied MonoType*/
1337 static MonoType*
1338 mono_type_get_type_byval (MonoType *type)
1339 {
1340         if (!type->byref)
1341                 return type;
1342         return &mono_class_from_mono_type (type)->byval_arg;
1343 }
1344
1345 static MonoType*
1346 mono_type_from_stack_slot (ILStackDesc *slot)
1347 {
1348         if (stack_slot_is_managed_pointer (slot))
1349                 return mono_type_get_type_byref (slot->type);
1350         return slot->type;
1351 }
1352
1353 /*Stack manipulation code*/
1354
1355 static void
1356 ensure_stack_size (ILCodeDesc *stack, int required)
1357 {
1358         int new_size = 8;
1359         ILStackDesc *tmp;
1360
1361         if (required < stack->max_size)
1362                 return;
1363
1364         /* We don't have to worry about the exponential growth since stack_copy prune unused space */
1365         new_size = MAX (8, MAX (required, stack->max_size * 2));
1366
1367         g_assert (new_size >= stack->size);
1368         g_assert (new_size >= required);
1369
1370         tmp = g_new0 (ILStackDesc, new_size);
1371         MEM_ALLOC (sizeof (ILStackDesc) * new_size);
1372
1373         if (stack->stack) {
1374                 if (stack->size)
1375                         memcpy (tmp, stack->stack, stack->size * sizeof (ILStackDesc));
1376                 g_free (stack->stack);
1377                 MEM_FREE (sizeof (ILStackDesc) * stack->max_size);
1378         }
1379
1380         stack->stack = tmp;
1381         stack->max_size = new_size;
1382 }
1383
1384 static void
1385 stack_init (VerifyContext *ctx, ILCodeDesc *state) 
1386 {
1387         if (state->flags & IL_CODE_FLAG_STACK_INITED)
1388                 return;
1389         state->size = state->max_size = 0;
1390         state->flags |= IL_CODE_FLAG_STACK_INITED;
1391 }
1392
1393 static void
1394 stack_copy (ILCodeDesc *to, ILCodeDesc *from)
1395 {
1396         ensure_stack_size (to, from->size);
1397         to->size = from->size;
1398
1399         /*stack copy happens at merge points, which have small stacks*/
1400         if (from->size)
1401                 memcpy (to->stack, from->stack, sizeof (ILStackDesc) * from->size);
1402 }
1403
1404 static void
1405 copy_stack_value (ILStackDesc *to, ILStackDesc *from)
1406 {
1407         to->stype = from->stype;
1408         to->type = from->type;
1409         to->method = from->method;
1410 }
1411
1412 static int
1413 check_underflow (VerifyContext *ctx, int size)
1414 {
1415         if (ctx->eval.size < size) {
1416                 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Stack underflow, required %d, but have %d at 0x%04x", size, ctx->eval.size, ctx->ip_offset));
1417                 return 0;
1418         }
1419         return 1;
1420 }
1421
1422 static int
1423 check_overflow (VerifyContext *ctx)
1424 {
1425         if (ctx->eval.size >= ctx->max_stack) {
1426                 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Method doesn't have stack-depth %d at 0x%04x", ctx->eval.size + 1, ctx->ip_offset));
1427                 return 0;
1428         }
1429         return 1;
1430 }
1431
1432 /*This reject out PTR, FNPTR and TYPEDBYREF*/
1433 static gboolean
1434 check_unmanaged_pointer (VerifyContext *ctx, ILStackDesc *value)
1435 {
1436         if (stack_slot_get_type (value) == TYPE_PTR) {
1437                 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Unmanaged pointer is not a verifiable type at 0x%04x", ctx->ip_offset));
1438                 return 0;
1439         }
1440         return 1;
1441 }
1442
1443 /*TODO verify if MONO_TYPE_TYPEDBYREF is not allowed here as well.*/
1444 static gboolean
1445 check_unverifiable_type (VerifyContext *ctx, MonoType *type)
1446 {
1447         if (type->type == MONO_TYPE_PTR || type->type == MONO_TYPE_FNPTR) {
1448                 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Unmanaged pointer is not a verifiable type at 0x%04x", ctx->ip_offset));
1449                 return 0;
1450         }
1451         return 1;
1452 }
1453
1454 static ILStackDesc *
1455 stack_push (VerifyContext *ctx)
1456 {
1457         g_assert (ctx->eval.size < ctx->max_stack);
1458         g_assert (ctx->eval.size <= ctx->eval.max_size);
1459
1460         ensure_stack_size (&ctx->eval, ctx->eval.size + 1);
1461
1462         return & ctx->eval.stack [ctx->eval.size++];
1463 }
1464
1465 static ILStackDesc *
1466 stack_push_val (VerifyContext *ctx, int stype, MonoType *type)
1467 {
1468         ILStackDesc *top = stack_push (ctx);
1469         top->stype = stype;
1470         top->type = type;
1471         return top;
1472 }
1473
1474 static ILStackDesc *
1475 stack_pop (VerifyContext *ctx)
1476 {
1477         ILStackDesc *ret;
1478         g_assert (ctx->eval.size > 0);  
1479         ret = ctx->eval.stack + --ctx->eval.size;
1480         if ((ret->stype & UNINIT_THIS_MASK) == UNINIT_THIS_MASK)
1481                 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Found use of uninitialized 'this ptr' ref at 0x%04x", ctx->ip_offset));
1482         return ret;
1483 }
1484
1485 /* This function allows to safely pop an unititialized this ptr from
1486  * the eval stack without marking the method as unverifiable. 
1487  */
1488 static ILStackDesc *
1489 stack_pop_safe (VerifyContext *ctx)
1490 {
1491         g_assert (ctx->eval.size > 0);
1492         return ctx->eval.stack + --ctx->eval.size;
1493 }
1494
1495 /*Positive number distance from stack top. [0] is stack top, [1] is the one below*/
1496 static ILStackDesc*
1497 stack_peek (VerifyContext *ctx, int distance)
1498 {
1499         g_assert (ctx->eval.size - distance > 0);
1500         return ctx->eval.stack + (ctx->eval.size - 1 - distance);
1501 }
1502
1503 static ILStackDesc *
1504 stack_push_stack_val (VerifyContext *ctx, ILStackDesc *value)
1505 {
1506         ILStackDesc *top = stack_push (ctx);
1507         copy_stack_value (top, value);
1508         return top;
1509 }
1510
1511 /* Returns the MonoType associated with the token, or NULL if it is invalid.
1512  * 
1513  * A boxable type can be either a reference or value type, but cannot be a byref type or an unmanaged pointer   
1514  * */
1515 static MonoType*
1516 get_boxable_mono_type (VerifyContext* ctx, int token, const char *opcode)
1517 {
1518         MonoType *type;
1519         MonoClass *class;
1520
1521         if (!(type = verifier_load_type (ctx, token, opcode)))
1522                 return NULL;
1523
1524         if (type->byref && type->type != MONO_TYPE_TYPEDBYREF) {
1525                 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid use of byref type for %s at 0x%04x", opcode, ctx->ip_offset));
1526                 return NULL;
1527         }
1528
1529         if (type->type == MONO_TYPE_VOID) {
1530                 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid use of void type for %s at 0x%04x", opcode, ctx->ip_offset));
1531                 return NULL;
1532         }
1533
1534         if (type->type == MONO_TYPE_TYPEDBYREF)
1535                 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid use of typedbyref for %s at 0x%04x", opcode, ctx->ip_offset));
1536
1537         if (!(class = mono_class_from_mono_type (type)))
1538                 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Could not retrieve type token for %s at 0x%04x", opcode, ctx->ip_offset));
1539
1540         if (class->generic_container && type->type != MONO_TYPE_GENERICINST)
1541                 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));      
1542
1543         check_unverifiable_type (ctx, type);
1544         return type;
1545 }
1546
1547
1548 /*operation result tables */
1549
1550 static const unsigned char bin_op_table [TYPE_MAX][TYPE_MAX] = {
1551         {TYPE_I4, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV},
1552         {TYPE_INV, TYPE_I8, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
1553         {TYPE_NATIVE_INT, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV},
1554         {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_R8, TYPE_INV, TYPE_INV},
1555         {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
1556         {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
1557 };
1558
1559 static const unsigned char add_table [TYPE_MAX][TYPE_MAX] = {
1560         {TYPE_I4, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV},
1561         {TYPE_INV, TYPE_I8, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
1562         {TYPE_NATIVE_INT, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV},
1563         {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_R8, TYPE_INV, TYPE_INV},
1564         {TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV, TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV, TYPE_INV, TYPE_INV},
1565         {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
1566 };
1567
1568 static const unsigned char sub_table [TYPE_MAX][TYPE_MAX] = {
1569         {TYPE_I4, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV},
1570         {TYPE_INV, TYPE_I8, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
1571         {TYPE_NATIVE_INT, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV},
1572         {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_R8, TYPE_INV, TYPE_INV},
1573         {TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV, TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV, TYPE_NATIVE_INT | NON_VERIFIABLE_RESULT, TYPE_INV},
1574         {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
1575 };
1576
1577 static const unsigned char int_bin_op_table [TYPE_MAX][TYPE_MAX] = {
1578         {TYPE_I4, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV},
1579         {TYPE_INV, TYPE_I8, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
1580         {TYPE_NATIVE_INT, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV},
1581         {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
1582         {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
1583         {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
1584 };
1585
1586 static const unsigned char shift_op_table [TYPE_MAX][TYPE_MAX] = {
1587         {TYPE_I4, TYPE_INV, TYPE_I4, TYPE_INV, TYPE_INV, TYPE_INV},
1588         {TYPE_I8, TYPE_INV, TYPE_I8, TYPE_INV, TYPE_INV, TYPE_INV},
1589         {TYPE_NATIVE_INT, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV},
1590         {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
1591         {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
1592         {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
1593 };
1594
1595 static const unsigned char cmp_br_op [TYPE_MAX][TYPE_MAX] = {
1596         {TYPE_I4, TYPE_INV, TYPE_I4, TYPE_INV, TYPE_INV, TYPE_INV},
1597         {TYPE_INV, TYPE_I4, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
1598         {TYPE_I4, TYPE_INV, TYPE_I4, TYPE_INV, TYPE_INV, TYPE_INV},
1599         {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_I4, TYPE_INV, TYPE_INV},
1600         {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_I4, TYPE_INV},
1601         {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
1602 };
1603
1604 static const unsigned char cmp_br_eq_op [TYPE_MAX][TYPE_MAX] = {
1605         {TYPE_I4, TYPE_INV, TYPE_I4, TYPE_INV, TYPE_INV, TYPE_INV},
1606         {TYPE_INV, TYPE_I4, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
1607         {TYPE_I4, TYPE_INV, TYPE_I4, TYPE_INV, TYPE_I4 | NON_VERIFIABLE_RESULT, TYPE_INV},
1608         {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_I4, TYPE_INV, TYPE_INV},
1609         {TYPE_INV, TYPE_INV, TYPE_I4 | NON_VERIFIABLE_RESULT, TYPE_INV, TYPE_I4, TYPE_INV},
1610         {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_I4},
1611 };
1612
1613 static const unsigned char add_ovf_un_table [TYPE_MAX][TYPE_MAX] = {
1614         {TYPE_I4, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV},
1615         {TYPE_INV, TYPE_I8, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
1616         {TYPE_NATIVE_INT, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV},
1617         {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
1618         {TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV, TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV, TYPE_INV, TYPE_INV},
1619         {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
1620 };
1621
1622 static const unsigned char sub_ovf_un_table [TYPE_MAX][TYPE_MAX] = {
1623         {TYPE_I4, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV},
1624         {TYPE_INV, TYPE_I8, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
1625         {TYPE_NATIVE_INT, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV},
1626         {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
1627         {TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV, TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV, TYPE_NATIVE_INT | NON_VERIFIABLE_RESULT, TYPE_INV},
1628         {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
1629 };
1630
1631 static const unsigned char bin_ovf_table [TYPE_MAX][TYPE_MAX] = {
1632         {TYPE_I4, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV},
1633         {TYPE_INV, TYPE_I8, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
1634         {TYPE_NATIVE_INT, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV},
1635         {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
1636         {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
1637         {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
1638 };
1639
1640 #ifdef MONO_VERIFIER_DEBUG
1641
1642 /*debug helpers */
1643 static void
1644 dump_stack_value (ILStackDesc *value)
1645 {
1646         printf ("[(%x)(%x)", value->type->type, value->stype);
1647
1648         if (stack_slot_is_this_pointer (value))
1649                 printf ("[this] ");
1650
1651         if (stack_slot_is_boxed_value (value))
1652                 printf ("[boxed] ");
1653
1654         if (stack_slot_is_null_literal (value))
1655                 printf ("[null] ");
1656
1657         if (stack_slot_is_managed_mutability_pointer (value))
1658                 printf ("Controled Mutability MP: ");
1659
1660         if (stack_slot_is_managed_pointer (value))
1661                 printf ("Managed Pointer to: ");
1662
1663         switch (stack_slot_get_underlying_type (value)) {
1664                 case TYPE_INV:
1665                         printf ("invalid type]"); 
1666                         return;
1667                 case TYPE_I4:
1668                         printf ("int32]"); 
1669                         return;
1670                 case TYPE_I8:
1671                         printf ("int64]"); 
1672                         return;
1673                 case TYPE_NATIVE_INT:
1674                         printf ("native int]"); 
1675                         return;
1676                 case TYPE_R8:
1677                         printf ("float64]"); 
1678                         return;
1679                 case TYPE_PTR:
1680                         printf ("unmanaged pointer]"); 
1681                         return;
1682                 case TYPE_COMPLEX:
1683                         switch (value->type->type) {
1684                         case MONO_TYPE_CLASS:
1685                         case MONO_TYPE_VALUETYPE:
1686                                 printf ("complex] (%s)", value->type->data.klass->name);
1687                                 return;
1688                         case MONO_TYPE_STRING:
1689                                 printf ("complex] (string)");
1690                                 return;
1691                         case MONO_TYPE_OBJECT:
1692                                 printf ("complex] (object)");
1693                                 return;
1694                         case MONO_TYPE_SZARRAY:
1695                                 printf ("complex] (%s [])", value->type->data.klass->name);
1696                                 return;
1697                         case MONO_TYPE_ARRAY:
1698                                 printf ("complex] (%s [%d %d %d])",
1699                                         value->type->data.array->eklass->name,
1700                                         value->type->data.array->rank,
1701                                         value->type->data.array->numsizes,
1702                                         value->type->data.array->numlobounds);
1703                                 return;
1704                         case MONO_TYPE_GENERICINST:
1705                                 printf ("complex] (inst of %s )", value->type->data.generic_class->container_class->name);
1706                                 return;
1707                         case MONO_TYPE_VAR:
1708                                 printf ("complex] (type generic param !%d - %s) ", value->type->data.generic_param->num, mono_generic_param_info (value->type->data.generic_param)->name);
1709                                 return;
1710                         case MONO_TYPE_MVAR:
1711                                 printf ("complex] (method generic param !!%d - %s) ", value->type->data.generic_param->num, mono_generic_param_info (value->type->data.generic_param)->name);
1712                                 return;
1713                         default: {
1714                                 //should be a boxed value 
1715                                 char * name = mono_type_full_name (value->type);
1716                                 printf ("complex] %s", name);
1717                                 g_free (name);
1718                                 return;
1719                                 }
1720                         }
1721                 default:
1722                         printf ("unknown stack %x type]\n", value->stype);
1723                         g_assert_not_reached ();
1724         }
1725 }
1726
1727 static void
1728 dump_stack_state (ILCodeDesc *state) 
1729 {
1730         int i;
1731
1732         printf ("(%d) ", state->size);
1733         for (i = 0; i < state->size; ++i)
1734                 dump_stack_value (state->stack + i);
1735         printf ("\n");
1736 }
1737 #endif
1738
1739 /*Returns TRUE if candidate array type can be assigned to target.
1740  *Both parameters MUST be of type MONO_TYPE_ARRAY (target->type == MONO_TYPE_ARRAY)
1741  */
1742 static gboolean
1743 is_array_type_compatible (MonoType *target, MonoType *candidate)
1744 {
1745         MonoArrayType *left = target->data.array;
1746         MonoArrayType *right = candidate->data.array;
1747
1748         g_assert (target->type == MONO_TYPE_ARRAY);
1749         g_assert (candidate->type == MONO_TYPE_ARRAY);
1750
1751         if (left->rank != right->rank)
1752                 return FALSE;
1753
1754         return mono_class_is_assignable_from (left->eklass, right->eklass);
1755 }
1756
1757 static int
1758 get_stack_type (MonoType *type)
1759 {
1760         int mask = 0;
1761         int type_kind = type->type;
1762         if (type->byref)
1763                 mask = POINTER_MASK;
1764         /*TODO handle CMMP_MASK */
1765
1766 handle_enum:
1767         switch (type_kind) {
1768         case MONO_TYPE_I1:
1769         case MONO_TYPE_U1:
1770         case MONO_TYPE_BOOLEAN:
1771         case MONO_TYPE_I2:
1772         case MONO_TYPE_U2:
1773         case MONO_TYPE_CHAR:
1774         case MONO_TYPE_I4:
1775         case MONO_TYPE_U4:
1776                 return TYPE_I4 | mask;
1777
1778         case MONO_TYPE_I:
1779         case MONO_TYPE_U:
1780                 return TYPE_NATIVE_INT | mask;
1781
1782         /* FIXME: the spec says that you cannot have a pointer to method pointer, do we need to check this here? */ 
1783         case MONO_TYPE_FNPTR:
1784         case MONO_TYPE_PTR:
1785         case MONO_TYPE_TYPEDBYREF:
1786                 return TYPE_PTR | mask;
1787
1788         case MONO_TYPE_VAR:
1789         case MONO_TYPE_MVAR:
1790
1791         case MONO_TYPE_CLASS:
1792         case MONO_TYPE_STRING:
1793         case MONO_TYPE_OBJECT:
1794         case MONO_TYPE_SZARRAY:
1795         case MONO_TYPE_ARRAY:
1796                 return TYPE_COMPLEX | mask;
1797
1798         case MONO_TYPE_I8:
1799         case MONO_TYPE_U8:
1800                 return TYPE_I8 | mask;
1801
1802         case MONO_TYPE_R4:
1803         case MONO_TYPE_R8:
1804                 return TYPE_R8 | mask;
1805
1806         case MONO_TYPE_GENERICINST:
1807         case MONO_TYPE_VALUETYPE:
1808                 if (mono_type_is_enum_type (type)) {
1809                         type = mono_type_get_underlying_type_any (type);
1810                         if (!type)
1811                                 return FALSE;
1812                         type_kind = type->type;
1813                         goto handle_enum;
1814                 } else {
1815                         return TYPE_COMPLEX | mask;
1816                 }
1817
1818         default:
1819                 return TYPE_INV;
1820         }
1821 }
1822
1823 /* convert MonoType to ILStackDesc format (stype) */
1824 static gboolean
1825 set_stack_value (VerifyContext *ctx, ILStackDesc *stack, MonoType *type, int take_addr)
1826 {
1827         int mask = 0;
1828         int type_kind = type->type;
1829
1830         if (type->byref || take_addr)
1831                 mask = POINTER_MASK;
1832         /* TODO handle CMMP_MASK */
1833
1834 handle_enum:
1835         stack->type = type;
1836
1837         switch (type_kind) {
1838         case MONO_TYPE_I1:
1839         case MONO_TYPE_U1:
1840         case MONO_TYPE_BOOLEAN:
1841         case MONO_TYPE_I2:
1842         case MONO_TYPE_U2:
1843         case MONO_TYPE_CHAR:
1844         case MONO_TYPE_I4:
1845         case MONO_TYPE_U4:
1846                 stack->stype = TYPE_I4 | mask;
1847                 break;
1848         case MONO_TYPE_I:
1849         case MONO_TYPE_U:
1850                 stack->stype = TYPE_NATIVE_INT | mask;
1851                 break;
1852
1853         /*FIXME: Do we need to check if it's a pointer to the method pointer? The spec says it' illegal to have that.*/
1854         case MONO_TYPE_FNPTR:
1855         case MONO_TYPE_PTR:
1856         case MONO_TYPE_TYPEDBYREF:
1857                 stack->stype = TYPE_PTR | mask;
1858                 break;
1859
1860         case MONO_TYPE_CLASS:
1861         case MONO_TYPE_STRING:
1862         case MONO_TYPE_OBJECT:
1863         case MONO_TYPE_SZARRAY:
1864         case MONO_TYPE_ARRAY:
1865
1866         case MONO_TYPE_VAR:
1867         case MONO_TYPE_MVAR: 
1868                 stack->stype = TYPE_COMPLEX | mask;
1869                 break;
1870                 
1871         case MONO_TYPE_I8:
1872         case MONO_TYPE_U8:
1873                 stack->stype = TYPE_I8 | mask;
1874                 break;
1875         case MONO_TYPE_R4:
1876         case MONO_TYPE_R8:
1877                 stack->stype = TYPE_R8 | mask;
1878                 break;
1879         case MONO_TYPE_GENERICINST:
1880         case MONO_TYPE_VALUETYPE:
1881                 if (mono_type_is_enum_type (type)) {
1882                         MonoType *utype = mono_type_get_underlying_type_any (type);
1883                         if (!utype) {
1884                                 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Could not resolve underlying type of %x at %d", type->type, ctx->ip_offset));
1885                                 return FALSE;
1886                         }
1887                         type = utype;
1888                         type_kind = type->type;
1889                         goto handle_enum;
1890                 } else {
1891                         stack->stype = TYPE_COMPLEX | mask;
1892                         break;
1893                 }
1894         default:
1895                 VERIFIER_DEBUG ( printf ("unknown type 0x%02x in eval stack type\n", type->type); );
1896                 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Illegal value set on stack 0x%02x at %d", type->type, ctx->ip_offset));
1897                 return FALSE;
1898         }
1899         return TRUE;
1900 }
1901
1902 /* 
1903  * init_stack_with_value_at_exception_boundary:
1904  * 
1905  * Initialize the stack and push a given type.
1906  * The instruction is marked as been on the exception boundary.
1907  */
1908 static void
1909 init_stack_with_value_at_exception_boundary (VerifyContext *ctx, ILCodeDesc *code, MonoClass *klass)
1910 {
1911         MonoError error;
1912         MonoType *type = mono_class_inflate_generic_type_checked (&klass->byval_arg, ctx->generic_context, &error);
1913
1914         if (!mono_error_ok (&error)) {
1915                 char *name = mono_type_get_full_name (klass);
1916                 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid class %s used for exception", name));
1917                 g_free (name);
1918                 mono_error_cleanup (&error);
1919                 return;
1920         }
1921
1922         if (!ctx->max_stack) {
1923                 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Stack overflow at 0x%04x", ctx->ip_offset));
1924                 return;
1925         }
1926
1927         stack_init (ctx, code);
1928         ensure_stack_size (code, 1);
1929         set_stack_value (ctx, code->stack, type, FALSE);
1930         ctx->exception_types = g_slist_prepend (ctx->exception_types, type);
1931         code->size = 1;
1932         code->flags |= IL_CODE_FLAG_WAS_TARGET;
1933         if (mono_type_is_generic_argument (type))
1934                 code->stack->stype |= BOXED_MASK;
1935 }
1936
1937 /*Verify if type 'candidate' can be stored in type 'target'.
1938  * 
1939  * If strict, check for the underlying type and not the verification stack types
1940  */
1941 static gboolean
1942 verify_type_compatibility_full (VerifyContext *ctx, MonoType *target, MonoType *candidate, gboolean strict)
1943 {
1944 #define IS_ONE_OF3(T, A, B, C) (T == A || T == B || T == C)
1945 #define IS_ONE_OF2(T, A, B) (T == A || T == B)
1946
1947         MonoType *original_candidate = candidate;
1948         VERIFIER_DEBUG ( printf ("checking type compatibility %s x %s strict %d\n", mono_type_full_name (target), mono_type_full_name (candidate), strict); );
1949
1950         /*only one is byref */
1951         if (candidate->byref ^ target->byref) {
1952                 /* converting from native int to byref*/
1953                 if (get_stack_type (candidate) == TYPE_NATIVE_INT && target->byref) {
1954                         CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("using byref native int at 0x%04x", ctx->ip_offset));
1955                         return TRUE;
1956                 }
1957                 return FALSE;
1958         }
1959         strict |= target->byref;
1960         /*From now on we don't care about byref anymore, so it's ok to discard it here*/
1961         candidate = mono_type_get_underlying_type_any (candidate);
1962
1963 handle_enum:
1964         switch (target->type) {
1965         case MONO_TYPE_VOID:
1966                 return candidate->type == MONO_TYPE_VOID;
1967         case MONO_TYPE_I1:
1968         case MONO_TYPE_U1:
1969         case MONO_TYPE_BOOLEAN:
1970                 if (strict)
1971                         return IS_ONE_OF3 (candidate->type, MONO_TYPE_I1, MONO_TYPE_U1, MONO_TYPE_BOOLEAN);
1972         case MONO_TYPE_I2:
1973         case MONO_TYPE_U2:
1974         case MONO_TYPE_CHAR:
1975                 if (strict)
1976                         return IS_ONE_OF3 (candidate->type, MONO_TYPE_I2, MONO_TYPE_U2, MONO_TYPE_CHAR);
1977         case MONO_TYPE_I4:
1978         case MONO_TYPE_U4: {
1979                 gboolean is_native_int = IS_ONE_OF2 (candidate->type, MONO_TYPE_I, MONO_TYPE_U);
1980                 gboolean is_int4 = IS_ONE_OF2 (candidate->type, MONO_TYPE_I4, MONO_TYPE_U4);
1981                 if (strict)
1982                         return is_native_int || is_int4;
1983                 return is_native_int || get_stack_type (candidate) == TYPE_I4;
1984         }
1985
1986         case MONO_TYPE_I8:
1987         case MONO_TYPE_U8:
1988                 return IS_ONE_OF2 (candidate->type, MONO_TYPE_I8, MONO_TYPE_U8);
1989
1990         case MONO_TYPE_R4:
1991         case MONO_TYPE_R8:
1992                 if (strict)
1993                         return candidate->type == target->type;
1994                 return IS_ONE_OF2 (candidate->type, MONO_TYPE_R4, MONO_TYPE_R8);
1995
1996         case MONO_TYPE_I:
1997         case MONO_TYPE_U: {
1998                 gboolean is_native_int = IS_ONE_OF2 (candidate->type, MONO_TYPE_I, MONO_TYPE_U);
1999                 gboolean is_int4 = IS_ONE_OF2 (candidate->type, MONO_TYPE_I4, MONO_TYPE_U4);
2000                 if (strict)
2001                         return is_native_int || is_int4;
2002                 return is_native_int || get_stack_type (candidate) == TYPE_I4;
2003         }
2004
2005         case MONO_TYPE_PTR:
2006                 if (candidate->type != MONO_TYPE_PTR)
2007                         return FALSE;
2008                 /* check the underlying type */
2009                 return verify_type_compatibility_full (ctx, target->data.type, candidate->data.type, TRUE);
2010
2011         case MONO_TYPE_FNPTR: {
2012                 MonoMethodSignature *left, *right;
2013                 if (candidate->type != MONO_TYPE_FNPTR)
2014                         return FALSE;
2015
2016                 left = mono_type_get_signature (target);
2017                 right = mono_type_get_signature (candidate);
2018                 return mono_metadata_signature_equal (left, right) && left->call_convention == right->call_convention;
2019         }
2020
2021         case MONO_TYPE_GENERICINST: {
2022                 MonoClass *target_klass;
2023                 MonoClass *candidate_klass;
2024                 if (mono_type_is_enum_type (target)) {
2025                         target = mono_type_get_underlying_type_any (target);
2026                         if (!target)
2027                                 return FALSE;
2028                         goto handle_enum;
2029                 }
2030                 /*
2031                  * VAR / MVAR compatibility must be checked by verify_stack_type_compatibility
2032                  * to take boxing status into account.
2033                  */
2034                 if (mono_type_is_generic_argument (original_candidate))
2035                         return FALSE;
2036
2037                 target_klass = mono_class_from_mono_type (target);
2038                 candidate_klass = mono_class_from_mono_type (candidate);
2039                 if (mono_class_is_nullable (target_klass)) {
2040                         if (!mono_class_is_nullable (candidate_klass))
2041                                 return FALSE;
2042                         return target_klass == candidate_klass;
2043                 }
2044                 
2045                 return mono_class_is_assignable_from (target_klass, candidate_klass);
2046         }
2047
2048         case MONO_TYPE_STRING:
2049                 return candidate->type == MONO_TYPE_STRING;
2050
2051         case MONO_TYPE_CLASS:
2052                 /*
2053                  * VAR / MVAR compatibility must be checked by verify_stack_type_compatibility
2054                  * to take boxing status into account.
2055                  */
2056                 if (mono_type_is_generic_argument (original_candidate))
2057                         return FALSE;
2058
2059                 if (candidate->type == MONO_TYPE_VALUETYPE)
2060                         return FALSE;
2061
2062                 /* If candidate is an enum it should return true for System.Enum and supertypes.
2063                  * That's why here we use the original type and not the underlying type.
2064                  */ 
2065                 return mono_class_is_assignable_from (target->data.klass, mono_class_from_mono_type (original_candidate));
2066
2067         case MONO_TYPE_OBJECT:
2068                 return MONO_TYPE_IS_REFERENCE (candidate);
2069
2070         case MONO_TYPE_SZARRAY: {
2071                 MonoClass *left;
2072                 MonoClass *right;
2073                 if (candidate->type != MONO_TYPE_SZARRAY)
2074                         return FALSE;
2075
2076                 left = mono_class_from_mono_type (target);
2077                 right = mono_class_from_mono_type (candidate);
2078
2079                 return mono_class_is_assignable_from (left, right);
2080         }
2081
2082         case MONO_TYPE_ARRAY:
2083                 if (candidate->type != MONO_TYPE_ARRAY)
2084                         return FALSE;
2085                 return is_array_type_compatible (target, candidate);
2086
2087         case MONO_TYPE_TYPEDBYREF:
2088                 return candidate->type == MONO_TYPE_TYPEDBYREF;
2089
2090         case MONO_TYPE_VALUETYPE: {
2091                 MonoClass *target_klass;
2092                 MonoClass *candidate_klass;
2093
2094                 if (candidate->type == MONO_TYPE_CLASS)
2095                         return FALSE;
2096
2097                 target_klass = mono_class_from_mono_type (target);
2098                 candidate_klass = mono_class_from_mono_type (candidate);
2099                 if (target_klass == candidate_klass)
2100                         return TRUE;
2101                 if (mono_type_is_enum_type (target)) {
2102                         target = mono_type_get_underlying_type_any (target);
2103                         if (!target)
2104                                 return FALSE;
2105                         goto handle_enum;
2106                 }
2107                 return FALSE;
2108         }
2109
2110         case MONO_TYPE_VAR:
2111                 if (candidate->type != MONO_TYPE_VAR)
2112                         return FALSE;
2113                 return mono_type_get_generic_param_num (candidate) == mono_type_get_generic_param_num (target);
2114
2115         case MONO_TYPE_MVAR:
2116                 if (candidate->type != MONO_TYPE_MVAR)
2117                         return FALSE;
2118                 return mono_type_get_generic_param_num (candidate) == mono_type_get_generic_param_num (target);
2119
2120         default:
2121                 VERIFIER_DEBUG ( printf ("unknown store type %d\n", target->type); );
2122                 g_assert_not_reached ();
2123                 return FALSE;
2124         }
2125         return 1;
2126 #undef IS_ONE_OF3
2127 #undef IS_ONE_OF2
2128 }
2129
2130 static gboolean
2131 verify_type_compatibility (VerifyContext *ctx, MonoType *target, MonoType *candidate)
2132 {
2133         return verify_type_compatibility_full (ctx, target, candidate, FALSE);
2134 }
2135
2136 /*
2137  * Returns the generic param bound to the context been verified.
2138  * 
2139  */
2140 static MonoGenericParam*
2141 get_generic_param (VerifyContext *ctx, MonoType *param) 
2142 {
2143         guint16 param_num = mono_type_get_generic_param_num (param);
2144         if (param->type == MONO_TYPE_VAR) {
2145                 if (!ctx->generic_context->class_inst || ctx->generic_context->class_inst->type_argc <= param_num) {
2146                         ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid generic type argument %d", param_num));
2147                         return NULL;
2148                 }
2149                 return ctx->generic_context->class_inst->type_argv [param_num]->data.generic_param;
2150         }
2151         
2152         /*param must be a MVAR */
2153         if (!ctx->generic_context->method_inst || ctx->generic_context->method_inst->type_argc <= param_num) {
2154                 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid generic method argument %d", param_num));
2155                 return NULL;
2156         }
2157         return ctx->generic_context->method_inst->type_argv [param_num]->data.generic_param;
2158         
2159 }
2160
2161 static gboolean
2162 recursive_boxed_constraint_type_check (VerifyContext *ctx, MonoType *type, MonoClass *constraint_class, int recursion_level)
2163 {
2164         MonoType *constraint_type = &constraint_class->byval_arg;
2165         if (recursion_level <= 0)
2166                 return FALSE;
2167
2168         if (verify_type_compatibility_full (ctx, type, mono_type_get_type_byval (constraint_type), FALSE))
2169                 return TRUE;
2170
2171         if (mono_type_is_generic_argument (constraint_type)) {
2172                 MonoGenericParam *param = get_generic_param (ctx, constraint_type);
2173                 MonoClass **class;
2174                 if (!param)
2175                         return FALSE;
2176                 for (class = mono_generic_param_info (param)->constraints; class && *class; ++class) {
2177                         if (recursive_boxed_constraint_type_check (ctx, type, *class, recursion_level - 1))
2178                                 return TRUE;
2179                 }
2180         }
2181         return FALSE;
2182 }
2183
2184 /*
2185  * is_compatible_boxed_valuetype:
2186  * 
2187  * Returns TRUE if @candidate / @stack is a valid boxed valuetype. 
2188  * 
2189  * @type The source type. It it tested to be of the proper type.    
2190  * @candidate type of the boxed valuetype.
2191  * @stack stack slot of the boxed valuetype, separate from @candidade since one could be changed before calling this function
2192  * @strict if TRUE candidate must be boxed compatible to the target type
2193  * 
2194  */
2195 static gboolean
2196 is_compatible_boxed_valuetype (VerifyContext *ctx, MonoType *type, MonoType *candidate, ILStackDesc *stack, gboolean strict)
2197 {
2198         if (!stack_slot_is_boxed_value (stack))
2199                 return FALSE;
2200         if (type->byref || candidate->byref)
2201                 return FALSE;
2202
2203         if (mono_type_is_generic_argument (candidate)) {
2204                 MonoGenericParam *param = get_generic_param (ctx, candidate);
2205                 MonoClass **class;
2206                 if (!param)
2207                         return FALSE;
2208
2209                 for (class = mono_generic_param_info (param)->constraints; class && *class; ++class) {
2210                         /*256 should be enough since there can't be more than 255 generic arguments.*/
2211                         if (recursive_boxed_constraint_type_check (ctx, type, *class, 256))
2212                                 return TRUE;
2213                 }
2214         }
2215
2216         if (mono_type_is_generic_argument (type))
2217                 return FALSE;
2218
2219         if (!strict)
2220                 return TRUE;
2221
2222         return MONO_TYPE_IS_REFERENCE (type) && mono_class_is_assignable_from (mono_class_from_mono_type (type), mono_class_from_mono_type (candidate));
2223 }
2224
2225 static int
2226 verify_stack_type_compatibility_full (VerifyContext *ctx, MonoType *type, ILStackDesc *stack, gboolean drop_byref, gboolean valuetype_must_be_boxed)
2227 {
2228         MonoType *candidate = mono_type_from_stack_slot (stack);
2229         if (MONO_TYPE_IS_REFERENCE (type) && !type->byref && stack_slot_is_null_literal (stack))
2230                 return TRUE;
2231
2232         if (is_compatible_boxed_valuetype (ctx, type, candidate, stack, TRUE))
2233                 return TRUE;
2234
2235         if (valuetype_must_be_boxed && !stack_slot_is_boxed_value (stack) && !MONO_TYPE_IS_REFERENCE (candidate))
2236                 return FALSE;
2237
2238         if (!valuetype_must_be_boxed && stack_slot_is_boxed_value (stack))
2239                 return FALSE;
2240
2241         if (drop_byref)
2242                 return verify_type_compatibility_full (ctx, type, mono_type_get_type_byval (candidate), FALSE);
2243
2244         return verify_type_compatibility_full (ctx, type, candidate, FALSE);
2245 }
2246
2247 static int
2248 verify_stack_type_compatibility (VerifyContext *ctx, MonoType *type, ILStackDesc *stack)
2249 {
2250         return verify_stack_type_compatibility_full (ctx, type, stack, FALSE, FALSE);
2251 }
2252
2253 static gboolean
2254 mono_delegate_type_equal (MonoType *target, MonoType *candidate)
2255 {
2256         if (candidate->byref ^ target->byref)
2257                 return FALSE;
2258
2259         switch (target->type) {
2260         case MONO_TYPE_VOID:
2261         case MONO_TYPE_I1:
2262         case MONO_TYPE_U1:
2263         case MONO_TYPE_BOOLEAN:
2264         case MONO_TYPE_I2:
2265         case MONO_TYPE_U2:
2266         case MONO_TYPE_CHAR:
2267         case MONO_TYPE_I4:
2268         case MONO_TYPE_U4:
2269         case MONO_TYPE_I8:
2270         case MONO_TYPE_U8:
2271         case MONO_TYPE_R4:
2272         case MONO_TYPE_R8:
2273         case MONO_TYPE_I:
2274         case MONO_TYPE_U:
2275         case MONO_TYPE_STRING:
2276         case MONO_TYPE_TYPEDBYREF:
2277                 return candidate->type == target->type;
2278
2279         case MONO_TYPE_PTR:
2280                 return mono_delegate_type_equal (target->data.type, candidate->data.type);
2281
2282         case MONO_TYPE_FNPTR:
2283                 if (candidate->type != MONO_TYPE_FNPTR)
2284                         return FALSE;
2285                 return mono_delegate_signature_equal (mono_type_get_signature (target), mono_type_get_signature (candidate), FALSE);
2286
2287         case MONO_TYPE_GENERICINST: {
2288                 MonoClass *target_klass;
2289                 MonoClass *candidate_klass;
2290                 target_klass = mono_class_from_mono_type (target);
2291                 candidate_klass = mono_class_from_mono_type (candidate);
2292                 /*FIXME handle nullables and enum*/
2293                 return mono_class_is_assignable_from (target_klass, candidate_klass);
2294         }
2295         case MONO_TYPE_OBJECT:
2296                 return MONO_TYPE_IS_REFERENCE (candidate);
2297
2298         case MONO_TYPE_CLASS:
2299                 return mono_class_is_assignable_from(target->data.klass, mono_class_from_mono_type (candidate));
2300
2301         case MONO_TYPE_SZARRAY:
2302                 if (candidate->type != MONO_TYPE_SZARRAY)
2303                         return FALSE;
2304                 return mono_class_is_assignable_from (mono_class_from_mono_type (target)->element_class, mono_class_from_mono_type (candidate)->element_class);
2305
2306         case MONO_TYPE_ARRAY:
2307                 if (candidate->type != MONO_TYPE_ARRAY)
2308                         return FALSE;
2309                 return is_array_type_compatible (target, candidate);
2310
2311         case MONO_TYPE_VALUETYPE:
2312                 /*FIXME handle nullables and enum*/
2313                 return mono_class_from_mono_type (candidate) == mono_class_from_mono_type (target);
2314
2315         case MONO_TYPE_VAR:
2316                 return candidate->type == MONO_TYPE_VAR && mono_type_get_generic_param_num (target) == mono_type_get_generic_param_num (candidate);
2317                 return FALSE;
2318
2319         case MONO_TYPE_MVAR:
2320                 return candidate->type == MONO_TYPE_MVAR && mono_type_get_generic_param_num (target) == mono_type_get_generic_param_num (candidate);
2321                 return FALSE;
2322
2323         default:
2324                 VERIFIER_DEBUG ( printf ("Unknown type %d. Implement me!\n", target->type); );
2325                 g_assert_not_reached ();
2326                 return FALSE;
2327         }
2328 }
2329
2330 static gboolean
2331 mono_delegate_param_equal (MonoType *delegate, MonoType *method)
2332 {
2333         if (mono_metadata_type_equal_full (delegate, method, TRUE))
2334                 return TRUE;
2335
2336         return mono_delegate_type_equal (method, delegate);
2337 }
2338
2339 static gboolean
2340 mono_delegate_ret_equal (MonoType *delegate, MonoType *method)
2341 {
2342         if (mono_metadata_type_equal_full (delegate, method, TRUE))
2343                 return TRUE;
2344
2345         return mono_delegate_type_equal (delegate, method);
2346 }
2347
2348 /*
2349  * mono_delegate_signature_equal:
2350  * 
2351  * Compare two signatures in the way expected by delegates.
2352  * 
2353  * This function only exists due to the fact that it should ignore the 'has_this' part of the signature.
2354  *
2355  * FIXME can this function be eliminated and proper metadata functionality be used?
2356  */
2357 static gboolean
2358 mono_delegate_signature_equal (MonoMethodSignature *delegate_sig, MonoMethodSignature *method_sig, gboolean is_static_ldftn)
2359 {
2360         int i;
2361         int method_offset = is_static_ldftn ? 1 : 0;
2362
2363         if (delegate_sig->param_count + method_offset != method_sig->param_count) 
2364                 return FALSE;
2365
2366         if (delegate_sig->call_convention != method_sig->call_convention)
2367                 return FALSE;
2368
2369         for (i = 0; i < delegate_sig->param_count; i++) { 
2370                 MonoType *p1 = delegate_sig->params [i];
2371                 MonoType *p2 = method_sig->params [i + method_offset];
2372
2373                 if (!mono_delegate_param_equal (p1, p2))
2374                         return FALSE;
2375         }
2376
2377         if (!mono_delegate_ret_equal (delegate_sig->ret, method_sig->ret))
2378                 return FALSE;
2379
2380         return TRUE;
2381 }
2382
2383 /* 
2384  * verify_ldftn_delegate:
2385  * 
2386  * Verify properties of ldftn based delegates.
2387  */
2388 static void
2389 verify_ldftn_delegate (VerifyContext *ctx, MonoClass *delegate, ILStackDesc *value, ILStackDesc *funptr)
2390 {
2391         MonoMethod *method = funptr->method;
2392
2393         /*ldftn non-final virtuals only allowed if method is not static,
2394          * the object is a this arg (comes from a ldarg.0), and there is no starg.0.
2395          * This rules doesn't apply if the object on stack is a boxed valuetype.
2396          */
2397         if ((method->flags & METHOD_ATTRIBUTE_VIRTUAL) && !(method->flags & METHOD_ATTRIBUTE_FINAL) && !(method->klass->flags & TYPE_ATTRIBUTE_SEALED) && !stack_slot_is_boxed_value (value)) {
2398                 /*A stdarg 0 must not happen, we fail here only in fail fast mode to avoid double error reports*/
2399                 if (IS_FAIL_FAST_MODE (ctx) && ctx->has_this_store)
2400                         CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid ldftn with virtual function in method with stdarg 0 at  0x%04x", ctx->ip_offset));
2401
2402                 /*current method must not be static*/
2403                 if (ctx->method->flags & METHOD_ATTRIBUTE_STATIC)
2404                         CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid ldftn with virtual function at 0x%04x", ctx->ip_offset));
2405
2406                 /*value is the this pointer, loaded using ldarg.0 */
2407                 if (!stack_slot_is_this_pointer (value))
2408                         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));
2409
2410                 ctx->code [ctx->ip_offset].flags |= IL_CODE_LDFTN_DELEGATE_NONFINAL_VIRTUAL;
2411         }
2412 }
2413
2414 /*
2415  * verify_delegate_compatibility:
2416  * 
2417  * Verify delegate creation sequence.
2418  * 
2419  */
2420 static void
2421 verify_delegate_compatibility (VerifyContext *ctx, MonoClass *delegate, ILStackDesc *value, ILStackDesc *funptr)
2422 {
2423 #define IS_VALID_OPCODE(offset, opcode) (ip [ip_offset - offset] == opcode && (ctx->code [ip_offset - offset].flags & IL_CODE_FLAG_SEEN))
2424 #define IS_LOAD_FUN_PTR(kind) (IS_VALID_OPCODE (6, CEE_PREFIX1) && ip [ip_offset - 5] == kind)
2425
2426         MonoMethod *invoke, *method;
2427         const guint8 *ip = ctx->header->code;
2428         guint32 ip_offset = ctx->ip_offset;
2429         gboolean is_static_ldftn = FALSE, is_first_arg_bound = FALSE;
2430         
2431         if (stack_slot_get_type (funptr) != TYPE_PTR || !funptr->method) {
2432                 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid function pointer parameter for delegate constructor at 0x%04x", ctx->ip_offset));
2433                 return;
2434         }
2435         
2436         invoke = mono_get_delegate_invoke (delegate);
2437         method = funptr->method;
2438
2439         if (!method || !mono_method_signature (method)) {
2440                 char *name = mono_type_get_full_name (delegate);
2441                 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid method on stack to create delegate %s construction at 0x%04x", name, ctx->ip_offset));
2442                 g_free (name);
2443                 return;
2444         }
2445
2446         if (!invoke || !mono_method_signature (invoke)) {
2447                 char *name = mono_type_get_full_name (delegate);
2448                 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Delegate type %s with bad Invoke method at 0x%04x", name, ctx->ip_offset));
2449                 g_free (name);
2450                 return;
2451         }
2452
2453         is_static_ldftn = (ip_offset > 5 && IS_LOAD_FUN_PTR (CEE_LDFTN)) && method->flags & METHOD_ATTRIBUTE_STATIC;
2454
2455         if (is_static_ldftn)
2456                 is_first_arg_bound = mono_method_signature (invoke)->param_count + 1 ==  mono_method_signature (method)->param_count;
2457
2458         if (!mono_delegate_signature_equal (mono_method_signature (invoke), mono_method_signature (method), is_first_arg_bound)) {
2459                 char *fun_sig = mono_signature_get_desc (mono_method_signature (method), FALSE);
2460                 char *invoke_sig = mono_signature_get_desc (mono_method_signature (invoke), FALSE);
2461                 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));
2462                 g_free (fun_sig);
2463                 g_free (invoke_sig);
2464         }
2465
2466         /* 
2467          * Delegate code sequences:
2468          * [-6] ldftn token
2469          * newobj ...
2470          * 
2471          * 
2472          * [-7] dup
2473          * [-6] ldvirtftn token
2474          * newobj ...
2475          * 
2476          * ldftn sequence:*/
2477         if (ip_offset > 5 && IS_LOAD_FUN_PTR (CEE_LDFTN)) {
2478                 verify_ldftn_delegate (ctx, delegate, value, funptr);
2479         } else if (ip_offset > 6 && IS_VALID_OPCODE (7, CEE_DUP) && IS_LOAD_FUN_PTR (CEE_LDVIRTFTN)) {
2480                 ctx->code [ip_offset - 6].flags |= IL_CODE_DELEGATE_SEQUENCE;   
2481         }else {
2482                 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid code sequence for delegate creation at 0x%04x", ctx->ip_offset));
2483         }
2484         ctx->code [ip_offset].flags |= IL_CODE_DELEGATE_SEQUENCE;
2485
2486         //general tests
2487         if (is_first_arg_bound) {
2488                 if (mono_method_signature (method)->param_count == 0 || !verify_stack_type_compatibility_full (ctx, mono_method_signature (method)->params [0], value, FALSE, TRUE))
2489                         CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("This object not compatible with function pointer for delegate creation at 0x%04x", ctx->ip_offset));
2490         } else {
2491                 if (method->flags & METHOD_ATTRIBUTE_STATIC) {
2492                         if (!stack_slot_is_null_literal (value) && !is_first_arg_bound)
2493                                 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Non-null this args used with static function for delegate creation at 0x%04x", ctx->ip_offset));
2494                 } else {
2495                         if (!verify_stack_type_compatibility_full (ctx, &method->klass->byval_arg, value, FALSE, TRUE) && !stack_slot_is_null_literal (value))
2496                                 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("This object not compatible with function pointer for delegate creation at 0x%04x", ctx->ip_offset));
2497                 }
2498         }
2499
2500         if (stack_slot_get_type (value) != TYPE_COMPLEX)
2501                 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid first parameter for delegate creation at 0x%04x", ctx->ip_offset));
2502
2503 #undef IS_VALID_OPCODE
2504 #undef IS_LOAD_FUN_PTR
2505 }
2506
2507 /* implement the opcode checks*/
2508 static void
2509 push_arg (VerifyContext *ctx, unsigned int arg, int take_addr) 
2510 {
2511         ILStackDesc *top;
2512
2513         if (arg >= ctx->max_args) {
2514                 if (take_addr) 
2515                         ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Method doesn't have argument %d", arg + 1));
2516                 else {
2517                         CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Method doesn't have argument %d", arg + 1));
2518                         if (check_overflow (ctx)) //FIXME: what sane value could we ever push?
2519                                 stack_push_val (ctx, TYPE_I4, &mono_defaults.int32_class->byval_arg);
2520                 }
2521         } else if (check_overflow (ctx)) {
2522                 /*We must let the value be pushed, otherwise we would get an underflow error*/
2523                 check_unverifiable_type (ctx, ctx->params [arg]);
2524                 if (ctx->params [arg]->byref && take_addr)
2525                         CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("ByRef of ByRef at 0x%04x", ctx->ip_offset));
2526                 top = stack_push (ctx);
2527                 if (!set_stack_value (ctx, top, ctx->params [arg], take_addr))
2528                         return;
2529
2530                 if (arg == 0 && !(ctx->method->flags & METHOD_ATTRIBUTE_STATIC)) {
2531                         if (take_addr)
2532                                 ctx->has_this_store = TRUE;
2533                         else
2534                                 top->stype |= THIS_POINTER_MASK;
2535                         if (mono_method_is_constructor (ctx->method) && !ctx->super_ctor_called && !ctx->method->klass->valuetype)
2536                                 top->stype |= UNINIT_THIS_MASK;
2537                 }
2538         } 
2539 }
2540
2541 static void
2542 push_local (VerifyContext *ctx, guint32 arg, int take_addr) 
2543 {
2544         if (arg >= ctx->num_locals) {
2545                 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Method doesn't have local %d", arg + 1));
2546         } else if (check_overflow (ctx)) {
2547                 /*We must let the value be pushed, otherwise we would get an underflow error*/
2548                 check_unverifiable_type (ctx, ctx->locals [arg]);
2549                 if (ctx->locals [arg]->byref && take_addr)
2550                         CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("ByRef of ByRef at 0x%04x", ctx->ip_offset));
2551
2552                 set_stack_value (ctx, stack_push (ctx), ctx->locals [arg], take_addr);
2553         } 
2554 }
2555
2556 static void
2557 store_arg (VerifyContext *ctx, guint32 arg)
2558 {
2559         ILStackDesc *value;
2560
2561         if (arg >= ctx->max_args) {
2562                 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Method doesn't have argument %d at 0x%04x", arg + 1, ctx->ip_offset));
2563                 if (check_underflow (ctx, 1))
2564                         stack_pop (ctx);
2565                 return;
2566         }
2567
2568         if (check_underflow (ctx, 1)) {
2569                 value = stack_pop (ctx);
2570                 if (!verify_stack_type_compatibility (ctx, ctx->params [arg], value)) {
2571                         CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Incompatible type %s in argument store at 0x%04x", stack_slot_get_name (value), ctx->ip_offset));
2572                 }
2573         }
2574         if (arg == 0 && !(ctx->method->flags & METHOD_ATTRIBUTE_STATIC))
2575                 ctx->has_this_store = 1;
2576 }
2577
2578 static void
2579 store_local (VerifyContext *ctx, guint32 arg)
2580 {
2581         ILStackDesc *value;
2582         if (arg >= ctx->num_locals) {
2583                 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Method doesn't have local var %d at 0x%04x", arg + 1, ctx->ip_offset));
2584                 return;
2585         }
2586
2587         /*TODO verify definite assigment */             
2588         if (check_underflow (ctx, 1)) {
2589                 value = stack_pop(ctx);
2590                 if (!verify_stack_type_compatibility (ctx, ctx->locals [arg], value)) {
2591                         char *expected = mono_type_full_name (ctx->locals [arg]);
2592                         char *found = stack_slot_full_name (value);
2593                         CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Incompatible type '%s' on stack cannot be stored to local %d with type '%s' at 0x%04x",
2594                                         found,
2595                                         arg,
2596                                         expected,
2597                                         ctx->ip_offset));
2598                         g_free (expected);
2599                         g_free (found); 
2600                 }
2601         }
2602 }
2603
2604 /*FIXME add and sub needs special care here*/
2605 static void
2606 do_binop (VerifyContext *ctx, unsigned int opcode, const unsigned char table [TYPE_MAX][TYPE_MAX])
2607 {
2608         ILStackDesc *a, *b, *top;
2609         int idxa, idxb, complexMerge = 0;
2610         unsigned char res;
2611
2612         if (!check_underflow (ctx, 2))
2613                 return;
2614         b = stack_pop (ctx);
2615         a = stack_pop (ctx);
2616
2617         idxa = stack_slot_get_underlying_type (a);
2618         if (stack_slot_is_managed_pointer (a)) {
2619                 idxa = TYPE_PTR;
2620                 complexMerge = 1;
2621         }
2622
2623         idxb = stack_slot_get_underlying_type (b);
2624         if (stack_slot_is_managed_pointer (b)) {
2625                 idxb = TYPE_PTR;
2626                 complexMerge = 2;
2627         }
2628
2629         --idxa;
2630         --idxb;
2631         res = table [idxa][idxb];
2632
2633         VERIFIER_DEBUG ( printf ("binop res %d\n", res); );
2634         VERIFIER_DEBUG ( printf ("idxa %d idxb %d\n", idxa, idxb); );
2635
2636         top = stack_push (ctx);
2637         if (res == TYPE_INV) {
2638                 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)));
2639                 copy_stack_value (top, a);
2640                 return;
2641         }
2642
2643         if (res & NON_VERIFIABLE_RESULT) {
2644                 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)));
2645
2646                 res = res & ~NON_VERIFIABLE_RESULT;
2647         }
2648
2649         if (complexMerge && res == TYPE_PTR) {
2650                 if (complexMerge == 1) 
2651                         copy_stack_value (top, a);
2652                 else if (complexMerge == 2)
2653                         copy_stack_value (top, b);
2654                 /*
2655                  * There is no need to merge the type of two pointers.
2656                  * The only valid operation is subtraction, that returns a native
2657                  *  int as result and can be used with any 2 pointer kinds.
2658                  * This is valid acording to Patition III 1.1.4
2659                  */
2660         } else
2661                 top->stype = res;
2662         
2663 }
2664
2665
2666 static void
2667 do_boolean_branch_op (VerifyContext *ctx, int delta)
2668 {
2669         int target = ctx->ip_offset + delta;
2670         ILStackDesc *top;
2671
2672         VERIFIER_DEBUG ( printf ("boolean branch offset %d delta %d target %d\n", ctx->ip_offset, delta, target); );
2673  
2674         if (target < 0 || target >= ctx->code_size) {
2675                 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Boolean branch target out of code at 0x%04x", ctx->ip_offset));
2676                 return;
2677         }
2678
2679         switch (is_valid_branch_instruction (ctx->header, ctx->ip_offset, target)) {
2680         case 1:
2681                 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Branch target escapes out of exception block at 0x%04x", ctx->ip_offset));
2682                 break;
2683         case 2:
2684                 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Branch target escapes out of exception block at 0x%04x", ctx->ip_offset));
2685                 return;
2686         }
2687
2688         ctx->target = target;
2689
2690         if (!check_underflow (ctx, 1))
2691                 return;
2692
2693         top = stack_pop (ctx);
2694         if (!is_valid_bool_arg (top))
2695                 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));
2696
2697         check_unmanaged_pointer (ctx, top);
2698 }
2699
2700 static gboolean
2701 stack_slot_is_complex_type_not_reference_type (ILStackDesc *slot)
2702 {
2703         return stack_slot_get_type (slot) == TYPE_COMPLEX && !MONO_TYPE_IS_REFERENCE (slot->type) && !stack_slot_is_boxed_value (slot);
2704 }
2705
2706 static void
2707 do_branch_op (VerifyContext *ctx, signed int delta, const unsigned char table [TYPE_MAX][TYPE_MAX])
2708 {
2709         ILStackDesc *a, *b;
2710         int idxa, idxb;
2711         unsigned char res;
2712         int target = ctx->ip_offset + delta;
2713
2714         VERIFIER_DEBUG ( printf ("branch offset %d delta %d target %d\n", ctx->ip_offset, delta, target); );
2715  
2716         if (target < 0 || target >= ctx->code_size) {
2717                 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Branch target out of code at 0x%04x", ctx->ip_offset));
2718                 return;
2719         }
2720
2721         switch (is_valid_cmp_branch_instruction (ctx->header, ctx->ip_offset, target)) {
2722         case 1: /*FIXME use constants and not magic numbers.*/
2723                 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Branch target escapes out of exception block at 0x%04x", ctx->ip_offset));
2724                 break;
2725         case 2:
2726                 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Branch target escapes out of exception block at 0x%04x", ctx->ip_offset));
2727                 return;
2728         }
2729
2730         ctx->target = target;
2731
2732         if (!check_underflow (ctx, 2))
2733                 return;
2734
2735         b = stack_pop (ctx);
2736         a = stack_pop (ctx);
2737
2738         idxa = stack_slot_get_underlying_type (a);
2739         if (stack_slot_is_managed_pointer (a))
2740                 idxa = TYPE_PTR;
2741
2742         idxb = stack_slot_get_underlying_type (b);
2743         if (stack_slot_is_managed_pointer (b))
2744                 idxb = TYPE_PTR;
2745
2746         if (stack_slot_is_complex_type_not_reference_type (a) || stack_slot_is_complex_type_not_reference_type (b)) {
2747                 res = TYPE_INV;
2748         } else {
2749                 --idxa;
2750                 --idxb;
2751                 res = table [idxa][idxb];
2752         }
2753
2754         VERIFIER_DEBUG ( printf ("branch res %d\n", res); );
2755         VERIFIER_DEBUG ( printf ("idxa %d idxb %d\n", idxa, idxb); );
2756
2757         if (res == TYPE_INV) {
2758                 CODE_NOT_VERIFIABLE (ctx,
2759                         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));
2760         } else if (res & NON_VERIFIABLE_RESULT) {
2761                         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)); 
2762                 res = res & ~NON_VERIFIABLE_RESULT;
2763         }
2764 }
2765
2766 static void
2767 do_cmp_op (VerifyContext *ctx, const unsigned char table [TYPE_MAX][TYPE_MAX], guint32 opcode)
2768 {
2769         ILStackDesc *a, *b;
2770         int idxa, idxb;
2771         unsigned char res;
2772
2773         if (!check_underflow (ctx, 2))
2774                 return;
2775         b = stack_pop (ctx);
2776         a = stack_pop (ctx);
2777
2778         if (opcode == CEE_CGT_UN) {
2779                 if (stack_slot_get_type (a) == TYPE_COMPLEX && stack_slot_get_type (b) == TYPE_COMPLEX) {
2780                         stack_push_val (ctx, TYPE_I4, &mono_defaults.int32_class->byval_arg);
2781                         return;
2782                 }
2783         }
2784
2785         idxa = stack_slot_get_underlying_type (a);
2786         if (stack_slot_is_managed_pointer (a))
2787                 idxa = TYPE_PTR;
2788
2789         idxb = stack_slot_get_underlying_type (b);
2790         if (stack_slot_is_managed_pointer (b)) 
2791                 idxb = TYPE_PTR;
2792
2793         if (stack_slot_is_complex_type_not_reference_type (a) || stack_slot_is_complex_type_not_reference_type (b)) {
2794                 res = TYPE_INV;
2795         } else {
2796                 --idxa;
2797                 --idxb;
2798                 res = table [idxa][idxb];
2799         }
2800
2801         if(res == TYPE_INV) {
2802                 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));
2803         } else if (res & NON_VERIFIABLE_RESULT) {
2804                 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)); 
2805                 res = res & ~NON_VERIFIABLE_RESULT;
2806         }
2807         stack_push_val (ctx, TYPE_I4, &mono_defaults.int32_class->byval_arg);
2808 }
2809
2810 static void
2811 do_ret (VerifyContext *ctx)
2812 {
2813         MonoType *ret = ctx->signature->ret;
2814         VERIFIER_DEBUG ( printf ("checking ret\n"); );
2815         if (ret->type != MONO_TYPE_VOID) {
2816                 ILStackDesc *top;
2817                 if (!check_underflow (ctx, 1))
2818                         return;
2819
2820                 top = stack_pop(ctx);
2821
2822                 if (!verify_stack_type_compatibility (ctx, ctx->signature->ret, top)) {
2823                         CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Incompatible return value on stack with method signature ret at 0x%04x", ctx->ip_offset));
2824                         return;
2825                 }
2826
2827                 if (ret->byref || ret->type == MONO_TYPE_TYPEDBYREF || mono_type_is_value_type (ret, "System", "ArgIterator") || mono_type_is_value_type (ret, "System", "RuntimeArgumentHandle"))
2828                         CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Method returns byref, TypedReference, ArgIterator or RuntimeArgumentHandle at 0x%04x", ctx->ip_offset));
2829         }
2830
2831         if (ctx->eval.size > 0) {
2832                 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Stack not empty (%d) after ret at 0x%04x", ctx->eval.size, ctx->ip_offset));
2833         } 
2834         if (in_any_block (ctx->header, ctx->ip_offset))
2835                 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("ret cannot escape exception blocks at 0x%04x", ctx->ip_offset));
2836 }
2837
2838 /*
2839  * 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.
2840  *      This is illegal but mono_get_method_full decoded it.
2841  * TODO handle calling .ctor outside one or calling the .ctor for other class but super  
2842  */
2843 static void
2844 do_invoke_method (VerifyContext *ctx, int method_token, gboolean virtual)
2845 {
2846         int param_count, i;
2847         MonoMethodSignature *sig;
2848         ILStackDesc *value;
2849         MonoMethod *method;
2850         gboolean virt_check_this = FALSE;
2851         gboolean constrained = ctx->prefix_set & PREFIX_CONSTRAINED;
2852
2853         if (!(method = verifier_load_method (ctx, method_token, virtual ? "callvirt" : "call")))
2854                 return;
2855
2856         if (virtual) {
2857                 CLEAR_PREFIX (ctx, PREFIX_CONSTRAINED);
2858
2859                 if (method->klass->valuetype) // && !constrained ???
2860                         CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use callvirtual with valuetype method at 0x%04x", ctx->ip_offset));
2861
2862                 if ((method->flags & METHOD_ATTRIBUTE_STATIC))
2863                         CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use callvirtual with static method at 0x%04x", ctx->ip_offset));
2864
2865         } else {
2866                 if (method->flags & METHOD_ATTRIBUTE_ABSTRACT) 
2867                         CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use call with an abstract method at 0x%04x", ctx->ip_offset));
2868                 
2869                 if ((method->flags & METHOD_ATTRIBUTE_VIRTUAL) && !(method->flags & METHOD_ATTRIBUTE_FINAL) && !(method->klass->flags & TYPE_ATTRIBUTE_SEALED)) {
2870                         virt_check_this = TRUE;
2871                         ctx->code [ctx->ip_offset].flags |= IL_CODE_CALL_NONFINAL_VIRTUAL;
2872                 }
2873         }
2874
2875         if (!(sig = mono_method_get_signature_full (method, ctx->image, method_token, ctx->generic_context)))
2876                 sig = mono_method_get_signature (method, ctx->image, method_token);
2877
2878         if (!sig) {
2879                 char *name = mono_type_get_full_name (method->klass);
2880                 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Could not resolve signature of %s:%s at 0x%04x", name, method->name, ctx->ip_offset));
2881                 g_free (name);
2882                 return;
2883         }
2884
2885         param_count = sig->param_count + sig->hasthis;
2886         if (!check_underflow (ctx, param_count))
2887                 return;
2888
2889         for (i = sig->param_count - 1; i >= 0; --i) {
2890                 VERIFIER_DEBUG ( printf ("verifying argument %d\n", i); );
2891                 value = stack_pop (ctx);
2892                 if (!verify_stack_type_compatibility (ctx, sig->params[i], value)) {
2893                         char *stack_name = stack_slot_full_name (value);
2894                         char *sig_name = mono_type_full_name (sig->params [i]);
2895                         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));
2896                         g_free (stack_name);
2897                         g_free (sig_name);
2898                 }
2899
2900                 if (stack_slot_is_managed_mutability_pointer (value))
2901                         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));
2902
2903                 if ((ctx->prefix_set & PREFIX_TAIL) && stack_slot_is_managed_pointer (value)) {
2904                         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));
2905                         return;
2906                 }
2907         }
2908
2909         if (sig->hasthis) {
2910                 MonoType *type = &method->klass->byval_arg;
2911                 ILStackDesc copy;
2912
2913                 if (mono_method_is_constructor (method) && !method->klass->valuetype) {
2914                         if (!mono_method_is_constructor (ctx->method))
2915                                 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot call a constructor outside one at 0x%04x", ctx->ip_offset));
2916                         if (method->klass != ctx->method->klass->parent && method->klass != ctx->method->klass)
2917                                 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));
2918
2919                         ctx->super_ctor_called = TRUE;
2920                         value = stack_pop_safe (ctx);
2921                         if ((value->stype & THIS_POINTER_MASK) != THIS_POINTER_MASK)
2922                                 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid 'this ptr' argument for constructor at 0x%04x", ctx->ip_offset));
2923                 } else {
2924                         value = stack_pop (ctx);
2925                 }
2926                         
2927                 copy_stack_value (&copy, value);
2928                 //TODO we should extract this to a 'drop_byref_argument' and use everywhere
2929                 //Other parts of the code suffer from the same issue of 
2930                 copy.type = mono_type_get_type_byval (copy.type);
2931                 copy.stype &= ~POINTER_MASK;
2932
2933                 if (virt_check_this && !stack_slot_is_this_pointer (value) && !(method->klass->valuetype || stack_slot_is_boxed_value (value)))
2934                         CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use the call opcode with a non-final virtual method on an object diferent thant the this pointer at 0x%04x", ctx->ip_offset));
2935
2936                 if (constrained && virtual) {
2937                         if (!stack_slot_is_managed_pointer (value))
2938                                 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Object is not a managed pointer for a constrained call at 0x%04x", ctx->ip_offset));
2939                         if (!mono_metadata_type_equal_full (mono_type_get_type_byval (value->type), ctx->constrained_type, TRUE))
2940                                 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Object not compatible with constrained type at 0x%04x", ctx->ip_offset));
2941                         copy.stype |= BOXED_MASK;
2942                 } else {
2943                         if (stack_slot_is_managed_pointer (value) && !mono_class_from_mono_type (value->type)->valuetype)
2944                                 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));
2945         
2946                         if (!virtual && mono_class_from_mono_type (value->type)->valuetype && !method->klass->valuetype && !stack_slot_is_boxed_value (value))
2947                                 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot call a valuetype baseclass at 0x%04x", ctx->ip_offset));
2948         
2949                         if (virtual && mono_class_from_mono_type (value->type)->valuetype && !stack_slot_is_boxed_value (value))
2950                                 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use a valuetype with callvirt at 0x%04x", ctx->ip_offset));
2951         
2952                         if (method->klass->valuetype && (stack_slot_is_boxed_value (value) || !stack_slot_is_managed_pointer (value)))
2953                                 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));
2954                 }
2955                 if (!verify_stack_type_compatibility (ctx, type, &copy))
2956                         CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Incompatible this argument on stack with method signature at 0x%04x", ctx->ip_offset));
2957
2958                 if (!IS_SKIP_VISIBILITY (ctx) && !mono_method_can_access_method_full (ctx->method, method, mono_class_from_mono_type (value->type))) {
2959                         char *name = mono_method_full_name (method, TRUE);
2960                         CODE_NOT_VERIFIABLE2 (ctx, g_strdup_printf ("Method %s is not accessible at 0x%04x", name, ctx->ip_offset), MONO_EXCEPTION_METHOD_ACCESS);
2961                         g_free (name);
2962                 }
2963
2964         } else if (!IS_SKIP_VISIBILITY (ctx) && !mono_method_can_access_method_full (ctx->method, method, NULL)) {
2965                 char *name = mono_method_full_name (method, TRUE);
2966                 CODE_NOT_VERIFIABLE2 (ctx, g_strdup_printf ("Method %s is not accessible at 0x%04x", name, ctx->ip_offset), MONO_EXCEPTION_METHOD_ACCESS);
2967                 g_free (name);
2968         }
2969
2970         if (sig->ret->type != MONO_TYPE_VOID) {
2971                 if (check_overflow (ctx)) {
2972                         value = stack_push (ctx);
2973                         set_stack_value (ctx, value, sig->ret, FALSE);
2974                         if ((ctx->prefix_set & PREFIX_READONLY) && method->klass->rank && !strcmp (method->name, "Address")) {
2975                                 ctx->prefix_set &= ~PREFIX_READONLY;
2976                                 value->stype |= CMMP_MASK;
2977                         }
2978                 }
2979         }
2980
2981         if ((ctx->prefix_set & PREFIX_TAIL)) {
2982                 if (!mono_delegate_ret_equal (mono_method_signature (ctx->method)->ret, sig->ret))
2983                         CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Tail call with incompatible return type at 0x%04x", ctx->ip_offset));
2984                 if (ctx->header->code [ctx->ip_offset + 5] != CEE_RET)
2985                         CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Tail call not followed by ret at 0x%04x", ctx->ip_offset));
2986         }
2987
2988 }
2989
2990 static void
2991 do_push_static_field (VerifyContext *ctx, int token, gboolean take_addr)
2992 {
2993         MonoClassField *field;
2994         MonoClass *klass;
2995         if (!check_overflow (ctx))
2996                 return;
2997         if (!take_addr)
2998                 CLEAR_PREFIX (ctx, PREFIX_VOLATILE);
2999
3000         if (!(field = verifier_load_field (ctx, token, &klass, take_addr ? "ldsflda" : "ldsfld")))
3001                 return;
3002
3003         if (!(field->type->attrs & FIELD_ATTRIBUTE_STATIC)) { 
3004                 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Cannot load non static field at 0x%04x", ctx->ip_offset));
3005                 return;
3006         }
3007         /*taking the address of initonly field only works from the static constructor */
3008         if (take_addr && (field->type->attrs & FIELD_ATTRIBUTE_INIT_ONLY) &&
3009                 !(field->parent == ctx->method->klass && (ctx->method->flags & (METHOD_ATTRIBUTE_SPECIAL_NAME | METHOD_ATTRIBUTE_STATIC)) && !strcmp (".cctor", ctx->method->name)))
3010                 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot take the address of a init-only field at 0x%04x", ctx->ip_offset));
3011
3012         if (!IS_SKIP_VISIBILITY (ctx) && !mono_method_can_access_field_full (ctx->method, field, NULL))
3013                 CODE_NOT_VERIFIABLE2 (ctx, g_strdup_printf ("Type at stack is not accessible at 0x%04x", ctx->ip_offset), MONO_EXCEPTION_FIELD_ACCESS);
3014
3015         set_stack_value (ctx, stack_push (ctx), field->type, take_addr);
3016 }
3017
3018 static void
3019 do_store_static_field (VerifyContext *ctx, int token) {
3020         MonoClassField *field;
3021         MonoClass *klass;
3022         ILStackDesc *value;
3023         CLEAR_PREFIX (ctx, PREFIX_VOLATILE);
3024
3025         if (!check_underflow (ctx, 1))
3026                 return;
3027
3028         value = stack_pop (ctx);
3029
3030         if (!(field = verifier_load_field (ctx, token, &klass, "stsfld")))
3031                 return;
3032
3033         if (!(field->type->attrs & FIELD_ATTRIBUTE_STATIC)) { 
3034                 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Cannot store non static field at 0x%04x", ctx->ip_offset));
3035                 return;
3036         }
3037
3038         if (field->type->type == MONO_TYPE_TYPEDBYREF) {
3039                 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Typedbyref field is an unverfiable type in store static field at 0x%04x", ctx->ip_offset));
3040                 return;
3041         }
3042
3043         if (!IS_SKIP_VISIBILITY (ctx) && !mono_method_can_access_field_full (ctx->method, field, NULL))
3044                 CODE_NOT_VERIFIABLE2 (ctx, g_strdup_printf ("Type at stack is not accessible at 0x%04x", ctx->ip_offset), MONO_EXCEPTION_FIELD_ACCESS);
3045
3046         if (!verify_stack_type_compatibility (ctx, field->type, value))
3047                 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));       
3048 }
3049
3050 static gboolean
3051 check_is_valid_type_for_field_ops (VerifyContext *ctx, int token, ILStackDesc *obj, MonoClassField **ret_field, const char *opcode)
3052 {
3053         MonoClassField *field;
3054         MonoClass *klass;
3055         gboolean is_pointer;
3056
3057         /*must be a reference type, a managed pointer, an unamanaged pointer, or a valuetype*/
3058         if (!(field = verifier_load_field (ctx, token, &klass, opcode)))
3059                 return FALSE;
3060
3061         *ret_field = field;
3062         //the value on stack is going to be used as a pointer
3063         is_pointer = stack_slot_get_type (obj) == TYPE_PTR || (stack_slot_get_type (obj) == TYPE_NATIVE_INT && !get_stack_type (&field->parent->byval_arg));
3064
3065         if (field->type->type == MONO_TYPE_TYPEDBYREF) {
3066                 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Typedbyref field is an unverfiable type at 0x%04x", ctx->ip_offset));
3067                 return FALSE;
3068         }
3069         g_assert (obj->type);
3070
3071         /*The value on the stack must be a subclass of the defining type of the field*/ 
3072         /* we need to check if we can load the field from the stack value*/
3073         if (is_pointer) {
3074                 if (stack_slot_get_underlying_type (obj) == TYPE_NATIVE_INT)
3075                         CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Native int is not a verifiable type to reference a field at 0x%04x", ctx->ip_offset));
3076
3077                 if (!IS_SKIP_VISIBILITY (ctx) && !mono_method_can_access_field_full (ctx->method, field, NULL))
3078                                 CODE_NOT_VERIFIABLE2 (ctx, g_strdup_printf ("Type at stack is not accessible at 0x%04x", ctx->ip_offset), MONO_EXCEPTION_FIELD_ACCESS);
3079         } else {
3080                 if (!field->parent->valuetype && stack_slot_is_managed_pointer (obj))
3081                         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));
3082
3083                 /*a value type can be loaded from a value or a managed pointer, but not a boxed object*/
3084                 if (field->parent->valuetype && stack_slot_is_boxed_value (obj))
3085                         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));
3086
3087                 if (!stack_slot_is_null_literal (obj) && !verify_stack_type_compatibility_full (ctx, &field->parent->byval_arg, obj, TRUE, FALSE)) {
3088                         char *found = stack_slot_full_name (obj);
3089                         char *expected = mono_type_full_name (&field->parent->byval_arg);
3090                         CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Expected type '%s' but found '%s' referencing the 'this' argument at 0x%04x", expected, found, ctx->ip_offset));
3091                         g_free (found);
3092                         g_free (expected);
3093                 }
3094
3095                 if (!IS_SKIP_VISIBILITY (ctx) && !mono_method_can_access_field_full (ctx->method, field, mono_class_from_mono_type (obj->type)))
3096                         CODE_NOT_VERIFIABLE2 (ctx, g_strdup_printf ("Type at stack is not accessible at 0x%04x", ctx->ip_offset), MONO_EXCEPTION_FIELD_ACCESS);
3097         } 
3098
3099         check_unmanaged_pointer (ctx, obj);
3100         return TRUE;
3101 }
3102
3103 static void
3104 do_push_field (VerifyContext *ctx, int token, gboolean take_addr)
3105 {
3106         ILStackDesc *obj;
3107         MonoClassField *field;
3108
3109         if (!take_addr)
3110                 CLEAR_PREFIX (ctx, PREFIX_UNALIGNED | PREFIX_VOLATILE);
3111
3112         if (!check_underflow (ctx, 1))
3113                 return;
3114         obj = stack_pop_safe (ctx);
3115
3116         if (!check_is_valid_type_for_field_ops (ctx, token, obj, &field, take_addr ? "ldflda" : "ldfld"))
3117                 return;
3118
3119         if (take_addr && field->parent->valuetype && !stack_slot_is_managed_pointer (obj))
3120                 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot take the address of a temporary value-type at 0x%04x", ctx->ip_offset));
3121
3122         if (take_addr && (field->type->attrs & FIELD_ATTRIBUTE_INIT_ONLY) &&
3123                 !(field->parent == ctx->method->klass && mono_method_is_constructor (ctx->method)))
3124                 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot take the address of a init-only field at 0x%04x", ctx->ip_offset));
3125
3126         set_stack_value (ctx, stack_push (ctx), field->type, take_addr);
3127 }
3128
3129 static void
3130 do_store_field (VerifyContext *ctx, int token)
3131 {
3132         ILStackDesc *value, *obj;
3133         MonoClassField *field;
3134         CLEAR_PREFIX (ctx, PREFIX_UNALIGNED | PREFIX_VOLATILE);
3135
3136         if (!check_underflow (ctx, 2))
3137                 return;
3138
3139         value = stack_pop (ctx);
3140         obj = stack_pop_safe (ctx);
3141
3142         if (!check_is_valid_type_for_field_ops (ctx, token, obj, &field, "stfld"))
3143                 return;
3144
3145         if (!verify_stack_type_compatibility (ctx, field->type, value))
3146                 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Incompatible type %s in field store at 0x%04x", stack_slot_get_name (value), ctx->ip_offset));      
3147 }
3148
3149 /*TODO proper handle for Nullable<T>*/
3150 static void
3151 do_box_value (VerifyContext *ctx, int klass_token)
3152 {
3153         ILStackDesc *value;
3154         MonoType *type = get_boxable_mono_type (ctx, klass_token, "box");
3155         MonoClass *klass;       
3156
3157         if (!type)
3158                 return;
3159
3160         if (!check_underflow (ctx, 1))
3161                 return;
3162
3163         value = stack_pop (ctx);
3164         /*box is a nop for reference types*/
3165
3166         if (stack_slot_get_underlying_type (value) == TYPE_COMPLEX && MONO_TYPE_IS_REFERENCE (value->type) && MONO_TYPE_IS_REFERENCE (type)) {
3167                 stack_push_stack_val (ctx, value)->stype |= BOXED_MASK;
3168                 return;
3169         }
3170
3171
3172         if (!verify_stack_type_compatibility (ctx, type, value))
3173                 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid type at stack for boxing operation at 0x%04x", ctx->ip_offset));
3174
3175         klass = mono_class_from_mono_type (type);
3176         if (mono_class_is_nullable (klass))
3177                 type = &mono_class_get_nullable_param (klass)->byval_arg;
3178         stack_push_val (ctx, TYPE_COMPLEX | BOXED_MASK, type);
3179 }
3180
3181 static void
3182 do_unbox_value (VerifyContext *ctx, int klass_token)
3183 {
3184         ILStackDesc *value;
3185         MonoType *type = get_boxable_mono_type (ctx, klass_token, "unbox");
3186
3187         if (!type)
3188                 return;
3189  
3190         if (!check_underflow (ctx, 1))
3191                 return;
3192
3193         if (!mono_class_from_mono_type (type)->valuetype)
3194                 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid reference type for unbox at 0x%04x", ctx->ip_offset));
3195
3196         value = stack_pop (ctx);
3197
3198         /*Value should be: a boxed valuetype or a reference type*/
3199         if (!(stack_slot_get_type (value) == TYPE_COMPLEX &&
3200                 (stack_slot_is_boxed_value (value) || !mono_class_from_mono_type (value->type)->valuetype)))
3201                 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));
3202
3203         set_stack_value (ctx, value = stack_push (ctx), mono_type_get_type_byref (type), FALSE);
3204         value->stype |= CMMP_MASK;
3205 }
3206
3207 static void
3208 do_unbox_any (VerifyContext *ctx, int klass_token)
3209 {
3210         ILStackDesc *value;
3211         MonoType *type = get_boxable_mono_type (ctx, klass_token, "unbox.any");
3212
3213         if (!type)
3214                 return;
3215  
3216         if (!check_underflow (ctx, 1))
3217                 return;
3218
3219         value = stack_pop (ctx);
3220
3221         /*Value should be: a boxed valuetype or a reference type*/
3222         if (!(stack_slot_get_type (value) == TYPE_COMPLEX &&
3223                 (stack_slot_is_boxed_value (value) || !mono_class_from_mono_type (value->type)->valuetype)))
3224                 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));
3225  
3226         set_stack_value (ctx, stack_push (ctx), type, FALSE);
3227 }
3228
3229 static void
3230 do_unary_math_op (VerifyContext *ctx, int op)
3231 {
3232         ILStackDesc *value;
3233         if (!check_underflow (ctx, 1))
3234                 return;
3235         value = stack_pop (ctx);
3236         switch (stack_slot_get_type (value)) {
3237         case TYPE_I4:
3238         case TYPE_I8:
3239         case TYPE_NATIVE_INT:
3240                 break;
3241         case TYPE_R8:
3242                 if (op == CEE_NEG)
3243                         break;
3244         case TYPE_COMPLEX: /*only enums are ok*/
3245                 if (mono_type_is_enum_type (value->type))
3246                         break;
3247         default:
3248                 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid type at stack for unary not at 0x%04x", ctx->ip_offset));
3249         }
3250         stack_push_stack_val (ctx, value);
3251 }
3252
3253 static void
3254 do_conversion (VerifyContext *ctx, int kind) 
3255 {
3256         ILStackDesc *value;
3257         if (!check_underflow (ctx, 1))
3258                 return;
3259         value = stack_pop (ctx);
3260
3261         switch (stack_slot_get_type (value)) {
3262         case TYPE_I4:
3263         case TYPE_I8:
3264         case TYPE_NATIVE_INT:
3265         case TYPE_R8:
3266                 break;
3267         default:
3268                 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));
3269         }
3270
3271         switch (kind) {
3272         case TYPE_I4:
3273                 stack_push_val (ctx, TYPE_I4, &mono_defaults.int32_class->byval_arg);
3274                 break;
3275         case TYPE_I8:
3276                 stack_push_val (ctx,TYPE_I8, &mono_defaults.int64_class->byval_arg);
3277                 break;
3278         case TYPE_R8:
3279                 stack_push_val (ctx, TYPE_R8, &mono_defaults.double_class->byval_arg);
3280                 break;
3281         case TYPE_NATIVE_INT:
3282                 stack_push_val (ctx, TYPE_NATIVE_INT, &mono_defaults.int_class->byval_arg);
3283                 break;
3284         default:
3285                 g_error ("unknown type %02x in conversion", kind);
3286
3287         }
3288 }
3289
3290 static void
3291 do_load_token (VerifyContext *ctx, int token) 
3292 {
3293         gpointer handle;
3294         MonoClass *handle_class;
3295         if (!check_overflow (ctx))
3296                 return;
3297         handle = mono_ldtoken (ctx->image, token, &handle_class, ctx->generic_context);
3298         if (!handle) {
3299                 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid token 0x%x for ldtoken at 0x%04x", token, ctx->ip_offset));
3300                 return;
3301         }
3302         if (handle_class == mono_defaults.typehandle_class) {
3303                 mono_type_is_valid_in_context (ctx, (MonoType*)handle);
3304         } else if (handle_class == mono_defaults.methodhandle_class) {
3305                 mono_method_is_valid_in_context (ctx, (MonoMethod*)handle);             
3306         } else if (handle_class == mono_defaults.fieldhandle_class) {
3307                 mono_type_is_valid_in_context (ctx, &((MonoClassField*)handle)->parent->byval_arg);                             
3308         } else {
3309                 ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid ldtoken type %x at 0x%04x", token, ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE);
3310         }
3311         stack_push_val (ctx, TYPE_COMPLEX, mono_class_get_type (handle_class));
3312 }
3313
3314 static void
3315 do_ldobj_value (VerifyContext *ctx, int token) 
3316 {
3317         ILStackDesc *value;
3318         MonoType *type = get_boxable_mono_type (ctx, token, "ldobj");
3319         CLEAR_PREFIX (ctx, PREFIX_UNALIGNED | PREFIX_VOLATILE);
3320
3321         if (!type)
3322                 return;
3323
3324         if (!check_underflow (ctx, 1))
3325                 return;
3326
3327         value = stack_pop (ctx);
3328         if (!stack_slot_is_managed_pointer (value) 
3329                         && stack_slot_get_type (value) != TYPE_NATIVE_INT
3330                         && !(stack_slot_get_type (value) == TYPE_PTR && value->type->type != MONO_TYPE_FNPTR)) {
3331                 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid argument %s to ldobj at 0x%04x", stack_slot_get_name (value), ctx->ip_offset));
3332                 return;
3333         }
3334
3335         if (stack_slot_get_type (value) == TYPE_NATIVE_INT)
3336                 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Using native pointer to ldobj at 0x%04x", ctx->ip_offset));
3337
3338         /*We have a byval on the stack, but the comparison must be strict. */
3339         if (!verify_type_compatibility_full (ctx, type, mono_type_get_type_byval (value->type), TRUE))
3340                 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid type at stack for ldojb operation at 0x%04x", ctx->ip_offset));
3341
3342         set_stack_value (ctx, stack_push (ctx), type, FALSE);
3343 }
3344
3345 static void
3346 do_stobj (VerifyContext *ctx, int token) 
3347 {
3348         ILStackDesc *dest, *src;
3349         MonoType *type = get_boxable_mono_type (ctx, token, "stobj");
3350         CLEAR_PREFIX (ctx, PREFIX_UNALIGNED | PREFIX_VOLATILE);
3351
3352         if (!type)
3353                 return;
3354
3355         if (!check_underflow (ctx, 2))
3356                 return;
3357
3358         src = stack_pop (ctx);
3359         dest = stack_pop (ctx);
3360
3361         if (stack_slot_is_managed_mutability_pointer (dest))
3362                 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use a readonly pointer with stobj at 0x%04x", ctx->ip_offset));
3363
3364         if (!stack_slot_is_managed_pointer (dest)) 
3365                 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid destination of stobj operation at 0x%04x", ctx->ip_offset));
3366
3367         if (stack_slot_is_boxed_value (src) && !MONO_TYPE_IS_REFERENCE (src->type) && !MONO_TYPE_IS_REFERENCE (type))
3368                 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));
3369
3370         if (!verify_stack_type_compatibility (ctx, type, src))
3371                 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Token and source types of stobj don't match at 0x%04x", ctx->ip_offset));
3372
3373         if (!verify_type_compatibility (ctx, mono_type_get_type_byval (dest->type), type))
3374                 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Destination and token types of stobj don't match at 0x%04x", ctx->ip_offset));
3375 }
3376
3377 static void
3378 do_cpobj (VerifyContext *ctx, int token)
3379 {
3380         ILStackDesc *dest, *src;
3381         MonoType *type = get_boxable_mono_type (ctx, token, "cpobj");
3382         if (!type)
3383                 return;
3384
3385         if (!check_underflow (ctx, 2))
3386                 return;
3387
3388         src = stack_pop (ctx);
3389         dest = stack_pop (ctx);
3390
3391         if (!stack_slot_is_managed_pointer (src)) 
3392                 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid source of cpobj operation at 0x%04x", ctx->ip_offset));
3393
3394         if (!stack_slot_is_managed_pointer (dest)) 
3395                 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid destination of cpobj operation at 0x%04x", ctx->ip_offset));
3396
3397         if (stack_slot_is_managed_mutability_pointer (dest))
3398                 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use a readonly pointer with cpobj at 0x%04x", ctx->ip_offset));
3399
3400         if (!verify_type_compatibility (ctx, type, mono_type_get_type_byval (src->type)))
3401                 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Token and source types of cpobj don't match at 0x%04x", ctx->ip_offset));
3402
3403         if (!verify_type_compatibility (ctx, mono_type_get_type_byval (dest->type), type))
3404                 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Destination and token types of cpobj don't match at 0x%04x", ctx->ip_offset));
3405 }
3406
3407 static void
3408 do_initobj (VerifyContext *ctx, int token)
3409 {
3410         ILStackDesc *obj;
3411         MonoType *stack, *type = get_boxable_mono_type (ctx, token, "initobj");
3412         if (!type)
3413                 return;
3414
3415         if (!check_underflow (ctx, 1))
3416                 return;
3417
3418         obj = stack_pop (ctx);
3419
3420         if (!stack_slot_is_managed_pointer (obj)) 
3421                 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid object address for initobj at 0x%04x", ctx->ip_offset));
3422
3423         if (stack_slot_is_managed_mutability_pointer (obj))
3424                 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use a readonly pointer with initobj at 0x%04x", ctx->ip_offset));
3425
3426         stack = mono_type_get_type_byval (obj->type);
3427         if (MONO_TYPE_IS_REFERENCE (stack)) {
3428                 if (!verify_type_compatibility (ctx, stack, type)) 
3429                         CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Type token of initobj not compatible with value on stack at 0x%04x", ctx->ip_offset));
3430                 else if (IS_STRICT_MODE (ctx) && !mono_metadata_type_equal (type, stack)) 
3431                         CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Type token of initobj not compatible with value on stack at 0x%04x", ctx->ip_offset));
3432         } else if (!verify_type_compatibility (ctx, stack, type)) {
3433                 char *expected_name = mono_type_full_name (type);
3434                 char *stack_name = mono_type_full_name (stack);
3435
3436                 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));
3437                 g_free (expected_name);
3438                 g_free (stack_name);
3439         }
3440 }
3441
3442 static void
3443 do_newobj (VerifyContext *ctx, int token) 
3444 {
3445         ILStackDesc *value;
3446         int i;
3447         MonoMethodSignature *sig;
3448         MonoMethod *method;
3449         gboolean is_delegate = FALSE;
3450
3451         if (!(method = verifier_load_method (ctx, token, "newobj")))
3452                 return;
3453
3454         if (!mono_method_is_constructor (method)) {
3455                 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Method from token 0x%08x not a constructor at 0x%04x", token, ctx->ip_offset));
3456                 return;
3457         }
3458
3459         if (method->klass->flags & (TYPE_ATTRIBUTE_ABSTRACT | TYPE_ATTRIBUTE_INTERFACE))
3460                 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Trying to instantiate an abstract or interface type at 0x%04x", ctx->ip_offset));
3461
3462         if (!mono_method_can_access_method_full (ctx->method, method, NULL)) {
3463                 char *from = mono_method_full_name (ctx->method, TRUE);
3464                 char *to = mono_method_full_name (method, TRUE);
3465                 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);
3466                 g_free (from);
3467                 g_free (to);
3468         }
3469
3470         //FIXME use mono_method_get_signature_full
3471         sig = mono_method_signature (method);
3472         if (!sig) {
3473                 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid constructor signature to newobj at 0x%04x", ctx->ip_offset));
3474                 return;
3475         }
3476
3477         if (!check_underflow (ctx, sig->param_count))
3478                 return;
3479
3480         is_delegate = method->klass->parent == mono_defaults.multicastdelegate_class;
3481
3482         if (is_delegate) {
3483                 ILStackDesc *funptr;
3484                 //first arg is object, second arg is fun ptr
3485                 if (sig->param_count != 2) {
3486                         ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid delegate constructor at 0x%04x", ctx->ip_offset));
3487                         return;
3488                 }
3489                 funptr = stack_pop (ctx);
3490                 value = stack_pop (ctx);
3491                 verify_delegate_compatibility (ctx, method->klass, value, funptr);
3492         } else {
3493                 for (i = sig->param_count - 1; i >= 0; --i) {
3494                         VERIFIER_DEBUG ( printf ("verifying constructor argument %d\n", i); );
3495                         value = stack_pop (ctx);
3496                         if (!verify_stack_type_compatibility (ctx, sig->params [i], value)) {
3497                                 char *stack_name = stack_slot_full_name (value);
3498                                 char *sig_name = mono_type_full_name (sig->params [i]);
3499                                 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));
3500                                 g_free (stack_name);
3501                                 g_free (sig_name);
3502                         }
3503
3504                         if (stack_slot_is_managed_mutability_pointer (value))
3505                                 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use a readonly pointer as argument of newobj at 0x%04x", ctx->ip_offset));
3506                 }
3507         }
3508
3509         if (check_overflow (ctx))
3510                 set_stack_value (ctx, stack_push (ctx),  &method->klass->byval_arg, FALSE);
3511 }
3512
3513 static void
3514 do_cast (VerifyContext *ctx, int token, const char *opcode) {
3515         ILStackDesc *value;
3516         MonoType *type;
3517         gboolean is_boxed;
3518         gboolean do_box;
3519
3520         if (!check_underflow (ctx, 1))
3521                 return;
3522
3523         if (!(type = verifier_load_type (ctx, token, opcode)))
3524                 return;
3525
3526         if (type->byref) {
3527                 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid %s type at 0x%04x", opcode, ctx->ip_offset));
3528                 return;
3529         }
3530
3531         value = stack_pop (ctx);
3532         is_boxed = stack_slot_is_boxed_value (value);
3533
3534         if (stack_slot_is_managed_pointer (value))
3535                 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid value for %s at 0x%04x", opcode, ctx->ip_offset));
3536         else if (!MONO_TYPE_IS_REFERENCE  (value->type) && !is_boxed) {
3537                 char *name = stack_slot_full_name (value);
3538                 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));
3539                 g_free (name);
3540         }
3541
3542         switch (value->type->type) {
3543         case MONO_TYPE_FNPTR:
3544         case MONO_TYPE_PTR:
3545         case MONO_TYPE_TYPEDBYREF: 
3546                 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid value for %s at 0x%04x", opcode, ctx->ip_offset));
3547         }
3548
3549         do_box = is_boxed || mono_type_is_generic_argument(type) || mono_class_from_mono_type (type)->valuetype;
3550         stack_push_val (ctx, TYPE_COMPLEX | (do_box ? BOXED_MASK : 0), type);
3551 }
3552
3553 static MonoType *
3554 mono_type_from_opcode (int opcode) {
3555         switch (opcode) {
3556         case CEE_LDIND_I1:
3557         case CEE_LDIND_U1:
3558         case CEE_STIND_I1:
3559         case CEE_LDELEM_I1:
3560         case CEE_LDELEM_U1:
3561         case CEE_STELEM_I1:
3562                 return &mono_defaults.sbyte_class->byval_arg;
3563
3564         case CEE_LDIND_I2:
3565         case CEE_LDIND_U2:
3566         case CEE_STIND_I2:
3567         case CEE_LDELEM_I2:
3568         case CEE_LDELEM_U2:
3569         case CEE_STELEM_I2:
3570                 return &mono_defaults.int16_class->byval_arg;
3571
3572         case CEE_LDIND_I4:
3573         case CEE_LDIND_U4:
3574         case CEE_STIND_I4:
3575         case CEE_LDELEM_I4:
3576         case CEE_LDELEM_U4:
3577         case CEE_STELEM_I4:
3578                 return &mono_defaults.int32_class->byval_arg;
3579
3580         case CEE_LDIND_I8:
3581         case CEE_STIND_I8:
3582         case CEE_LDELEM_I8:
3583         case CEE_STELEM_I8:
3584                 return &mono_defaults.int64_class->byval_arg;
3585
3586         case CEE_LDIND_R4:
3587         case CEE_STIND_R4:
3588         case CEE_LDELEM_R4:
3589         case CEE_STELEM_R4:
3590                 return &mono_defaults.single_class->byval_arg;
3591
3592         case CEE_LDIND_R8:
3593         case CEE_STIND_R8:
3594         case CEE_LDELEM_R8:
3595         case CEE_STELEM_R8:
3596                 return &mono_defaults.double_class->byval_arg;
3597
3598         case CEE_LDIND_I:
3599         case CEE_STIND_I:
3600         case CEE_LDELEM_I:
3601         case CEE_STELEM_I:
3602                 return &mono_defaults.int_class->byval_arg;
3603
3604         case CEE_LDIND_REF:
3605         case CEE_STIND_REF:
3606         case CEE_LDELEM_REF:
3607         case CEE_STELEM_REF:
3608                 return &mono_defaults.object_class->byval_arg;
3609
3610         default:
3611                 g_error ("unknown opcode %02x in mono_type_from_opcode ", opcode);
3612                 return NULL;
3613         }
3614 }
3615
3616 static void
3617 do_load_indirect (VerifyContext *ctx, int opcode)
3618 {
3619         ILStackDesc *value;
3620         CLEAR_PREFIX (ctx, PREFIX_UNALIGNED | PREFIX_VOLATILE);
3621
3622         if (!check_underflow (ctx, 1))
3623                 return;
3624         
3625         value = stack_pop (ctx);
3626         if (!stack_slot_is_managed_pointer (value)) {
3627                 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Load indirect not using a manager pointer at 0x%04x", ctx->ip_offset));
3628                 set_stack_value (ctx, stack_push (ctx), mono_type_from_opcode (opcode), FALSE);
3629                 return;
3630         }
3631
3632         if (opcode == CEE_LDIND_REF) {
3633                 if (stack_slot_get_underlying_type (value) != TYPE_COMPLEX || mono_class_from_mono_type (value->type)->valuetype)
3634                         CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid type at stack for ldind_ref expected object byref operation at 0x%04x", ctx->ip_offset));
3635                 set_stack_value (ctx, stack_push (ctx), mono_type_get_type_byval (value->type), FALSE);
3636         } else {
3637                 if (!verify_type_compatibility_full (ctx, mono_type_from_opcode (opcode), mono_type_get_type_byval (value->type), TRUE))
3638                         CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid type at stack for ldind 0x%x operation at 0x%04x", opcode, ctx->ip_offset));
3639                 set_stack_value (ctx, stack_push (ctx), mono_type_from_opcode (opcode), FALSE);
3640         }
3641 }
3642
3643 static void
3644 do_store_indirect (VerifyContext *ctx, int opcode)
3645 {
3646         ILStackDesc *addr, *val;
3647         CLEAR_PREFIX (ctx, PREFIX_UNALIGNED | PREFIX_VOLATILE);
3648
3649         if (!check_underflow (ctx, 2))
3650                 return;
3651
3652         val = stack_pop (ctx);
3653         addr = stack_pop (ctx); 
3654
3655         check_unmanaged_pointer (ctx, addr);
3656
3657         if (!stack_slot_is_managed_pointer (addr) && stack_slot_get_type (addr) != TYPE_PTR) {
3658                 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid non-pointer argument to stind at 0x%04x", ctx->ip_offset));
3659                 return;
3660         }
3661
3662         if (stack_slot_is_managed_mutability_pointer (addr)) {
3663                 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use a readonly pointer with stind at 0x%04x", ctx->ip_offset));
3664                 return;
3665         }
3666
3667         if (!verify_type_compatibility_full (ctx, mono_type_from_opcode (opcode), mono_type_get_type_byval (addr->type), TRUE))
3668                 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid addr type at stack for stind 0x%x operation at 0x%04x", opcode, ctx->ip_offset));
3669
3670         if (!verify_stack_type_compatibility (ctx, mono_type_from_opcode (opcode), val))
3671                 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid value type at stack for stind 0x%x operation at 0x%04x", opcode, ctx->ip_offset));
3672 }
3673
3674 static void
3675 do_newarr (VerifyContext *ctx, int token) 
3676 {
3677         ILStackDesc *value;
3678         MonoType *type = get_boxable_mono_type (ctx, token, "newarr");
3679
3680         if (!type)
3681                 return;
3682
3683         if (!check_underflow (ctx, 1))
3684                 return;
3685
3686         value = stack_pop (ctx);
3687         if (stack_slot_get_type (value) != TYPE_I4 && stack_slot_get_type (value) != TYPE_NATIVE_INT)
3688                 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));
3689
3690         set_stack_value (ctx, stack_push (ctx), mono_class_get_type (mono_array_class_get (mono_class_from_mono_type (type), 1)), FALSE);
3691 }
3692
3693 /*FIXME handle arrays that are not 0-indexed*/
3694 static void
3695 do_ldlen (VerifyContext *ctx)
3696 {
3697         ILStackDesc *value;
3698
3699         if (!check_underflow (ctx, 1))
3700                 return;
3701
3702         value = stack_pop (ctx);
3703
3704         if (stack_slot_get_type (value) != TYPE_COMPLEX || value->type->type != MONO_TYPE_SZARRAY)
3705                 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type for ldlen at 0x%04x", ctx->ip_offset));
3706
3707         stack_push_val (ctx, TYPE_NATIVE_INT, &mono_defaults.int_class->byval_arg);     
3708 }
3709
3710 /*FIXME handle arrays that are not 0-indexed*/
3711 /*FIXME handle readonly prefix and CMMP*/
3712 static void
3713 do_ldelema (VerifyContext *ctx, int klass_token)
3714 {
3715         ILStackDesc *index, *array, *res;
3716         MonoType *type = get_boxable_mono_type (ctx, klass_token, "ldelema");
3717         gboolean valid; 
3718
3719         if (!type)
3720                 return;
3721
3722         if (!check_underflow (ctx, 2))
3723                 return;
3724
3725         index = stack_pop (ctx);
3726         array = stack_pop (ctx);
3727
3728         if (stack_slot_get_type (index) != TYPE_I4 && stack_slot_get_type (index) != TYPE_NATIVE_INT)
3729                 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));
3730
3731         if (!stack_slot_is_null_literal (array)) {
3732                 if (stack_slot_get_type (array) != TYPE_COMPLEX || array->type->type != MONO_TYPE_SZARRAY)
3733                         CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type(%s) for ldelema at 0x%04x", stack_slot_get_name (array), ctx->ip_offset));
3734                 else {
3735                         if (get_stack_type (type) == TYPE_I4 || get_stack_type (type) == TYPE_NATIVE_INT) {
3736                                         valid = verify_type_compatibility_full (ctx, type, &array->type->data.klass->byval_arg, TRUE);
3737                         } else {
3738                                 valid = mono_metadata_type_equal (type, &array->type->data.klass->byval_arg);
3739                         }
3740                         if (!valid)
3741                                 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type on stack for ldelema at 0x%04x", ctx->ip_offset));
3742                 }
3743         }
3744
3745         res = stack_push (ctx);
3746         set_stack_value (ctx, res, type, TRUE);
3747         if (ctx->prefix_set & PREFIX_READONLY) {
3748                 ctx->prefix_set &= ~PREFIX_READONLY;
3749                 res->stype |= CMMP_MASK;
3750         }
3751 }
3752
3753 /*
3754  * FIXME handle arrays that are not 0-indexed
3755  * FIXME handle readonly prefix and CMMP
3756  */
3757 static void
3758 do_ldelem (VerifyContext *ctx, int opcode, int token)
3759 {
3760 #define IS_ONE_OF2(T, A, B) (T == A || T == B)
3761         ILStackDesc *index, *array;
3762         MonoType *type;
3763         if (!check_underflow (ctx, 2))
3764                 return;
3765
3766         if (opcode == CEE_LDELEM) {
3767                 if (!(type = verifier_load_type (ctx, token, "ldelem.any"))) {
3768                         ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Type (0x%08x) not found at 0x%04x", token, ctx->ip_offset));
3769                         return;
3770                 }
3771         } else {
3772                 type = mono_type_from_opcode (opcode);
3773         }
3774
3775         index = stack_pop (ctx);
3776         array = stack_pop (ctx);
3777
3778         if (stack_slot_get_type (index) != TYPE_I4 && stack_slot_get_type (index) != TYPE_NATIVE_INT)
3779                 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));
3780
3781         if (!stack_slot_is_null_literal (array)) {
3782                 if (stack_slot_get_type (array) != TYPE_COMPLEX || array->type->type != MONO_TYPE_SZARRAY)
3783                         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));
3784                 else {
3785                         if (opcode == CEE_LDELEM_REF) {
3786                                 if (array->type->data.klass->valuetype)
3787                                         CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type is not a reference type for ldelem.ref 0x%04x", ctx->ip_offset));
3788                                 type = &array->type->data.klass->byval_arg;
3789                         } else {
3790                                 MonoType *candidate = &array->type->data.klass->byval_arg;
3791                                 if (IS_STRICT_MODE (ctx)) {
3792                                         MonoType *underlying_type = mono_type_get_underlying_type_any (type);
3793                                         MonoType *underlying_candidate = mono_type_get_underlying_type_any (candidate);
3794                                         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)) ||
3795                                                 (IS_ONE_OF2 (underlying_candidate->type, MONO_TYPE_I4, MONO_TYPE_U4) && IS_ONE_OF2 (underlying_type->type, MONO_TYPE_I, MONO_TYPE_U)))
3796                                                 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type on stack for ldelem.X at 0x%04x", ctx->ip_offset));
3797                                 }
3798                                 if (!verify_type_compatibility_full (ctx, type, candidate, TRUE))
3799                                         CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type on stack for ldelem.X at 0x%04x", ctx->ip_offset));
3800                         }
3801                 }
3802         }
3803
3804         set_stack_value (ctx, stack_push (ctx), type, FALSE);
3805 #undef IS_ONE_OF2
3806 }
3807
3808 /*
3809  * FIXME handle arrays that are not 0-indexed
3810  */
3811 static void
3812 do_stelem (VerifyContext *ctx, int opcode, int token)
3813 {
3814         ILStackDesc *index, *array, *value;
3815         MonoType *type;
3816         if (!check_underflow (ctx, 3))
3817                 return;
3818
3819         if (opcode == CEE_STELEM) {
3820                 if (!(type = verifier_load_type (ctx, token, "stelem.any"))) {
3821                         ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Type (0x%08x) not found at 0x%04x", token, ctx->ip_offset));
3822                         return;
3823                 }
3824         } else {
3825                 type = mono_type_from_opcode (opcode);
3826         }
3827         
3828         value = stack_pop (ctx);
3829         index = stack_pop (ctx);
3830         array = stack_pop (ctx);
3831
3832         if (stack_slot_get_type (index) != TYPE_I4 && stack_slot_get_type (index) != TYPE_NATIVE_INT)
3833                 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));
3834
3835         if (!stack_slot_is_null_literal (array)) {
3836                 if (stack_slot_get_type (array) != TYPE_COMPLEX || array->type->type != MONO_TYPE_SZARRAY) {
3837                         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));
3838                 } else {
3839                         if (opcode == CEE_STELEM_REF) {
3840                                 if (array->type->data.klass->valuetype)
3841                                         CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type is not a reference type for stelem.ref 0x%04x", ctx->ip_offset));
3842                         } else if (!verify_type_compatibility_full (ctx, &array->type->data.klass->byval_arg, type, TRUE)) {
3843                                         CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type on stack for stdelem.X at 0x%04x", ctx->ip_offset));
3844                         }
3845                 }
3846         }
3847         if (opcode == CEE_STELEM_REF) {
3848                 if (!stack_slot_is_boxed_value (value) && mono_class_from_mono_type (value->type)->valuetype)
3849                         CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid value is not a reference type for stelem.ref 0x%04x", ctx->ip_offset));
3850         } else if (opcode != CEE_STELEM_REF) {
3851                 if (!verify_stack_type_compatibility (ctx, type, value))
3852                         CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid value on stack for stdelem.X at 0x%04x", ctx->ip_offset));
3853
3854                 if (stack_slot_is_boxed_value (value) && !MONO_TYPE_IS_REFERENCE (value->type) && !MONO_TYPE_IS_REFERENCE (type))
3855                         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));
3856
3857         }
3858 }
3859
3860 static void
3861 do_throw (VerifyContext *ctx)
3862 {
3863         ILStackDesc *exception;
3864         if (!check_underflow (ctx, 1))
3865                 return;
3866         exception = stack_pop (ctx);
3867
3868         if (!stack_slot_is_null_literal (exception) && !(stack_slot_get_type (exception) == TYPE_COMPLEX && !mono_class_from_mono_type (exception->type)->valuetype))
3869                 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid type on stack for throw, expected reference type at 0x%04x", ctx->ip_offset));
3870
3871         if (mono_type_is_generic_argument (exception->type) && !stack_slot_is_boxed_value (exception)) {
3872                 char *name = mono_type_full_name (exception->type);
3873                 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));
3874                 g_free (name);
3875         }
3876         /*The stack is left empty after a throw*/
3877         ctx->eval.size = 0;
3878 }
3879
3880
3881 static void
3882 do_endfilter (VerifyContext *ctx)
3883 {
3884         MonoExceptionClause *clause;
3885
3886         if (IS_STRICT_MODE (ctx)) {
3887                 if (ctx->eval.size != 1)
3888                         CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Stack size must have one item for endfilter at 0x%04x", ctx->ip_offset));
3889
3890                 if (ctx->eval.size >= 1 && stack_slot_get_type (stack_pop (ctx)) != TYPE_I4)
3891                         CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Stack item type is not an int32 for endfilter at 0x%04x", ctx->ip_offset));
3892         }
3893
3894         if ((clause = is_correct_endfilter (ctx, ctx->ip_offset))) {
3895                 if (IS_STRICT_MODE (ctx)) {
3896                         if (ctx->ip_offset != clause->handler_offset - 2)
3897                                 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("endfilter is not the last instruction of the filter clause at 0x%04x", ctx->ip_offset));                       
3898                 } else {
3899                         if ((ctx->ip_offset != clause->handler_offset - 2) && !MONO_OFFSET_IN_HANDLER (clause, ctx->ip_offset))
3900                                 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("endfilter is not the last instruction of the filter clause at 0x%04x", ctx->ip_offset));
3901                 }
3902         } else {
3903                 if (IS_STRICT_MODE (ctx) && !is_unverifiable_endfilter (ctx, ctx->ip_offset))
3904                         ADD_VERIFY_ERROR (ctx, g_strdup_printf ("endfilter outside filter clause at 0x%04x", ctx->ip_offset));
3905                 else
3906                         CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("endfilter outside filter clause at 0x%04x", ctx->ip_offset));
3907         }
3908
3909         ctx->eval.size = 0;
3910 }
3911
3912 static void
3913 do_leave (VerifyContext *ctx, int delta)
3914 {
3915         int target = ((gint32)ctx->ip_offset) + delta;
3916         if (target >= ctx->code_size || target < 0)
3917                 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Branch target out of code at 0x%04x", ctx->ip_offset));
3918
3919         if (!is_correct_leave (ctx->header, ctx->ip_offset, target))
3920                 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Leave not allowed in finally block at 0x%04x", ctx->ip_offset));
3921         ctx->eval.size = 0;
3922 }
3923
3924 /* 
3925  * do_static_branch:
3926  * 
3927  * Verify br and br.s opcodes.
3928  */
3929 static void
3930 do_static_branch (VerifyContext *ctx, int delta)
3931 {
3932         int target = ctx->ip_offset + delta;
3933         if (target < 0 || target >= ctx->code_size) {
3934                 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("branch target out of code at 0x%04x", ctx->ip_offset));
3935                 return;
3936         }
3937
3938         switch (is_valid_branch_instruction (ctx->header, ctx->ip_offset, target)) {
3939         case 1:
3940                 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Branch target escapes out of exception block at 0x%04x", ctx->ip_offset));
3941                 break;
3942         case 2:
3943                 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Branch target escapes out of exception block at 0x%04x", ctx->ip_offset));
3944                 break;
3945         }
3946
3947         ctx->target = target;
3948 }
3949
3950 static void
3951 do_switch (VerifyContext *ctx, int count, const unsigned char *data)
3952 {
3953         int i, base = ctx->ip_offset + 5 + count * 4;
3954         ILStackDesc *value;
3955
3956         if (!check_underflow (ctx, 1))
3957                 return;
3958
3959         value = stack_pop (ctx);
3960
3961         if (stack_slot_get_type (value) != TYPE_I4 && stack_slot_get_type (value) != TYPE_NATIVE_INT)
3962                 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid argument to switch at 0x%04x", ctx->ip_offset));
3963
3964         for (i = 0; i < count; ++i) {
3965                 int target = base + read32 (data + i * 4);
3966
3967                 if (target < 0 || target >= ctx->code_size) {
3968                         ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Switch target %x out of code at 0x%04x", i, ctx->ip_offset));
3969                         return;
3970                 }
3971
3972                 switch (is_valid_branch_instruction (ctx->header, ctx->ip_offset, target)) {
3973                 case 1:
3974                         CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Switch target %x escapes out of exception block at 0x%04x", i, ctx->ip_offset));
3975                         break;
3976                 case 2:
3977                         ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Switch target %x escapes out of exception block at 0x%04x", i, ctx->ip_offset));
3978                         return;
3979                 }
3980                 merge_stacks (ctx, &ctx->eval, &ctx->code [target], FALSE, TRUE);
3981         }
3982 }
3983
3984 static void
3985 do_load_function_ptr (VerifyContext *ctx, guint32 token, gboolean virtual)
3986 {
3987         ILStackDesc *top;
3988         MonoMethod *method;
3989
3990         if (virtual && !check_underflow (ctx, 1))
3991                 return;
3992
3993         if (!virtual && !check_overflow (ctx))
3994                 return;
3995
3996         if (!IS_METHOD_DEF_OR_REF_OR_SPEC (token) || !token_bounds_check (ctx->image, token)) {
3997                 ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid token %x for ldftn  at 0x%04x", token, ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE);
3998                 return;
3999         }
4000
4001         if (!(method = verifier_load_method (ctx, token, virtual ? "ldvirtfrn" : "ldftn")))
4002                 return;
4003
4004         if (mono_method_is_constructor (method))
4005                 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use ldftn with a constructor at 0x%04x", ctx->ip_offset));
4006
4007         if (virtual) {
4008                 ILStackDesc *top = stack_pop (ctx);
4009         
4010                 if (stack_slot_get_type (top) != TYPE_COMPLEX || top->type->type == MONO_TYPE_VALUETYPE)
4011                         CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid argument to ldvirtftn at 0x%04x", ctx->ip_offset));
4012         
4013                 if (method->flags & METHOD_ATTRIBUTE_STATIC)
4014                         CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use ldvirtftn with a constructor at 0x%04x", ctx->ip_offset));
4015
4016                 if (!verify_stack_type_compatibility (ctx, &method->klass->byval_arg, top))
4017                         CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Unexpected object for ldvirtftn at 0x%04x", ctx->ip_offset));
4018         }
4019         
4020         if (!mono_method_can_access_method_full (ctx->method, method, NULL))
4021                 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);
4022
4023         top = stack_push_val(ctx, TYPE_PTR, mono_type_create_fnptr_from_mono_method (ctx, method));
4024         top->method = method;
4025 }
4026
4027 static void
4028 do_sizeof (VerifyContext *ctx, int token)
4029 {
4030         MonoType *type;
4031
4032         if (!IS_TYPE_DEF_OR_REF_OR_SPEC (token) || !token_bounds_check (ctx->image, token)) {
4033                 ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid type token %x at 0x%04x", token, ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE);
4034                 return;
4035         }
4036         
4037         if (!(type = verifier_load_type (ctx, token, "sizeof")))
4038                 return;
4039
4040         if (type->byref && type->type != MONO_TYPE_TYPEDBYREF) {
4041                 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid use of byref type at 0x%04x", ctx->ip_offset));
4042                 return;
4043         }
4044
4045         if (type->type == MONO_TYPE_VOID) {
4046                 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid use of void type at 0x%04x", ctx->ip_offset));
4047                 return;
4048         }
4049
4050         if (check_overflow (ctx))
4051                 set_stack_value (ctx, stack_push (ctx), &mono_defaults.uint32_class->byval_arg, FALSE);
4052 }
4053
4054 /* Stack top can be of any type, the runtime doesn't care and treat everything as an int. */
4055 static void
4056 do_localloc (VerifyContext *ctx)
4057 {
4058         ILStackDesc *top;
4059         
4060         if (ctx->eval.size != 1) {
4061                 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Stack must have only size item in localloc at 0x%04x", ctx->ip_offset));
4062                 return;         
4063         }
4064
4065         if (in_any_exception_block (ctx->header, ctx->ip_offset)) {
4066                 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Stack must have only size item in localloc at 0x%04x", ctx->ip_offset));
4067                 return;
4068         }
4069
4070         /*TODO verify top type*/
4071         top = stack_pop (ctx);
4072
4073         set_stack_value (ctx, stack_push (ctx), &mono_defaults.int_class->byval_arg, FALSE);
4074         CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Instruction localloc in never verifiable at 0x%04x", ctx->ip_offset));
4075 }
4076
4077 static void
4078 do_ldstr (VerifyContext *ctx, guint32 token)
4079 {
4080         GSList *error = NULL;
4081         if (mono_metadata_token_code (token) != MONO_TOKEN_STRING) {
4082                 ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid string token %x at 0x%04x", token, ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE);
4083                 return;
4084         }
4085
4086         if (!ctx->image->dynamic && !mono_verifier_verify_string_signature (ctx->image, mono_metadata_token_index (token), &error)) {
4087                 if (error)
4088                         ctx->list = g_slist_concat (ctx->list, error);
4089                 ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid string index %x at 0x%04x", token, ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE);
4090                 return;
4091         }
4092
4093         if (check_overflow (ctx))
4094                 stack_push_val (ctx, TYPE_COMPLEX,  &mono_defaults.string_class->byval_arg);
4095 }
4096
4097 static void
4098 do_refanyval (VerifyContext *ctx, int token)
4099 {
4100         ILStackDesc *top;
4101         MonoType *type;
4102         if (!check_underflow (ctx, 1))
4103                 return;
4104
4105         if (!(type = get_boxable_mono_type (ctx, token, "refanyval")))
4106                 return;
4107
4108         top = stack_pop (ctx);
4109
4110         if (top->stype != TYPE_PTR || top->type->type != MONO_TYPE_TYPEDBYREF)
4111                 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));
4112
4113         set_stack_value (ctx, stack_push (ctx), type, TRUE);
4114 }
4115
4116 static void
4117 do_refanytype (VerifyContext *ctx)
4118 {
4119         ILStackDesc *top;
4120
4121         if (!check_underflow (ctx, 1))
4122                 return;
4123
4124         top = stack_pop (ctx);
4125
4126         if (top->stype != TYPE_PTR || top->type->type != MONO_TYPE_TYPEDBYREF)
4127                 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));
4128
4129         set_stack_value (ctx, stack_push (ctx), &mono_defaults.typehandle_class->byval_arg, FALSE);
4130
4131 }
4132
4133 static void
4134 do_mkrefany (VerifyContext *ctx, int token)
4135 {
4136         ILStackDesc *top;
4137         MonoType *type;
4138         if (!check_underflow (ctx, 1))
4139                 return;
4140
4141         if (!(type = get_boxable_mono_type (ctx, token, "refanyval")))
4142                 return;
4143
4144         top = stack_pop (ctx);
4145
4146         if (stack_slot_is_managed_mutability_pointer (top))
4147                 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use a readonly pointer with mkrefany at 0x%04x", ctx->ip_offset));
4148
4149         if (!stack_slot_is_managed_pointer (top)) {
4150                 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));
4151         }else {
4152                 MonoType *stack_type = mono_type_get_type_byval (top->type);
4153                 if (MONO_TYPE_IS_REFERENCE (type) && !mono_metadata_type_equal (type, stack_type))
4154                         CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Type not compatible for mkrefany at 0x%04x", ctx->ip_offset));
4155                         
4156                 if (!MONO_TYPE_IS_REFERENCE (type) && !verify_type_compatibility_full (ctx, type, stack_type, TRUE))
4157                         CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Type not compatible for mkrefany at 0x%04x", ctx->ip_offset));
4158         }
4159
4160         set_stack_value (ctx, stack_push (ctx), &mono_defaults.typed_reference_class->byval_arg, FALSE);
4161 }
4162
4163 static void
4164 do_ckfinite (VerifyContext *ctx)
4165 {
4166         ILStackDesc *top;
4167         if (!check_underflow (ctx, 1))
4168                 return;
4169
4170         top = stack_pop (ctx);
4171
4172         if (stack_slot_get_underlying_type (top) != TYPE_R8)
4173                 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)); 
4174         stack_push_stack_val (ctx, top);
4175 }
4176 /*
4177  * merge_stacks:
4178  * Merge the stacks and perform compat checks. The merge check if types of @from are mergeable with type of @to 
4179  * 
4180  * @from holds new values for a given control path
4181  * @to holds the current values of a given control path
4182  * 
4183  * TODO we can eliminate the from argument as all callers pass &ctx->eval
4184  */
4185 static void
4186 merge_stacks (VerifyContext *ctx, ILCodeDesc *from, ILCodeDesc *to, gboolean start, gboolean external) 
4187 {
4188         MonoError error;
4189         int i, j, k;
4190         stack_init (ctx, to);
4191
4192         if (start) {
4193                 if (to->flags == IL_CODE_FLAG_NOT_PROCESSED) 
4194                         from->size = 0;
4195                 else
4196                         stack_copy (&ctx->eval, to);
4197                 goto end_verify;
4198         } else if (!(to->flags & IL_CODE_STACK_MERGED)) {
4199                 stack_copy (to, &ctx->eval);
4200                 goto end_verify;
4201         }
4202         VERIFIER_DEBUG ( printf ("performing stack merge %d x %d\n", from->size, to->size); );
4203
4204         if (from->size != to->size) {
4205                 VERIFIER_DEBUG ( printf ("different stack sizes %d x %d at 0x%04x\n", from->size, to->size, ctx->ip_offset); );
4206                 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)); 
4207                 goto end_verify;
4208         }
4209
4210         //FIXME we need to preserve CMMP attributes
4211         //FIXME we must take null literals into consideration.
4212         for (i = 0; i < from->size; ++i) {
4213                 ILStackDesc *new_slot = from->stack + i;
4214                 ILStackDesc *old_slot = to->stack + i;
4215                 MonoType *new_type = mono_type_from_stack_slot (new_slot);
4216                 MonoType *old_type = mono_type_from_stack_slot (old_slot);
4217                 MonoClass *old_class = mono_class_from_mono_type (old_type);
4218                 MonoClass *new_class = mono_class_from_mono_type (new_type);
4219                 MonoClass *match_class = NULL;
4220
4221                 // S := T then U = S (new value is compatible with current value, keep current)
4222                 if (verify_stack_type_compatibility (ctx, old_type, new_slot)) {
4223                         copy_stack_value (new_slot, old_slot);
4224                         continue;
4225                 }
4226
4227                 // T := S then U = T (old value is compatible with current value, use new)
4228                 if (verify_stack_type_compatibility (ctx, new_type, old_slot)) {
4229                         copy_stack_value (old_slot, new_slot);
4230                         continue;
4231                 }
4232
4233                 if (mono_type_is_generic_argument (old_type) || mono_type_is_generic_argument (new_type)) {
4234                         char *old_name = stack_slot_full_name (old_slot); 
4235                         char *new_name = stack_slot_full_name (new_slot);
4236                         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));
4237                         g_free (old_name);
4238                         g_free (new_name);
4239                         goto end_verify;                        
4240                 } 
4241
4242                 //both are reference types, use closest common super type
4243                 if (!mono_class_from_mono_type (old_type)->valuetype 
4244                         && !mono_class_from_mono_type (new_type)->valuetype
4245                         && !stack_slot_is_managed_pointer (old_slot)
4246                         && !stack_slot_is_managed_pointer (new_slot)) {
4247                         
4248                         for (j = MIN (old_class->idepth, new_class->idepth) - 1; j > 0; --j) {
4249                                 if (mono_metadata_type_equal (&old_class->supertypes [j]->byval_arg, &new_class->supertypes [j]->byval_arg)) {
4250                                         match_class = old_class->supertypes [j];
4251                                         goto match_found;
4252                                 }
4253                         }
4254
4255                         mono_class_setup_interfaces (old_class, &error);
4256                         if (!mono_error_ok (&error)) {
4257                                 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot merge stacks due to a TypeLoadException %s at 0x%04x", mono_error_get_message (&error), ctx->ip_offset));
4258                                 mono_error_cleanup (&error);
4259                                 goto end_verify;
4260                         }
4261                         for (j = 0; j < old_class->interface_count; ++j) {
4262                                 for (k = 0; k < new_class->interface_count; ++k) {
4263                                         if (mono_metadata_type_equal (&old_class->interfaces [j]->byval_arg, &new_class->interfaces [k]->byval_arg)) {
4264                                                 match_class = old_class->interfaces [j];
4265                                                 goto match_found;
4266                                         }
4267                                 }
4268                         }
4269
4270                         //No decent super type found, use object
4271                         match_class = mono_defaults.object_class;
4272                         goto match_found;
4273                 } 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)) {
4274                         match_class = mono_defaults.object_class;
4275                         goto match_found;
4276                 }
4277
4278                 {
4279                 char *old_name = stack_slot_full_name (old_slot); 
4280                 char *new_name = stack_slot_full_name (new_slot);
4281                 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)); 
4282                 g_free (old_name);
4283                 g_free (new_name);
4284                 }
4285                 set_stack_value (ctx, old_slot, &new_class->byval_arg, stack_slot_is_managed_pointer (old_slot));
4286                 goto end_verify;
4287
4288 match_found:
4289                 g_assert (match_class);
4290                 set_stack_value (ctx, old_slot, &match_class->byval_arg, stack_slot_is_managed_pointer (old_slot));
4291                 set_stack_value (ctx, new_slot, &match_class->byval_arg, stack_slot_is_managed_pointer (old_slot));
4292                 continue;
4293         }
4294
4295 end_verify:
4296         if (external)
4297                 to->flags |= IL_CODE_FLAG_WAS_TARGET;
4298         to->flags |= IL_CODE_STACK_MERGED;
4299 }
4300
4301 #define HANDLER_START(clause) ((clause)->flags == MONO_EXCEPTION_CLAUSE_FILTER ? (clause)->data.filter_offset : clause->handler_offset)
4302 #define IS_CATCH_OR_FILTER(clause) ((clause)->flags == MONO_EXCEPTION_CLAUSE_FILTER || (clause)->flags == MONO_EXCEPTION_CLAUSE_NONE)
4303
4304 /*
4305  * is_clause_in_range :
4306  * 
4307  * Returns TRUE if either the protected block or the handler of @clause is in the @start - @end range.  
4308  */
4309 static gboolean
4310 is_clause_in_range (MonoExceptionClause *clause, guint32 start, guint32 end)
4311 {
4312         if (clause->try_offset >= start && clause->try_offset < end)
4313                 return TRUE;
4314         if (HANDLER_START (clause) >= start && HANDLER_START (clause) < end)
4315                 return TRUE;
4316         return FALSE;
4317 }
4318
4319 /*
4320  * is_clause_inside_range :
4321  * 
4322  * Returns TRUE if @clause lies completely inside the @start - @end range.  
4323  */
4324 static gboolean
4325 is_clause_inside_range (MonoExceptionClause *clause, guint32 start, guint32 end)
4326 {
4327         if (clause->try_offset < start || (clause->try_offset + clause->try_len) > end)
4328                 return FALSE;
4329         if (HANDLER_START (clause) < start || (clause->handler_offset + clause->handler_len) > end)
4330                 return FALSE;
4331         return TRUE;
4332 }
4333
4334 /*
4335  * is_clause_nested :
4336  * 
4337  * Returns TRUE if @nested is nested in @clause.   
4338  */
4339 static gboolean
4340 is_clause_nested (MonoExceptionClause *clause, MonoExceptionClause *nested)
4341 {
4342         if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER && is_clause_inside_range (nested, clause->data.filter_offset, clause->handler_offset))
4343                 return TRUE;
4344         return is_clause_inside_range (nested, clause->try_offset, clause->try_offset + clause->try_len) ||
4345         is_clause_inside_range (nested, clause->handler_offset, clause->handler_offset + clause->handler_len);
4346 }
4347
4348 /* Test the relationship between 2 exception clauses. Follow  P.1 12.4.2.7 of ECMA
4349  * the each pair of exception must have the following properties:
4350  *  - one is fully nested on another (the outer must not be a filter clause) (the nested one must come earlier)
4351  *  - completely disjoin (none of the 3 regions of each entry overlap with the other 3)
4352  *  - mutual protection (protected block is EXACT the same, handlers are disjoin and all handler are catch or all handler are filter)
4353  */
4354 static void
4355 verify_clause_relationship (VerifyContext *ctx, MonoExceptionClause *clause, MonoExceptionClause *to_test)
4356 {
4357         /*clause is nested*/
4358         if (to_test->flags == MONO_EXCEPTION_CLAUSE_FILTER && is_clause_inside_range (clause, to_test->data.filter_offset, to_test->handler_offset)) {
4359                 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Exception clause inside filter"));
4360                 return;
4361         }
4362
4363         /*wrong nesting order.*/
4364         if (is_clause_nested (clause, to_test)) {
4365                 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Nested exception clause appears after enclosing clause"));
4366                 return;
4367         }
4368
4369         /*mutual protection*/
4370         if (clause->try_offset == to_test->try_offset && clause->try_len == to_test->try_len) {
4371                 /*handlers are not disjoint*/
4372                 if (is_clause_in_range (to_test, HANDLER_START (clause), clause->handler_offset + clause->handler_len)) {
4373                         ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Exception handlers overlap"));
4374                         return;
4375                 }
4376                 /* handlers are not catch or filter */
4377                 if (!IS_CATCH_OR_FILTER (clause) || !IS_CATCH_OR_FILTER (to_test)) {
4378                         ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Exception clauses with shared protected block are neither catch or filter"));
4379                         return;
4380                 }
4381                 /*OK*/
4382                 return;
4383         }
4384
4385         /*not completelly disjoint*/
4386         if ((is_clause_in_range (to_test, clause->try_offset, clause->try_offset + clause->try_len) ||
4387                 is_clause_in_range (to_test, HANDLER_START (clause), clause->handler_offset + clause->handler_len)) && !is_clause_nested (to_test, clause))
4388                 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Exception clauses overlap"));
4389 }
4390
4391 #define code_bounds_check(size) \
4392         if (ADDP_IS_GREATER_OR_OVF (ip, size, end)) {\
4393                 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Code overrun starting with 0x%x at 0x%04x", *ip, ctx.ip_offset)); \
4394                 break; \
4395         } \
4396
4397 static gboolean
4398 mono_opcode_is_prefix (int op)
4399 {
4400         switch (op) {
4401         case MONO_CEE_UNALIGNED_:
4402         case MONO_CEE_VOLATILE_:
4403         case MONO_CEE_TAIL_:
4404         case MONO_CEE_CONSTRAINED_:
4405         case MONO_CEE_READONLY_:
4406                 return TRUE;
4407         }
4408         return FALSE;
4409 }
4410
4411 /*
4412  * FIXME: need to distinguish between valid and verifiable.
4413  * Need to keep track of types on the stack.
4414  * Verify types for opcodes.
4415  */
4416 GSList*
4417 mono_method_verify (MonoMethod *method, int level)
4418 {
4419         MonoError error;
4420         const unsigned char *ip, *code_start;
4421         const unsigned char *end;
4422         MonoSimpleBasicBlock *bb = NULL, *original_bb = NULL;
4423
4424         int i, n, need_merge = 0, start = 0;
4425         guint token, ip_offset = 0, prefix = 0;
4426         MonoGenericContext *generic_context = NULL;
4427         MonoImage *image;
4428         VerifyContext ctx;
4429         GSList *tmp;
4430         VERIFIER_DEBUG ( printf ("Verify IL for method %s %s %s\n",  method->klass->name_space,  method->klass->name, method->name); );
4431
4432         init_verifier_stats ();
4433
4434         if (method->iflags & (METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL | METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
4435                         (method->flags & (METHOD_ATTRIBUTE_PINVOKE_IMPL | METHOD_ATTRIBUTE_ABSTRACT))) {
4436                 return NULL;
4437         }
4438
4439         memset (&ctx, 0, sizeof (VerifyContext));
4440
4441         //FIXME use mono_method_get_signature_full
4442         ctx.signature = mono_method_signature (method);
4443         if (!ctx.signature) {
4444                 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Could not decode method signature"));
4445
4446                 finish_collect_stats ();
4447                 return ctx.list;
4448         }
4449         ctx.header = mono_method_get_header (method);
4450         if (!ctx.header) {
4451                 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Could not decode method header"));
4452                 finish_collect_stats ();
4453                 return ctx.list;
4454         }
4455         ctx.method = method;
4456         code_start = ip = ctx.header->code;
4457         end = ip + ctx.header->code_size;
4458         ctx.image = image = method->klass->image;
4459
4460
4461         ctx.max_args = ctx.signature->param_count + ctx.signature->hasthis;
4462         ctx.max_stack = ctx.header->max_stack;
4463         ctx.verifiable = ctx.valid = 1;
4464         ctx.level = level;
4465
4466         ctx.code = g_new (ILCodeDesc, ctx.header->code_size);
4467         ctx.code_size = ctx.header->code_size;
4468         MEM_ALLOC (sizeof (ILCodeDesc) * ctx.header->code_size);
4469
4470         memset(ctx.code, 0, sizeof (ILCodeDesc) * ctx.header->code_size);
4471
4472         ctx.num_locals = ctx.header->num_locals;
4473         ctx.locals = g_memdup (ctx.header->locals, sizeof (MonoType*) * ctx.header->num_locals);
4474         MEM_ALLOC (sizeof (MonoType*) * ctx.header->num_locals);
4475
4476         if (ctx.num_locals > 0 && !ctx.header->init_locals)
4477                 CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Method with locals variable but without init locals set"));
4478
4479         ctx.params = g_new (MonoType*, ctx.max_args);
4480         MEM_ALLOC (sizeof (MonoType*) * ctx.max_args);
4481
4482         if (ctx.signature->hasthis)
4483                 ctx.params [0] = method->klass->valuetype ? &method->klass->this_arg : &method->klass->byval_arg;
4484         memcpy (ctx.params + ctx.signature->hasthis, ctx.signature->params, sizeof (MonoType *) * ctx.signature->param_count);
4485
4486         if (ctx.signature->is_inflated)
4487                 ctx.generic_context = generic_context = mono_method_get_context (method);
4488
4489         if (!generic_context && (method->klass->generic_container || method->is_generic)) {
4490                 if (method->is_generic)
4491                         ctx.generic_context = generic_context = &(mono_method_get_generic_container (method)->context);
4492                 else
4493                         ctx.generic_context = generic_context = &method->klass->generic_container->context;
4494         }
4495
4496         for (i = 0; i < ctx.num_locals; ++i) {
4497                 MonoType *uninflated = ctx.locals [i];
4498                 ctx.locals [i] = mono_class_inflate_generic_type_checked (ctx.locals [i], ctx.generic_context, &error);
4499                 if (!mono_error_ok (&error)) {
4500                         char *name = mono_type_full_name (ctx.locals [i] ? ctx.locals [i] : uninflated);
4501                         ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid local %d of type %s", i, name));
4502                         g_free (name);
4503                         mono_error_cleanup (&error);
4504                         /* we must not free (in cleanup) what was not yet allocated (but only copied) */
4505                         ctx.num_locals = i;
4506                         ctx.max_args = 0;
4507                         goto cleanup;
4508                 }
4509         }
4510         for (i = 0; i < ctx.max_args; ++i) {
4511                 MonoType *uninflated = ctx.params [i];
4512                 ctx.params [i] = mono_class_inflate_generic_type_checked (ctx.params [i], ctx.generic_context, &error);
4513                 if (!mono_error_ok (&error)) {
4514                         char *name = mono_type_full_name (ctx.params [i] ? ctx.params [i] : uninflated);
4515                         ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid parameter %d of type %s", i, name));
4516                         g_free (name);
4517                         mono_error_cleanup (&error);
4518                         /* we must not free (in cleanup) what was not yet allocated (but only copied) */
4519                         ctx.max_args = i;
4520                         goto cleanup;
4521                 }
4522         }
4523         stack_init (&ctx, &ctx.eval);
4524
4525         for (i = 0; i < ctx.num_locals; ++i) {
4526                 if (!mono_type_is_valid_in_context (&ctx, ctx.locals [i]))
4527                         break;
4528                 if (get_stack_type (ctx.locals [i]) == TYPE_INV) {
4529                         char *name = mono_type_full_name (ctx.locals [i]);
4530                         ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid local %i of type %s", i, name));
4531                         g_free (name);
4532                         break;
4533                 }
4534                 
4535         }
4536
4537         for (i = 0; i < ctx.max_args; ++i) {
4538                 if (!mono_type_is_valid_in_context (&ctx, ctx.params [i]))
4539                         break;
4540
4541                 if (get_stack_type (ctx.params [i]) == TYPE_INV) {
4542                         char *name = mono_type_full_name (ctx.params [i]);
4543                         ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid parameter %i of type %s", i, name));
4544                         g_free (name);
4545                         break;
4546                 }
4547         }
4548
4549         if (!ctx.valid)
4550                 goto cleanup;
4551
4552         for (i = 0; i < ctx.header->num_clauses && ctx.valid; ++i) {
4553                 MonoExceptionClause *clause = ctx.header->clauses + i;
4554                 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); );
4555
4556                 if (clause->try_offset > ctx.code_size || ADD_IS_GREATER_OR_OVF (clause->try_offset, clause->try_len, ctx.code_size))
4557                         ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("try clause out of bounds at 0x%04x", clause->try_offset));
4558
4559                 if (clause->try_len <= 0)
4560                         ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("try clause len <= 0 at 0x%04x", clause->try_offset));
4561
4562                 if (clause->handler_offset > ctx.code_size || ADD_IS_GREATER_OR_OVF (clause->handler_offset, clause->handler_len, ctx.code_size))
4563                         ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("handler clause out of bounds at 0x%04x", clause->try_offset));
4564
4565                 if (clause->handler_len <= 0)
4566                         ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("handler clause len <= 0 at 0x%04x", clause->try_offset));
4567
4568                 if (clause->try_offset < clause->handler_offset && ADD_IS_GREATER_OR_OVF (clause->try_offset, clause->try_len, HANDLER_START (clause)))
4569                         ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("try block (at 0x%04x) includes handler block (at 0x%04x)", clause->try_offset, clause->handler_offset));
4570
4571                 if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
4572                         if (clause->data.filter_offset > ctx.code_size)
4573                                 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("filter clause out of bounds at 0x%04x", clause->try_offset));
4574
4575                         if (clause->data.filter_offset >= clause->handler_offset)
4576                                 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("filter clause must come before the handler clause at 0x%04x", clause->data.filter_offset));
4577                 }
4578
4579                 for (n = i + 1; n < ctx.header->num_clauses && ctx.valid; ++n)
4580                         verify_clause_relationship (&ctx, clause, ctx.header->clauses + n);
4581
4582                 if (!ctx.valid)
4583                         break;
4584
4585                 ctx.code [clause->try_offset].flags |= IL_CODE_FLAG_WAS_TARGET;
4586                 if (clause->try_offset + clause->try_len < ctx.code_size)
4587                         ctx.code [clause->try_offset + clause->try_len].flags |= IL_CODE_FLAG_WAS_TARGET;
4588                 if (clause->handler_offset + clause->handler_len < ctx.code_size)
4589                         ctx.code [clause->handler_offset + clause->handler_len].flags |= IL_CODE_FLAG_WAS_TARGET;
4590
4591                 if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE) {
4592                         if (!clause->data.catch_class) {
4593                                 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Catch clause %d with invalid type", i));
4594                                 break;
4595                         }
4596                 
4597                         init_stack_with_value_at_exception_boundary (&ctx, ctx.code + clause->handler_offset, clause->data.catch_class);
4598                 }
4599                 else if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
4600                         init_stack_with_value_at_exception_boundary (&ctx, ctx.code + clause->data.filter_offset, mono_defaults.exception_class);
4601                         init_stack_with_value_at_exception_boundary (&ctx, ctx.code + clause->handler_offset, mono_defaults.exception_class);   
4602                 }
4603         }
4604
4605         original_bb = bb = mono_basic_block_split (method, &error);
4606         if (!mono_error_ok (&error)) {
4607                 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid branch target: %s", mono_error_get_message (&error)));
4608                 mono_error_cleanup (&error);
4609                 goto cleanup;
4610         }
4611         g_assert (bb);
4612
4613         while (ip < end && ctx.valid) {
4614                 ip_offset = ip - code_start;
4615                 {
4616                         const unsigned char *ip_copy = ip;
4617                         int size, op;
4618
4619                         if (ip_offset > bb->end) {
4620                                 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Branch or EH block at [0x%04x] targets middle instruction at 0x%04x", bb->end, ip_offset));
4621                                 goto cleanup;
4622                         }
4623
4624                         if (ip_offset == bb->end)
4625                                 bb = bb->next;
4626         
4627                         size = mono_opcode_value_and_size (&ip_copy, end, &op);
4628                         if (size == -1) {
4629                                 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid instruction %x at 0x%04x", *ip, ip_offset));
4630                                 goto cleanup;
4631                         }
4632
4633                         if (ADD_IS_GREATER_OR_OVF (ip_offset, size, bb->end)) {
4634                                 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Branch or EH block targets middle of instruction at 0x%04x", ip_offset));
4635                                 goto cleanup;
4636                         }
4637
4638                         /*Last Instruction*/
4639                         if (ip_offset + size == bb->end && mono_opcode_is_prefix (op)) {
4640                                 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Branch or EH block targets between prefix '%s' and instruction at 0x%04x", mono_opcode_name (op), ip_offset));
4641                                 goto cleanup;
4642                         }
4643
4644                         if (bb->dead) {
4645                                 /*FIXME remove this once we move all bad branch checking code to use BB only*/
4646                                 ctx.code [ip_offset].flags |= IL_CODE_FLAG_SEEN;
4647                                 ip += size;
4648                                 continue;
4649                         }
4650                 }
4651
4652                 ctx.ip_offset = ip_offset = ip - code_start;
4653
4654                 /*We need to check against fallthrou in and out of protected blocks.
4655                  * For fallout we check the once a protected block ends, if the start flag is not set.
4656                  * Likewise for fallthru in, we check if ip is the start of a protected block and start is not set
4657                  * TODO convert these checks to be done using flags and not this loop
4658                  */
4659                 for (i = 0; i < ctx.header->num_clauses && ctx.valid; ++i) {
4660                         MonoExceptionClause *clause = ctx.header->clauses + i;
4661
4662                         if ((clause->try_offset + clause->try_len == ip_offset) && start == 0) {
4663                                 CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("fallthru off try block at 0x%04x", ip_offset));
4664                                 start = 1;
4665                         }
4666
4667                         if ((clause->handler_offset + clause->handler_len == ip_offset) && start == 0) {
4668                                 if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER)
4669                                         ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("fallout of handler block at 0x%04x", ip_offset));
4670                                 else
4671                                         CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("fallout of handler block at 0x%04x", ip_offset));
4672                                 start = 1;
4673                         }
4674
4675                         if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER && clause->handler_offset == ip_offset && start == 0) {
4676                                 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("fallout of filter block at 0x%04x", ip_offset));
4677                                 start = 1;
4678                         }
4679
4680                         if (clause->handler_offset == ip_offset && start == 0) {
4681                                 CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("fallthru handler block at 0x%04x", ip_offset));
4682                                 start = 1;
4683                         }
4684
4685                         if (clause->try_offset == ip_offset && ctx.eval.size > 0 && start == 0) {
4686                                 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Try to enter try block with a non-empty stack at 0x%04x", ip_offset));
4687                                 start = 1;
4688                         }
4689                 }
4690
4691                 if (!ctx.valid)
4692                         break;
4693
4694                 if (need_merge) {
4695                         VERIFIER_DEBUG ( printf ("extra merge needed! 0x%04x \n", ctx.target); );
4696                         merge_stacks (&ctx, &ctx.eval, &ctx.code [ctx.target], FALSE, TRUE);
4697                         need_merge = 0; 
4698                 }
4699                 merge_stacks (&ctx, &ctx.eval, &ctx.code[ip_offset], start, FALSE);
4700                 start = 0;
4701
4702                 /*TODO we can fast detect a forward branch or exception block targeting code after prefix, we should fail fast*/
4703 #ifdef MONO_VERIFIER_DEBUG
4704                 {
4705                         char *discode;
4706                         discode = mono_disasm_code_one (NULL, method, ip, NULL);
4707                         discode [strlen (discode) - 1] = 0; /* no \n */
4708                         g_print ("[%d] %-29s (%d)\n",  ip_offset, discode, ctx.eval.size);
4709                         g_free (discode);
4710                 }
4711                 dump_stack_state (&ctx.code [ip_offset]);
4712                 dump_stack_state (&ctx.eval);
4713 #endif
4714
4715                 switch (*ip) {
4716                 case CEE_NOP:
4717                 case CEE_BREAK:
4718                         ++ip;
4719                         break;
4720
4721                 case CEE_LDARG_0:
4722                 case CEE_LDARG_1:
4723                 case CEE_LDARG_2:
4724                 case CEE_LDARG_3:
4725                         push_arg (&ctx, *ip - CEE_LDARG_0, FALSE);
4726                         ++ip;
4727                         break;
4728
4729                 case CEE_LDARG_S:
4730                 case CEE_LDARGA_S:
4731                         code_bounds_check (2);
4732                         push_arg (&ctx, ip [1],  *ip == CEE_LDARGA_S);
4733                         ip += 2;
4734                         break;
4735
4736                 case CEE_ADD_OVF_UN:
4737                         do_binop (&ctx, *ip, add_ovf_un_table);
4738                         ++ip;
4739                         break;
4740
4741                 case CEE_SUB_OVF_UN:
4742                         do_binop (&ctx, *ip, sub_ovf_un_table);
4743                         ++ip;
4744                         break;
4745
4746                 case CEE_ADD_OVF:
4747                 case CEE_SUB_OVF:
4748                 case CEE_MUL_OVF:
4749                 case CEE_MUL_OVF_UN:
4750                         do_binop (&ctx, *ip, bin_ovf_table);
4751                         ++ip;
4752                         break;
4753
4754                 case CEE_ADD:
4755                         do_binop (&ctx, *ip, add_table);
4756                         ++ip;
4757                         break;
4758
4759                 case CEE_SUB:
4760                         do_binop (&ctx, *ip, sub_table);
4761                         ++ip;
4762                         break;
4763
4764                 case CEE_MUL:
4765                 case CEE_DIV:
4766                 case CEE_REM:
4767                         do_binop (&ctx, *ip, bin_op_table);
4768                         ++ip;
4769                         break;
4770
4771                 case CEE_AND:
4772                 case CEE_DIV_UN:
4773                 case CEE_OR:
4774                 case CEE_REM_UN:
4775                 case CEE_XOR:
4776                         do_binop (&ctx, *ip, int_bin_op_table);
4777                         ++ip;
4778                         break;
4779
4780                 case CEE_SHL:
4781                 case CEE_SHR:
4782                 case CEE_SHR_UN:
4783                         do_binop (&ctx, *ip, shift_op_table);
4784                         ++ip;
4785                         break;
4786
4787                 case CEE_POP:
4788                         if (!check_underflow (&ctx, 1))
4789                                 break;
4790                         stack_pop_safe (&ctx);
4791                         ++ip;
4792                         break;
4793
4794                 case CEE_RET:
4795                         do_ret (&ctx);
4796                         ++ip;
4797                         start = 1;
4798                         break;
4799
4800                 case CEE_LDLOC_0:
4801                 case CEE_LDLOC_1:
4802                 case CEE_LDLOC_2:
4803                 case CEE_LDLOC_3:
4804                         /*TODO support definite assignment verification? */
4805                         push_local (&ctx, *ip - CEE_LDLOC_0, FALSE);
4806                         ++ip;
4807                         break;
4808
4809                 case CEE_STLOC_0:
4810                 case CEE_STLOC_1:
4811                 case CEE_STLOC_2:
4812                 case CEE_STLOC_3:
4813                         store_local (&ctx, *ip - CEE_STLOC_0);
4814                         ++ip;
4815                         break;
4816
4817                 case CEE_STLOC_S:
4818                         code_bounds_check (2);
4819                         store_local (&ctx, ip [1]);
4820                         ip += 2;
4821                         break;
4822
4823                 case CEE_STARG_S:
4824                         code_bounds_check (2);
4825                         store_arg (&ctx, ip [1]);
4826                         ip += 2;
4827                         break;
4828
4829                 case CEE_LDC_I4_M1:
4830                 case CEE_LDC_I4_0:
4831                 case CEE_LDC_I4_1:
4832                 case CEE_LDC_I4_2:
4833                 case CEE_LDC_I4_3:
4834                 case CEE_LDC_I4_4:
4835                 case CEE_LDC_I4_5:
4836                 case CEE_LDC_I4_6:
4837                 case CEE_LDC_I4_7:
4838                 case CEE_LDC_I4_8:
4839                         if (check_overflow (&ctx))
4840                                 stack_push_val (&ctx, TYPE_I4, &mono_defaults.int32_class->byval_arg);
4841                         ++ip;
4842                         break;
4843
4844                 case CEE_LDC_I4_S:
4845                         code_bounds_check (2);
4846                         if (check_overflow (&ctx))
4847                                 stack_push_val (&ctx, TYPE_I4, &mono_defaults.int32_class->byval_arg);
4848                         ip += 2;
4849                         break;
4850
4851                 case CEE_LDC_I4:
4852                         code_bounds_check (5);
4853                         if (check_overflow (&ctx))
4854                                 stack_push_val (&ctx,TYPE_I4, &mono_defaults.int32_class->byval_arg);
4855                         ip += 5;
4856                         break;
4857
4858                 case CEE_LDC_I8:
4859                         code_bounds_check (9);
4860                         if (check_overflow (&ctx))
4861                                 stack_push_val (&ctx,TYPE_I8, &mono_defaults.int64_class->byval_arg);
4862                         ip += 9;
4863                         break;
4864
4865                 case CEE_LDC_R4:
4866                         code_bounds_check (5);
4867                         if (check_overflow (&ctx))
4868                                 stack_push_val (&ctx, TYPE_R8, &mono_defaults.double_class->byval_arg);
4869                         ip += 5;
4870                         break;
4871
4872                 case CEE_LDC_R8:
4873                         code_bounds_check (9);
4874                         if (check_overflow (&ctx))
4875                                 stack_push_val (&ctx, TYPE_R8, &mono_defaults.double_class->byval_arg);
4876                         ip += 9;
4877                         break;
4878
4879                 case CEE_LDNULL:
4880                         if (check_overflow (&ctx))
4881                                 stack_push_val (&ctx, TYPE_COMPLEX | NULL_LITERAL_MASK, &mono_defaults.object_class->byval_arg);
4882                         ++ip;
4883                         break;
4884
4885                 case CEE_BEQ_S:
4886                 case CEE_BNE_UN_S:
4887                         code_bounds_check (2);
4888                         do_branch_op (&ctx, (signed char)ip [1] + 2, cmp_br_eq_op);
4889                         ip += 2;
4890                         need_merge = 1;
4891                         break;
4892
4893                 case CEE_BGE_S:
4894                 case CEE_BGT_S:
4895                 case CEE_BLE_S:
4896                 case CEE_BLT_S:
4897                 case CEE_BGE_UN_S:
4898                 case CEE_BGT_UN_S:
4899                 case CEE_BLE_UN_S:
4900                 case CEE_BLT_UN_S:
4901                         code_bounds_check (2);
4902                         do_branch_op (&ctx, (signed char)ip [1] + 2, cmp_br_op);
4903                         ip += 2;
4904                         need_merge = 1;
4905                         break;
4906
4907                 case CEE_BEQ:
4908                 case CEE_BNE_UN:
4909                         code_bounds_check (5);
4910                         do_branch_op (&ctx, (gint32)read32 (ip + 1) + 5, cmp_br_eq_op);
4911                         ip += 5;
4912                         need_merge = 1;
4913                         break;
4914
4915                 case CEE_BGE:
4916                 case CEE_BGT:
4917                 case CEE_BLE:
4918                 case CEE_BLT:
4919                 case CEE_BGE_UN:
4920                 case CEE_BGT_UN:
4921                 case CEE_BLE_UN:
4922                 case CEE_BLT_UN:
4923                         code_bounds_check (5);
4924                         do_branch_op (&ctx, (gint32)read32 (ip + 1) + 5, cmp_br_op);
4925                         ip += 5;
4926                         need_merge = 1;
4927                         break;
4928
4929                 case CEE_LDLOC_S:
4930                 case CEE_LDLOCA_S:
4931                         code_bounds_check (2);
4932                         push_local (&ctx, ip[1], *ip == CEE_LDLOCA_S);
4933                         ip += 2;
4934                         break;
4935
4936                 case CEE_UNUSED99:
4937                         ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Use of the `unused' opcode"));
4938                         ++ip;
4939                         break; 
4940
4941                 case CEE_DUP: {
4942                         ILStackDesc *top;
4943                         if (!check_underflow (&ctx, 1))
4944                                 break;
4945                         if (!check_overflow (&ctx))
4946                                 break;
4947                         top = stack_push (&ctx);
4948                         copy_stack_value (top, stack_peek (&ctx, 1));
4949                         ++ip;
4950                         break;
4951                 }
4952
4953                 case CEE_JMP:
4954                         code_bounds_check (5);
4955                         if (ctx.eval.size)
4956                                 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Eval stack must be empty in jmp at 0x%04x", ip_offset));
4957                         token = read32 (ip + 1);
4958                         if (in_any_block (ctx.header, ip_offset))
4959                                 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("jmp cannot escape exception blocks at 0x%04x", ip_offset));
4960
4961                         CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Intruction jmp is not verifiable at 0x%04x", ctx.ip_offset));
4962                         /*
4963                          * FIXME: check signature, retval, arguments etc.
4964                          */
4965                         ip += 5;
4966                         break;
4967                 case CEE_CALL:
4968                 case CEE_CALLVIRT:
4969                         code_bounds_check (5);
4970                         do_invoke_method (&ctx, read32 (ip + 1), *ip == CEE_CALLVIRT);
4971                         ip += 5;
4972                         break;
4973
4974                 case CEE_CALLI:
4975                         code_bounds_check (5);
4976                         token = read32 (ip + 1);
4977                         /*
4978                          * FIXME: check signature, retval, arguments etc.
4979                          * FIXME: check requirements for tail call
4980                          */
4981                         CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Intruction calli is not verifiable at 0x%04x", ctx.ip_offset));
4982                         ip += 5;
4983                         break;
4984                 case CEE_BR_S:
4985                         code_bounds_check (2);
4986                         do_static_branch (&ctx, (signed char)ip [1] + 2);
4987                         need_merge = 1;
4988                         ip += 2;
4989                         start = 1;
4990                         break;
4991
4992                 case CEE_BRFALSE_S:
4993                 case CEE_BRTRUE_S:
4994                         code_bounds_check (2);
4995                         do_boolean_branch_op (&ctx, (signed char)ip [1] + 2);
4996                         ip += 2;
4997                         need_merge = 1;
4998                         break;
4999
5000                 case CEE_BR:
5001                         code_bounds_check (5);
5002                         do_static_branch (&ctx, (gint32)read32 (ip + 1) + 5);
5003                         need_merge = 1;
5004                         ip += 5;
5005                         start = 1;
5006                         break;
5007
5008                 case CEE_BRFALSE:
5009                 case CEE_BRTRUE:
5010                         code_bounds_check (5);
5011                         do_boolean_branch_op (&ctx, (gint32)read32 (ip + 1) + 5);
5012                         ip += 5;
5013                         need_merge = 1;
5014                         break;
5015
5016                 case CEE_SWITCH: {
5017                         guint32 entries;
5018                         code_bounds_check (5);
5019                         entries = read32 (ip + 1);
5020
5021                         if (entries > 0xFFFFFFFFU / sizeof (guint32))
5022                                 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Too many switch entries %x at 0x%04x", entries, ctx.ip_offset));
5023
5024                         ip += 5;
5025                         code_bounds_check (sizeof (guint32) * entries);
5026                         
5027                         do_switch (&ctx, entries, ip);
5028                         ip += sizeof (guint32) * entries;
5029                         break;
5030                 }
5031                 case CEE_LDIND_I1:
5032                 case CEE_LDIND_U1:
5033                 case CEE_LDIND_I2:
5034                 case CEE_LDIND_U2:
5035                 case CEE_LDIND_I4:
5036                 case CEE_LDIND_U4:
5037                 case CEE_LDIND_I8:
5038                 case CEE_LDIND_I:
5039                 case CEE_LDIND_R4:
5040                 case CEE_LDIND_R8:
5041                 case CEE_LDIND_REF:
5042                         do_load_indirect (&ctx, *ip);
5043                         ++ip;
5044                         break;
5045                         
5046                 case CEE_STIND_REF:
5047                 case CEE_STIND_I1:
5048                 case CEE_STIND_I2:
5049                 case CEE_STIND_I4:
5050                 case CEE_STIND_I8:
5051                 case CEE_STIND_R4:
5052                 case CEE_STIND_R8:
5053                 case CEE_STIND_I:
5054                         do_store_indirect (&ctx, *ip);
5055                         ++ip;
5056                         break;
5057
5058                 case CEE_NOT:
5059                 case CEE_NEG:
5060                         do_unary_math_op (&ctx, *ip);
5061                         ++ip;
5062                         break;
5063
5064                 case CEE_CONV_I1:
5065                 case CEE_CONV_I2:
5066                 case CEE_CONV_I4:
5067                 case CEE_CONV_U1:
5068                 case CEE_CONV_U2:
5069                 case CEE_CONV_U4:
5070                         do_conversion (&ctx, TYPE_I4);
5071                         ++ip;
5072                         break;                  
5073
5074                 case CEE_CONV_I8:
5075                 case CEE_CONV_U8:
5076                         do_conversion (&ctx, TYPE_I8);
5077                         ++ip;
5078                         break;                  
5079
5080                 case CEE_CONV_R4:
5081                 case CEE_CONV_R8:
5082                 case CEE_CONV_R_UN:
5083                         do_conversion (&ctx, TYPE_R8);
5084                         ++ip;
5085                         break;                  
5086
5087                 case CEE_CONV_I:
5088                 case CEE_CONV_U:
5089                         do_conversion (&ctx, TYPE_NATIVE_INT);
5090                         ++ip;
5091                         break;
5092
5093                 case CEE_CPOBJ:
5094                         code_bounds_check (5);
5095                         do_cpobj (&ctx, read32 (ip + 1));
5096                         ip += 5;
5097                         break;
5098
5099                 case CEE_LDOBJ:
5100                         code_bounds_check (5);
5101                         do_ldobj_value (&ctx, read32 (ip + 1));
5102                         ip += 5;
5103                         break;
5104
5105                 case CEE_LDSTR:
5106                         code_bounds_check (5);
5107                         do_ldstr (&ctx, read32 (ip + 1));
5108                         ip += 5;
5109                         break;
5110
5111                 case CEE_NEWOBJ:
5112                         code_bounds_check (5);
5113                         do_newobj (&ctx, read32 (ip + 1));
5114                         ip += 5;
5115                         break;
5116
5117                 case CEE_CASTCLASS:
5118                 case CEE_ISINST:
5119                         code_bounds_check (5);
5120                         do_cast (&ctx, read32 (ip + 1), *ip == CEE_CASTCLASS ? "castclass" : "isinst");
5121                         ip += 5;
5122                         break;
5123
5124                 case CEE_UNUSED58:
5125                 case CEE_UNUSED1:
5126                         ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Use of the `unused' opcode"));
5127                         ++ip;
5128                         break;
5129
5130                 case CEE_UNBOX:
5131                         code_bounds_check (5);
5132                         do_unbox_value (&ctx, read32 (ip + 1));
5133                         ip += 5;
5134                         break;
5135
5136                 case CEE_THROW:
5137                         do_throw (&ctx);
5138                         start = 1;
5139                         ++ip;
5140                         break;
5141
5142                 case CEE_LDFLD:
5143                 case CEE_LDFLDA:
5144                         code_bounds_check (5);
5145                         do_push_field (&ctx, read32 (ip + 1), *ip == CEE_LDFLDA);
5146                         ip += 5;
5147                         break;
5148
5149                 case CEE_LDSFLD:
5150                 case CEE_LDSFLDA:
5151                         code_bounds_check (5);
5152                         do_push_static_field (&ctx, read32 (ip + 1), *ip == CEE_LDSFLDA);
5153                         ip += 5;
5154                         break;
5155
5156                 case CEE_STFLD:
5157                         code_bounds_check (5);
5158                         do_store_field (&ctx, read32 (ip + 1));
5159                         ip += 5;
5160                         break;
5161
5162                 case CEE_STSFLD:
5163                         code_bounds_check (5);
5164                         do_store_static_field (&ctx, read32 (ip + 1));
5165                         ip += 5;
5166                         break;
5167
5168                 case CEE_STOBJ:
5169                         code_bounds_check (5);
5170                         do_stobj (&ctx, read32 (ip + 1));
5171                         ip += 5;
5172                         break;
5173
5174                 case CEE_CONV_OVF_I1_UN:
5175                 case CEE_CONV_OVF_I2_UN:
5176                 case CEE_CONV_OVF_I4_UN:
5177                 case CEE_CONV_OVF_U1_UN:
5178                 case CEE_CONV_OVF_U2_UN:
5179                 case CEE_CONV_OVF_U4_UN:
5180                         do_conversion (&ctx, TYPE_I4);
5181                         ++ip;
5182                         break;                  
5183
5184                 case CEE_CONV_OVF_I8_UN:
5185                 case CEE_CONV_OVF_U8_UN:
5186                         do_conversion (&ctx, TYPE_I8);
5187                         ++ip;
5188                         break;                  
5189
5190                 case CEE_CONV_OVF_I_UN:
5191                 case CEE_CONV_OVF_U_UN:
5192                         do_conversion (&ctx, TYPE_NATIVE_INT);
5193                         ++ip;
5194                         break;
5195
5196                 case CEE_BOX:
5197                         code_bounds_check (5);
5198                         do_box_value (&ctx, read32 (ip + 1));
5199                         ip += 5;
5200                         break;
5201
5202                 case CEE_NEWARR:
5203                         code_bounds_check (5);
5204                         do_newarr (&ctx, read32 (ip + 1));
5205                         ip += 5;
5206                         break;
5207
5208                 case CEE_LDLEN:
5209                         do_ldlen (&ctx);
5210                         ++ip;
5211                         break;
5212
5213                 case CEE_LDELEMA:
5214                         code_bounds_check (5);
5215                         do_ldelema (&ctx, read32 (ip + 1));
5216                         ip += 5;
5217                         break;
5218
5219                 case CEE_LDELEM_I1:
5220                 case CEE_LDELEM_U1:
5221                 case CEE_LDELEM_I2:
5222                 case CEE_LDELEM_U2:
5223                 case CEE_LDELEM_I4:
5224                 case CEE_LDELEM_U4:
5225                 case CEE_LDELEM_I8:
5226                 case CEE_LDELEM_I:
5227                 case CEE_LDELEM_R4:
5228                 case CEE_LDELEM_R8:
5229                 case CEE_LDELEM_REF:
5230                         do_ldelem (&ctx, *ip, 0);
5231                         ++ip;
5232                         break;
5233
5234                 case CEE_STELEM_I:
5235                 case CEE_STELEM_I1:
5236                 case CEE_STELEM_I2:
5237                 case CEE_STELEM_I4:
5238                 case CEE_STELEM_I8:
5239                 case CEE_STELEM_R4:
5240                 case CEE_STELEM_R8:
5241                 case CEE_STELEM_REF:
5242                         do_stelem (&ctx, *ip, 0);
5243                         ++ip;
5244                         break;
5245
5246                 case CEE_LDELEM:
5247                         code_bounds_check (5);
5248                         do_ldelem (&ctx, *ip, read32 (ip + 1));
5249                         ip += 5;
5250                         break;
5251
5252                 case CEE_STELEM:
5253                         code_bounds_check (5);
5254                         do_stelem (&ctx, *ip, read32 (ip + 1));
5255                         ip += 5;
5256                         break;
5257                         
5258                 case CEE_UNBOX_ANY:
5259                         code_bounds_check (5);
5260                         do_unbox_any (&ctx, read32 (ip + 1));
5261                         ip += 5;
5262                         break;
5263
5264                 case CEE_CONV_OVF_I1:
5265                 case CEE_CONV_OVF_U1:
5266                 case CEE_CONV_OVF_I2:
5267                 case CEE_CONV_OVF_U2:
5268                 case CEE_CONV_OVF_I4:
5269                 case CEE_CONV_OVF_U4:
5270                         do_conversion (&ctx, TYPE_I4);
5271                         ++ip;
5272                         break;
5273
5274                 case CEE_CONV_OVF_I8:
5275                 case CEE_CONV_OVF_U8:
5276                         do_conversion (&ctx, TYPE_I8);
5277                         ++ip;
5278                         break;
5279
5280                 case CEE_CONV_OVF_I:
5281                 case CEE_CONV_OVF_U:
5282                         do_conversion (&ctx, TYPE_NATIVE_INT);
5283                         ++ip;
5284                         break;
5285
5286                 case CEE_REFANYVAL:
5287                         code_bounds_check (5);
5288                         do_refanyval (&ctx, read32 (ip + 1));
5289                         ip += 5;
5290                         break;
5291
5292                 case CEE_CKFINITE:
5293                         do_ckfinite (&ctx);
5294                         ++ip;
5295                         break;
5296
5297                 case CEE_MKREFANY:
5298                         code_bounds_check (5);
5299                         do_mkrefany (&ctx,  read32 (ip + 1));
5300                         ip += 5;
5301                         break;
5302
5303                 case CEE_LDTOKEN:
5304                         code_bounds_check (5);
5305                         do_load_token (&ctx, read32 (ip + 1));
5306                         ip += 5;
5307                         break;
5308
5309                 case CEE_ENDFINALLY:
5310                         if (!is_correct_endfinally (ctx.header, ip_offset))
5311                                 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("endfinally must be used inside a finally/fault handler at 0x%04x", ctx.ip_offset));
5312                         ctx.eval.size = 0;
5313                         start = 1;
5314                         ++ip;
5315                         break;
5316
5317                 case CEE_LEAVE:
5318                         code_bounds_check (5);
5319                         do_leave (&ctx, read32 (ip + 1) + 5);
5320                         ip += 5;
5321                         start = 1;
5322                         break;
5323
5324                 case CEE_LEAVE_S:
5325                         code_bounds_check (2);
5326                         do_leave (&ctx, (signed char)ip [1] + 2);
5327                         ip += 2;
5328                         start = 1;
5329                         break;
5330
5331                 case CEE_PREFIX1:
5332                         code_bounds_check (2);
5333                         ++ip;
5334                         switch (*ip) {
5335                         case CEE_STLOC:
5336                                 code_bounds_check (3);
5337                                 store_local (&ctx, read16 (ip + 1));
5338                                 ip += 3;
5339                                 break;
5340
5341                         case CEE_CEQ:
5342                                 do_cmp_op (&ctx, cmp_br_eq_op, *ip);
5343                                 ++ip;
5344                                 break;
5345
5346                         case CEE_CGT:
5347                         case CEE_CGT_UN:
5348                         case CEE_CLT:
5349                         case CEE_CLT_UN:
5350                                 do_cmp_op (&ctx, cmp_br_op, *ip);
5351                                 ++ip;
5352                                 break;
5353
5354                         case CEE_STARG:
5355                                 code_bounds_check (3);
5356                                 store_arg (&ctx, read16 (ip + 1) );
5357                                 ip += 3;
5358                                 break;
5359
5360
5361                         case CEE_ARGLIST:
5362                                 check_overflow (&ctx);
5363                                 if (ctx.signature->call_convention != MONO_CALL_VARARG)
5364                                         ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Cannot use arglist on method without VARGARG calling convention at 0x%04x", ctx.ip_offset));
5365                                 set_stack_value (&ctx, stack_push (&ctx), &mono_defaults.argumenthandle_class->byval_arg, FALSE);
5366                                 ++ip;
5367                                 break;
5368         
5369                         case CEE_LDFTN:
5370                                 code_bounds_check (5);
5371                                 do_load_function_ptr (&ctx, read32 (ip + 1), FALSE);
5372                                 ip += 5;
5373                                 break;
5374
5375                         case CEE_LDVIRTFTN:
5376                                 code_bounds_check (5);
5377                                 do_load_function_ptr (&ctx, read32 (ip + 1), TRUE);
5378                                 ip += 5;
5379                                 break;
5380
5381                         case CEE_LDARG:
5382                         case CEE_LDARGA:
5383                                 code_bounds_check (3);
5384                                 push_arg (&ctx, read16 (ip + 1),  *ip == CEE_LDARGA);
5385                                 ip += 3;
5386                                 break;
5387
5388                         case CEE_LDLOC:
5389                         case CEE_LDLOCA:
5390                                 code_bounds_check (3);
5391                                 push_local (&ctx, read16 (ip + 1), *ip == CEE_LDLOCA);
5392                                 ip += 3;
5393                                 break;
5394
5395                         case CEE_LOCALLOC:
5396                                 do_localloc (&ctx);
5397                                 ++ip;
5398                                 break;
5399
5400                         case CEE_UNUSED56:
5401                         case CEE_UNUSED57:
5402                         case CEE_UNUSED70:
5403                         case CEE_UNUSED:
5404                                 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Use of the `unused' opcode"));
5405                                 ++ip;
5406                                 break;
5407                         case CEE_ENDFILTER:
5408                                 do_endfilter (&ctx);
5409                                 start = 1;
5410                                 ++ip;
5411                                 break;
5412                         case CEE_UNALIGNED_:
5413                                 code_bounds_check (2);
5414                                 prefix |= PREFIX_UNALIGNED;
5415                                 ip += 2;
5416                                 break;
5417                         case CEE_VOLATILE_:
5418                                 prefix |= PREFIX_VOLATILE;
5419                                 ++ip;
5420                                 break;
5421                         case CEE_TAIL_:
5422                                 prefix |= PREFIX_TAIL;
5423                                 ++ip;
5424                                 if (ip < end && (*ip != CEE_CALL && *ip != CEE_CALLI && *ip != CEE_CALLVIRT))
5425                                         ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("tail prefix must be used only with call opcodes at 0x%04x", ip_offset));
5426                                 break;
5427
5428                         case CEE_INITOBJ:
5429                                 code_bounds_check (5);
5430                                 do_initobj (&ctx, read32 (ip + 1));
5431                                 ip += 5;
5432                                 break;
5433
5434                         case CEE_CONSTRAINED_:
5435                                 code_bounds_check (5);
5436                                 ctx.constrained_type = get_boxable_mono_type (&ctx, read32 (ip + 1), "constrained.");
5437                                 prefix |= PREFIX_CONSTRAINED;
5438                                 ip += 5;
5439                                 break;
5440         
5441                         case CEE_READONLY_:
5442                                 prefix |= PREFIX_READONLY;
5443                                 ip++;
5444                                 break;
5445
5446                         case CEE_CPBLK:
5447                                 CLEAR_PREFIX (&ctx, PREFIX_UNALIGNED | PREFIX_VOLATILE);
5448                                 if (!check_underflow (&ctx, 3))
5449                                         break;
5450                                 CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Instruction cpblk is not verifiable at 0x%04x", ctx.ip_offset));
5451                                 ip++;
5452                                 break;
5453                                 
5454                         case CEE_INITBLK:
5455                                 CLEAR_PREFIX (&ctx, PREFIX_UNALIGNED | PREFIX_VOLATILE);
5456                                 if (!check_underflow (&ctx, 3))
5457                                         break;
5458                                 CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Instruction initblk is not verifiable at 0x%04x", ctx.ip_offset));
5459                                 ip++;
5460                                 break;
5461                                 
5462                         case CEE_NO_:
5463                                 ip += 2;
5464                                 break;
5465                         case CEE_RETHROW:
5466                                 if (!is_correct_rethrow (ctx.header, ip_offset))
5467                                         ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("rethrow must be used inside a catch handler at 0x%04x", ctx.ip_offset));
5468                                 ctx.eval.size = 0;
5469                                 start = 1;
5470                                 ++ip;
5471                                 break;
5472
5473                         case CEE_SIZEOF:
5474                                 code_bounds_check (5);
5475                                 do_sizeof (&ctx, read32 (ip + 1));
5476                                 ip += 5;
5477                                 break;
5478
5479                         case CEE_REFANYTYPE:
5480                                 do_refanytype (&ctx);
5481                                 ++ip;
5482                                 break;
5483
5484                         default:
5485                                 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid instruction FE %x at 0x%04x", *ip, ctx.ip_offset));
5486                                 ++ip;
5487                         }
5488                         break;
5489
5490                 default:
5491                         ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid instruction %x at 0x%04x", *ip, ctx.ip_offset));
5492                         ++ip;
5493                 }
5494
5495                 /*TODO we can fast detect a forward branch or exception block targeting code after prefix, we should fail fast*/
5496                 if (prefix) {
5497                         if (!ctx.prefix_set) //first prefix
5498                                 ctx.code [ctx.ip_offset].flags |= IL_CODE_FLAG_SEEN;
5499                         ctx.prefix_set |= prefix;
5500                         ctx.has_flags = TRUE;
5501                         prefix = 0;
5502                 } else {
5503                         if (!ctx.has_flags)
5504                                 ctx.code [ctx.ip_offset].flags |= IL_CODE_FLAG_SEEN;
5505
5506                         if (ctx.prefix_set & PREFIX_CONSTRAINED)
5507                                 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid instruction after constrained prefix at 0x%04x", ctx.ip_offset));
5508                         if (ctx.prefix_set & PREFIX_READONLY)
5509                                 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid instruction after readonly prefix at 0x%04x", ctx.ip_offset));
5510                         if (ctx.prefix_set & PREFIX_VOLATILE)
5511                                 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid instruction after volatile prefix at 0x%04x", ctx.ip_offset));
5512                         if (ctx.prefix_set & PREFIX_UNALIGNED)
5513                                 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid instruction after unaligned prefix at 0x%04x", ctx.ip_offset));
5514                         ctx.prefix_set = prefix = 0;
5515                         ctx.has_flags = FALSE;
5516                 }
5517         }
5518         /*
5519          * if ip != end we overflowed: mark as error.
5520          */
5521         if ((ip != end || !start) && ctx.verifiable && !ctx.list) {
5522                 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Run ahead of method code at 0x%04x", ip_offset));
5523         }
5524
5525         /*We should guard against the last decoded opcode, otherwise we might add errors that doesn't make sense.*/
5526         for (i = 0; i < ctx.code_size && i < ip_offset; ++i) {
5527                 if (ctx.code [i].flags & IL_CODE_FLAG_WAS_TARGET) {
5528                         if (!(ctx.code [i].flags & IL_CODE_FLAG_SEEN))
5529                                 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Branch or exception block target middle of intruction at 0x%04x", i));
5530
5531                         if (ctx.code [i].flags & IL_CODE_DELEGATE_SEQUENCE)
5532                                 CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Branch to delegate code sequence at 0x%04x", i));
5533                 }
5534                 if ((ctx.code [i].flags & IL_CODE_LDFTN_DELEGATE_NONFINAL_VIRTUAL) && ctx.has_this_store)
5535                         CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Invalid ldftn with virtual function in method with stdarg 0 at  0x%04x", i));
5536
5537                 if ((ctx.code [i].flags & IL_CODE_CALL_NONFINAL_VIRTUAL) && ctx.has_this_store)
5538                         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));
5539         }
5540
5541         if (mono_method_is_constructor (ctx.method) && !ctx.super_ctor_called && !ctx.method->klass->valuetype && ctx.method->klass != mono_defaults.object_class) {
5542                 char *method_name = mono_method_full_name (ctx.method, TRUE);
5543                 char *type = mono_type_get_full_name (ctx.method->klass);
5544                 if (ctx.method->klass->parent && ctx.method->klass->parent->exception_type != MONO_EXCEPTION_NONE)
5545                         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));
5546                 else
5547                         CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Constructor %s for type %s not calling base type ctor.", method_name, type));
5548                 g_free (method_name);
5549                 g_free (type);
5550         }
5551
5552 cleanup:
5553         if (ctx.code) {
5554                 for (i = 0; i < ctx.header->code_size; ++i) {
5555                         if (ctx.code [i].stack)
5556                                 g_free (ctx.code [i].stack);
5557                 }
5558         }
5559
5560         for (tmp = ctx.funptrs; tmp; tmp = tmp->next)
5561                 g_free (tmp->data);
5562         g_slist_free (ctx.funptrs);
5563
5564         for (tmp = ctx.exception_types; tmp; tmp = tmp->next)
5565                 mono_metadata_free_type (tmp->data);
5566         g_slist_free (ctx.exception_types);
5567
5568         for (i = 0; i < ctx.num_locals; ++i) {
5569                 if (ctx.locals [i])
5570                         mono_metadata_free_type (ctx.locals [i]);
5571         }
5572         for (i = 0; i < ctx.max_args; ++i) {
5573                 if (ctx.params [i])
5574                         mono_metadata_free_type (ctx.params [i]);
5575         }
5576
5577         if (ctx.eval.stack)
5578                 g_free (ctx.eval.stack);
5579         if (ctx.code)
5580                 g_free (ctx.code);
5581         g_free (ctx.locals);
5582         g_free (ctx.params);
5583         mono_basic_block_free (original_bb);
5584         mono_metadata_free_mh (ctx.header);
5585
5586         finish_collect_stats ();
5587         return ctx.list;
5588 }
5589
5590 char*
5591 mono_verify_corlib ()
5592 {
5593         /* This is a public API function so cannot be removed */
5594         return NULL;
5595 }
5596
5597 /*
5598  * Returns true if @method needs to be verified.
5599  * 
5600  */
5601 gboolean
5602 mono_verifier_is_enabled_for_method (MonoMethod *method)
5603 {
5604         return mono_verifier_is_enabled_for_class (method->klass) && method->wrapper_type == MONO_WRAPPER_NONE;
5605 }
5606
5607 /*
5608  * Returns true if @klass need to be verified.
5609  * 
5610  */
5611 gboolean
5612 mono_verifier_is_enabled_for_class (MonoClass *klass)
5613 {
5614         return verify_all || (verifier_mode > MONO_VERIFIER_MODE_OFF && !(klass->image->assembly && klass->image->assembly->in_gac) && klass->image != mono_defaults.corlib);
5615 }
5616
5617 gboolean
5618 mono_verifier_is_enabled_for_image (MonoImage *image)
5619 {
5620         return verify_all || verifier_mode > MONO_VERIFIER_MODE_OFF;
5621 }
5622
5623 gboolean
5624 mono_verifier_is_method_full_trust (MonoMethod *method)
5625 {
5626         return mono_verifier_is_class_full_trust (method->klass);
5627 }
5628
5629 /*
5630  * Returns if @klass is under full trust or not.
5631  * 
5632  * TODO This code doesn't take CAS into account.
5633  * 
5634  * Under verify_all all user code must be verifiable if no security option was set 
5635  * 
5636  */
5637 gboolean
5638 mono_verifier_is_class_full_trust (MonoClass *klass)
5639 {
5640         /* under CoreCLR code is trusted if it is part of the "platform" otherwise all code inside the GAC is trusted */
5641         gboolean trusted_location = (mono_security_get_mode () != MONO_SECURITY_MODE_CORE_CLR) ? 
5642                 (klass->image->assembly && klass->image->assembly->in_gac) : mono_security_core_clr_is_platform_image (klass->image);
5643
5644         if (verify_all && verifier_mode == MONO_VERIFIER_MODE_OFF)
5645                 return trusted_location || klass->image == mono_defaults.corlib;
5646         return verifier_mode < MONO_VERIFIER_MODE_VERIFIABLE || trusted_location || klass->image == mono_defaults.corlib;
5647 }
5648
5649 GSList*
5650 mono_method_verify_with_current_settings (MonoMethod *method, gboolean skip_visibility)
5651 {
5652         return mono_method_verify (method, 
5653                         (verifier_mode != MONO_VERIFIER_MODE_STRICT ? MONO_VERIFY_NON_STRICT: 0)
5654                         | (!mono_verifier_is_method_full_trust (method) ? MONO_VERIFY_FAIL_FAST : 0)
5655                         | (skip_visibility ? MONO_VERIFY_SKIP_VISIBILITY : 0));
5656 }
5657
5658 static int
5659 get_field_end (MonoClassField *field)
5660 {
5661         int align;
5662         int size = mono_type_size (field->type, &align);
5663         if (size == 0)
5664                 size = 4; /*FIXME Is this a safe bet?*/
5665         return size + field->offset;
5666 }
5667
5668 static gboolean
5669 verify_class_for_overlapping_reference_fields (MonoClass *class)
5670 {
5671         int i = 0, j;
5672         gpointer iter = NULL;
5673         MonoClassField *field;
5674         gboolean is_fulltrust = mono_verifier_is_class_full_trust (class);
5675         /*We can't skip types with !has_references since this is calculated after we have run.*/
5676         if (!((class->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_EXPLICIT_LAYOUT))
5677                 return TRUE;
5678
5679
5680         /*We must check for stuff overlapping reference fields.
5681           The outer loop uses mono_class_get_fields to ensure that MonoClass:fields get inited.
5682         */
5683         while ((field = mono_class_get_fields (class, &iter))) {
5684                 int fieldEnd = get_field_end (field);
5685                 gboolean is_valuetype = !MONO_TYPE_IS_REFERENCE (field->type);
5686                 ++i;
5687
5688                 if (mono_field_is_deleted (field) || (field->type->attrs & FIELD_ATTRIBUTE_STATIC))
5689                         continue;
5690
5691                 for (j = i; j < class->field.count; ++j) {
5692                         MonoClassField *other = &class->fields [j];
5693                         int otherEnd = get_field_end (other);
5694                         if (mono_field_is_deleted (other) || (is_valuetype && !MONO_TYPE_IS_REFERENCE (other->type)) || (other->type->attrs & FIELD_ATTRIBUTE_STATIC))
5695                                 continue;
5696
5697                         if (!is_valuetype && MONO_TYPE_IS_REFERENCE (other->type) && field->offset == other->offset && is_fulltrust)
5698                                 continue;
5699
5700                         if ((otherEnd > field->offset && otherEnd <= fieldEnd) || (other->offset >= field->offset && other->offset < fieldEnd))
5701                                 return FALSE;
5702                 }
5703         }
5704         return TRUE;
5705 }
5706
5707 static guint
5708 field_hash (gconstpointer key)
5709 {
5710         const MonoClassField *field = key;
5711         return g_str_hash (field->name) ^ mono_metadata_type_hash (field->type); /**/
5712 }
5713
5714 static gboolean
5715 field_equals (gconstpointer _a, gconstpointer _b)
5716 {
5717         const MonoClassField *a = _a;
5718         const MonoClassField *b = _b;
5719         return !strcmp (a->name, b->name) && mono_metadata_type_equal (a->type, b->type);
5720 }
5721
5722
5723 static gboolean
5724 verify_class_fields (MonoClass *class)
5725 {
5726         gpointer iter = NULL;
5727         MonoClassField *field;
5728         MonoGenericContext *context = mono_class_get_context (class);
5729         GHashTable *unique_fields = g_hash_table_new_full (&field_hash, &field_equals, NULL, NULL);
5730         if (class->generic_container)
5731                 context = &class->generic_container->context;
5732
5733         while ((field = mono_class_get_fields (class, &iter)) != NULL) {
5734                 if (!mono_type_is_valid_type_in_context (field->type, context)) {
5735                         g_hash_table_destroy (unique_fields);
5736                         return FALSE;
5737                 }
5738                 if (g_hash_table_lookup (unique_fields, field)) {
5739                         g_hash_table_destroy (unique_fields);
5740                         return FALSE;
5741                 }
5742                 g_hash_table_insert (unique_fields, field, field);
5743         }
5744         g_hash_table_destroy (unique_fields);
5745         return TRUE;
5746 }
5747
5748 static gboolean
5749 verify_interfaces (MonoClass *class)
5750 {
5751         int i;
5752         for (i = 0; i < class->interface_count; ++i) {
5753                 MonoClass *iface = class->interfaces [i];
5754                 if (!(iface->flags & TYPE_ATTRIBUTE_INTERFACE))
5755                         return FALSE;
5756         }
5757         return TRUE;
5758 }
5759
5760 static gboolean
5761 verify_valuetype_layout_with_target (MonoClass *class, MonoClass *target_class)
5762 {
5763         int type;
5764         gpointer iter = NULL;
5765         MonoClassField *field;
5766         MonoClass *field_class;
5767
5768         if (!class->valuetype)
5769                 return TRUE;
5770
5771         type = class->byval_arg.type;
5772         /*primitive type fields are not properly decoded*/
5773         if ((type >= MONO_TYPE_BOOLEAN && type <= MONO_TYPE_R8) || (type >= MONO_TYPE_I && type <= MONO_TYPE_U))
5774                 return TRUE;
5775
5776         while ((field = mono_class_get_fields (class, &iter)) != NULL) {
5777                 if (!field->type)
5778                         return FALSE;
5779
5780                 if (field->type->attrs & (FIELD_ATTRIBUTE_STATIC | FIELD_ATTRIBUTE_HAS_FIELD_RVA))
5781                         continue;
5782
5783                 field_class = mono_class_get_generic_type_definition (mono_class_from_mono_type (field->type));
5784
5785                 if (field_class == target_class || class == field_class || !verify_valuetype_layout_with_target (field_class, target_class))
5786                         return FALSE;
5787         }
5788
5789         return TRUE;
5790 }
5791
5792 static gboolean
5793 verify_valuetype_layout (MonoClass *class)
5794 {
5795         gboolean res;
5796         res = verify_valuetype_layout_with_target (class, class);
5797         return res;
5798 }
5799
5800 static gboolean
5801 recursive_mark_constraint_args (MonoBitSet *used_args, MonoGenericContainer *gc, MonoType *type)
5802 {
5803         int idx;
5804         MonoClass **constraints;
5805         MonoGenericParamInfo *param_info;
5806
5807         g_assert (mono_type_is_generic_argument (type));
5808
5809         idx = mono_type_get_generic_param_num (type);
5810         if (mono_bitset_test_fast (used_args, idx))
5811                 return FALSE;
5812
5813         mono_bitset_set_fast (used_args, idx);
5814         param_info = mono_generic_container_get_param_info (gc, idx);
5815
5816         if (!param_info->constraints)
5817                 return TRUE;
5818
5819         for (constraints = param_info->constraints; *constraints; ++constraints) {
5820                 MonoClass *ctr = *constraints;
5821                 MonoType *constraint_type = &ctr->byval_arg;
5822
5823                 if (mono_type_is_generic_argument (constraint_type) && !recursive_mark_constraint_args (used_args, gc, constraint_type))
5824                         return FALSE;
5825         }
5826         return TRUE;
5827 }
5828
5829 static gboolean
5830 verify_generic_parameters (MonoClass *class)
5831 {
5832         int i;
5833         MonoGenericContainer *gc = class->generic_container;
5834         MonoBitSet *used_args = mono_bitset_new (gc->type_argc, 0);
5835
5836         for (i = 0; i < gc->type_argc; ++i) {
5837                 MonoGenericParamInfo *param_info = mono_generic_container_get_param_info (gc, i);
5838                 MonoClass **constraints;
5839
5840                 if (!param_info->constraints)
5841                         continue;
5842
5843                 mono_bitset_clear_all (used_args);
5844                 mono_bitset_set_fast (used_args, i);
5845
5846                 for (constraints = param_info->constraints; *constraints; ++constraints) {
5847                         MonoClass *ctr = *constraints;
5848                         MonoType *constraint_type = &ctr->byval_arg;
5849
5850                         if (!mono_type_is_valid_type_in_context (constraint_type, &gc->context))
5851                                 goto fail;
5852
5853                         if (mono_type_is_generic_argument (constraint_type) && !recursive_mark_constraint_args (used_args, gc, constraint_type))
5854                                 goto fail;
5855                 }
5856         }
5857         mono_bitset_free (used_args);
5858         return TRUE;
5859
5860 fail:
5861         mono_bitset_free (used_args);
5862         return FALSE;
5863 }
5864
5865 /*
5866  * Check if the class is verifiable.
5867  * 
5868  * Right now there are no conditions that make a class a valid but not verifiable. Both overlapping reference
5869  * field and invalid generic instantiation are fatal errors.
5870  * 
5871  * This method must be safe to be called from mono_class_init and all code must be carefull about that.
5872  * 
5873  */
5874 gboolean
5875 mono_verifier_verify_class (MonoClass *class)
5876 {
5877         /*Neither <Module>, object or ifaces have parent.*/
5878         if (!class->parent &&
5879                 class != mono_defaults.object_class && 
5880                 !MONO_CLASS_IS_INTERFACE (class) &&
5881                 (!class->image->dynamic && class->type_token != 0x2000001)) /*<Module> is the first type in the assembly*/
5882                 return FALSE;
5883         if (class->parent && MONO_CLASS_IS_INTERFACE (class->parent))
5884                 return FALSE;
5885         if (class->generic_container && (class->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_EXPLICIT_LAYOUT)
5886                 return FALSE;
5887         if (class->generic_container && !verify_generic_parameters (class))
5888                 return FALSE;
5889         if (!verify_class_for_overlapping_reference_fields (class))
5890                 return FALSE;
5891         if (class->generic_class && !mono_class_is_valid_generic_instantiation (NULL, class))
5892                 return FALSE;
5893         if (class->generic_class == NULL && !verify_class_fields (class))
5894                 return FALSE;
5895         if (class->valuetype && !verify_valuetype_layout (class))
5896                 return FALSE;
5897         if (!verify_interfaces (class))
5898                 return FALSE;
5899         return TRUE;
5900 }
5901 #else
5902
5903 gboolean
5904 mono_verifier_verify_class (MonoClass *class)
5905 {
5906         /* The verifier was disabled at compile time */
5907         return TRUE;
5908 }
5909
5910 GSList*
5911 mono_method_verify_with_current_settings (MonoMethod *method, gboolean skip_visibility)
5912 {
5913         /* The verifier was disabled at compile time */
5914         return NULL;
5915 }
5916
5917 gboolean
5918 mono_verifier_is_class_full_trust (MonoClass *klass)
5919 {
5920         /* The verifier was disabled at compile time */
5921         return TRUE;
5922 }
5923
5924 gboolean
5925 mono_verifier_is_method_full_trust (MonoMethod *method)
5926 {
5927         /* The verifier was disabled at compile time */
5928         return TRUE;
5929 }
5930
5931 gboolean
5932 mono_verifier_is_enabled_for_image (MonoImage *image)
5933 {
5934         /* The verifier was disabled at compile time */
5935         return FALSE;
5936 }
5937
5938 gboolean
5939 mono_verifier_is_enabled_for_class (MonoClass *klass)
5940 {
5941         /* The verifier was disabled at compile time */
5942         return FALSE;
5943 }
5944
5945 gboolean
5946 mono_verifier_is_enabled_for_method (MonoMethod *method)
5947 {
5948         /* The verifier was disabled at compile time */
5949         return FALSE;
5950 }
5951
5952 GSList*
5953 mono_method_verify (MonoMethod *method, int level)
5954 {
5955         /* The verifier was disabled at compile time */
5956         return NULL;
5957 }
5958
5959 void
5960 mono_free_verify_list (GSList *list)
5961 {
5962         /* The verifier was disabled at compile time */
5963         /* will always be null if verifier is disabled */
5964 }
5965
5966 #endif