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