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