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