New tests.
[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_I8:
1798         case MONO_TYPE_U8:
1799                 return TYPE_I8 | mask;
1800
1801         case MONO_TYPE_R4:
1802         case MONO_TYPE_R8:
1803                 return TYPE_R8 | mask;
1804
1805         case MONO_TYPE_GENERICINST:
1806         case MONO_TYPE_VALUETYPE:
1807                 if (mono_type_is_enum_type (type)) {
1808                         type = mono_type_get_underlying_type_any (type);
1809                         if (!type)
1810                                 return FALSE;
1811                         type_kind = type->type;
1812                         goto handle_enum;
1813                 } else {
1814                         return TYPE_COMPLEX | mask;
1815                 }
1816
1817         default:
1818                 return TYPE_INV;
1819         }
1820 }
1821
1822 /* convert MonoType to ILStackDesc format (stype) */
1823 static gboolean
1824 set_stack_value (VerifyContext *ctx, ILStackDesc *stack, MonoType *type, int take_addr)
1825 {
1826         int mask = 0;
1827         int type_kind = type->type;
1828
1829         if (type->byref || take_addr)
1830                 mask = POINTER_MASK;
1831         /* TODO handle CMMP_MASK */
1832
1833 handle_enum:
1834         stack->type = type;
1835
1836         switch (type_kind) {
1837         case MONO_TYPE_I1:
1838         case MONO_TYPE_U1:
1839         case MONO_TYPE_BOOLEAN:
1840         case MONO_TYPE_I2:
1841         case MONO_TYPE_U2:
1842         case MONO_TYPE_CHAR:
1843         case MONO_TYPE_I4:
1844         case MONO_TYPE_U4:
1845                 stack->stype = TYPE_I4 | mask;
1846                 break;
1847         case MONO_TYPE_I:
1848         case MONO_TYPE_U:
1849                 stack->stype = TYPE_NATIVE_INT | mask;
1850                 break;
1851
1852         /*FIXME: Do we need to check if it's a pointer to the method pointer? The spec says it' illegal to have that.*/
1853         case MONO_TYPE_FNPTR:
1854         case MONO_TYPE_PTR:
1855         case MONO_TYPE_TYPEDBYREF:
1856                 stack->stype = TYPE_PTR | mask;
1857                 break;
1858
1859         case MONO_TYPE_CLASS:
1860         case MONO_TYPE_STRING:
1861         case MONO_TYPE_OBJECT:
1862         case MONO_TYPE_SZARRAY:
1863         case MONO_TYPE_ARRAY:
1864
1865         case MONO_TYPE_VAR:
1866         case MONO_TYPE_MVAR: 
1867                 stack->stype = TYPE_COMPLEX | mask;
1868                 break;
1869                 
1870         case MONO_TYPE_I8:
1871         case MONO_TYPE_U8:
1872                 stack->stype = TYPE_I8 | mask;
1873                 break;
1874         case MONO_TYPE_R4:
1875         case MONO_TYPE_R8:
1876                 stack->stype = TYPE_R8 | mask;
1877                 break;
1878         case MONO_TYPE_GENERICINST:
1879         case MONO_TYPE_VALUETYPE:
1880                 if (mono_type_is_enum_type (type)) {
1881                         MonoType *utype = mono_type_get_underlying_type_any (type);
1882                         if (!utype) {
1883                                 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Could not resolve underlying type of %x at %d", type->type, ctx->ip_offset));
1884                                 return FALSE;
1885                         }
1886                         type = utype;
1887                         type_kind = type->type;
1888                         goto handle_enum;
1889                 } else {
1890                         stack->stype = TYPE_COMPLEX | mask;
1891                         break;
1892                 }
1893         default:
1894                 VERIFIER_DEBUG ( printf ("unknown type 0x%02x in eval stack type\n", type->type); );
1895                 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Illegal value set on stack 0x%02x at %d", type->type, ctx->ip_offset));
1896                 return FALSE;
1897         }
1898         return TRUE;
1899 }
1900
1901 /* 
1902  * init_stack_with_value_at_exception_boundary:
1903  * 
1904  * Initialize the stack and push a given type.
1905  * The instruction is marked as been on the exception boundary.
1906  */
1907 static void
1908 init_stack_with_value_at_exception_boundary (VerifyContext *ctx, ILCodeDesc *code, MonoClass *klass)
1909 {
1910         MonoError error;
1911         MonoType *type = mono_class_inflate_generic_type_checked (&klass->byval_arg, ctx->generic_context, &error);
1912
1913         if (!mono_error_ok (&error)) {
1914                 char *name = mono_type_get_full_name (klass);
1915                 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid class %s used for exception", name));
1916                 g_free (name);
1917                 mono_error_cleanup (&error);
1918                 return;
1919         }
1920
1921         if (!ctx->max_stack) {
1922                 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Stack overflow at 0x%04x", ctx->ip_offset));
1923                 return;
1924         }
1925
1926         stack_init (ctx, code);
1927         ensure_stack_size (code, 1);
1928         set_stack_value (ctx, code->stack, type, FALSE);
1929         ctx->exception_types = g_slist_prepend (ctx->exception_types, type);
1930         code->size = 1;
1931         code->flags |= IL_CODE_FLAG_WAS_TARGET;
1932         if (mono_type_is_generic_argument (type))
1933                 code->stack->stype |= BOXED_MASK;
1934 }
1935
1936 /*Verify if type 'candidate' can be stored in type 'target'.
1937  * 
1938  * If strict, check for the underlying type and not the verification stack types
1939  */
1940 static gboolean
1941 verify_type_compatibility_full (VerifyContext *ctx, MonoType *target, MonoType *candidate, gboolean strict)
1942 {
1943 #define IS_ONE_OF3(T, A, B, C) (T == A || T == B || T == C)
1944 #define IS_ONE_OF2(T, A, B) (T == A || T == B)
1945
1946         MonoType *original_candidate = candidate;
1947         VERIFIER_DEBUG ( printf ("checking type compatibility %s x %s strict %d\n", mono_type_full_name (target), mono_type_full_name (candidate), strict); );
1948
1949         /*only one is byref */
1950         if (candidate->byref ^ target->byref) {
1951                 /* converting from native int to byref*/
1952                 if (get_stack_type (candidate) == TYPE_NATIVE_INT && target->byref) {
1953                         CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("using byref native int at 0x%04x", ctx->ip_offset));
1954                         return TRUE;
1955                 }
1956                 return FALSE;
1957         }
1958         strict |= target->byref;
1959         /*From now on we don't care about byref anymore, so it's ok to discard it here*/
1960         candidate = mono_type_get_underlying_type_any (candidate);
1961
1962 handle_enum:
1963         switch (target->type) {
1964         case MONO_TYPE_VOID:
1965                 return candidate->type == MONO_TYPE_VOID;
1966         case MONO_TYPE_I1:
1967         case MONO_TYPE_U1:
1968         case MONO_TYPE_BOOLEAN:
1969                 if (strict)
1970                         return IS_ONE_OF3 (candidate->type, MONO_TYPE_I1, MONO_TYPE_U1, MONO_TYPE_BOOLEAN);
1971         case MONO_TYPE_I2:
1972         case MONO_TYPE_U2:
1973         case MONO_TYPE_CHAR:
1974                 if (strict)
1975                         return IS_ONE_OF3 (candidate->type, MONO_TYPE_I2, MONO_TYPE_U2, MONO_TYPE_CHAR);
1976         case MONO_TYPE_I4:
1977         case MONO_TYPE_U4: {
1978                 gboolean is_native_int = IS_ONE_OF2 (candidate->type, MONO_TYPE_I, MONO_TYPE_U);
1979                 gboolean is_int4 = IS_ONE_OF2 (candidate->type, MONO_TYPE_I4, MONO_TYPE_U4);
1980                 if (strict)
1981                         return is_native_int || is_int4;
1982                 return is_native_int || get_stack_type (candidate) == TYPE_I4;
1983         }
1984
1985         case MONO_TYPE_I8:
1986         case MONO_TYPE_U8:
1987                 return IS_ONE_OF2 (candidate->type, MONO_TYPE_I8, MONO_TYPE_U8);
1988
1989         case MONO_TYPE_R4:
1990         case MONO_TYPE_R8:
1991                 if (strict)
1992                         return candidate->type == target->type;
1993                 return IS_ONE_OF2 (candidate->type, MONO_TYPE_R4, MONO_TYPE_R8);
1994
1995         case MONO_TYPE_I:
1996         case MONO_TYPE_U: {
1997                 gboolean is_native_int = IS_ONE_OF2 (candidate->type, MONO_TYPE_I, MONO_TYPE_U);
1998                 gboolean is_int4 = IS_ONE_OF2 (candidate->type, MONO_TYPE_I4, MONO_TYPE_U4);
1999                 if (strict)
2000                         return is_native_int || is_int4;
2001                 return is_native_int || get_stack_type (candidate) == TYPE_I4;
2002         }
2003
2004         case MONO_TYPE_PTR:
2005                 if (candidate->type != MONO_TYPE_PTR)
2006                         return FALSE;
2007                 /* check the underlying type */
2008                 return verify_type_compatibility_full (ctx, target->data.type, candidate->data.type, TRUE);
2009
2010         case MONO_TYPE_FNPTR: {
2011                 MonoMethodSignature *left, *right;
2012                 if (candidate->type != MONO_TYPE_FNPTR)
2013                         return FALSE;
2014
2015                 left = mono_type_get_signature (target);
2016                 right = mono_type_get_signature (candidate);
2017                 return mono_metadata_signature_equal (left, right) && left->call_convention == right->call_convention;
2018         }
2019
2020         case MONO_TYPE_GENERICINST: {
2021                 MonoClass *target_klass;
2022                 MonoClass *candidate_klass;
2023                 if (mono_type_is_enum_type (target)) {
2024                         target = mono_type_get_underlying_type_any (target);
2025                         if (!target)
2026                                 return FALSE;
2027                         goto handle_enum;
2028                 }
2029                 /*
2030                  * VAR / MVAR compatibility must be checked by verify_stack_type_compatibility
2031                  * to take boxing status into account.
2032                  */
2033                 if (mono_type_is_generic_argument (original_candidate))
2034                         return FALSE;
2035
2036                 target_klass = mono_class_from_mono_type (target);
2037                 candidate_klass = mono_class_from_mono_type (candidate);
2038                 if (mono_class_is_nullable (target_klass)) {
2039                         if (!mono_class_is_nullable (candidate_klass))
2040                                 return FALSE;
2041                         return target_klass == candidate_klass;
2042                 }
2043                 
2044                 return mono_class_is_assignable_from (target_klass, candidate_klass);
2045         }
2046
2047         case MONO_TYPE_STRING:
2048                 return candidate->type == MONO_TYPE_STRING;
2049
2050         case MONO_TYPE_CLASS:
2051                 /*
2052                  * VAR / MVAR compatibility must be checked by verify_stack_type_compatibility
2053                  * to take boxing status into account.
2054                  */
2055                 if (mono_type_is_generic_argument (original_candidate))
2056                         return FALSE;
2057
2058                 if (candidate->type == MONO_TYPE_VALUETYPE)
2059                         return FALSE;
2060
2061                 /* If candidate is an enum it should return true for System.Enum and supertypes.
2062                  * That's why here we use the original type and not the underlying type.
2063                  */ 
2064                 return mono_class_is_assignable_from (target->data.klass, mono_class_from_mono_type (original_candidate));
2065
2066         case MONO_TYPE_OBJECT:
2067                 return MONO_TYPE_IS_REFERENCE (candidate);
2068
2069         case MONO_TYPE_SZARRAY: {
2070                 MonoClass *left;
2071                 MonoClass *right;
2072                 if (candidate->type != MONO_TYPE_SZARRAY)
2073                         return FALSE;
2074
2075                 left = mono_class_from_mono_type (target);
2076                 right = mono_class_from_mono_type (candidate);
2077
2078                 return mono_class_is_assignable_from (left, right);
2079         }
2080
2081         case MONO_TYPE_ARRAY:
2082                 if (candidate->type != MONO_TYPE_ARRAY)
2083                         return FALSE;
2084                 return is_array_type_compatible (target, candidate);
2085
2086         case MONO_TYPE_TYPEDBYREF:
2087                 return candidate->type == MONO_TYPE_TYPEDBYREF;
2088
2089         case MONO_TYPE_VALUETYPE: {
2090                 MonoClass *target_klass;
2091                 MonoClass *candidate_klass;
2092
2093                 if (candidate->type == MONO_TYPE_CLASS)
2094                         return FALSE;
2095
2096                 target_klass = mono_class_from_mono_type (target);
2097                 candidate_klass = mono_class_from_mono_type (candidate);
2098                 if (target_klass == candidate_klass)
2099                         return TRUE;
2100                 if (mono_type_is_enum_type (target)) {
2101                         target = mono_type_get_underlying_type_any (target);
2102                         if (!target)
2103                                 return FALSE;
2104                         goto handle_enum;
2105                 }
2106                 return FALSE;
2107         }
2108
2109         case MONO_TYPE_VAR:
2110                 if (candidate->type != MONO_TYPE_VAR)
2111                         return FALSE;
2112                 return mono_type_get_generic_param_num (candidate) == mono_type_get_generic_param_num (target);
2113
2114         case MONO_TYPE_MVAR:
2115                 if (candidate->type != MONO_TYPE_MVAR)
2116                         return FALSE;
2117                 return mono_type_get_generic_param_num (candidate) == mono_type_get_generic_param_num (target);
2118
2119         default:
2120                 VERIFIER_DEBUG ( printf ("unknown store type %d\n", target->type); );
2121                 g_assert_not_reached ();
2122                 return FALSE;
2123         }
2124         return 1;
2125 #undef IS_ONE_OF3
2126 #undef IS_ONE_OF2
2127 }
2128
2129 static gboolean
2130 verify_type_compatibility (VerifyContext *ctx, MonoType *target, MonoType *candidate)
2131 {
2132         return verify_type_compatibility_full (ctx, target, candidate, FALSE);
2133 }
2134
2135 /*
2136  * Returns the generic param bound to the context been verified.
2137  * 
2138  */
2139 static MonoGenericParam*
2140 get_generic_param (VerifyContext *ctx, MonoType *param) 
2141 {
2142         guint16 param_num = mono_type_get_generic_param_num (param);
2143         if (param->type == MONO_TYPE_VAR) {
2144                 if (!ctx->generic_context->class_inst || ctx->generic_context->class_inst->type_argc <= param_num) {
2145                         ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid generic type argument %d", param_num));
2146                         return NULL;
2147                 }
2148                 return ctx->generic_context->class_inst->type_argv [param_num]->data.generic_param;
2149         }
2150         
2151         /*param must be a MVAR */
2152         if (!ctx->generic_context->method_inst || ctx->generic_context->method_inst->type_argc <= param_num) {
2153                 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid generic method argument %d", param_num));
2154                 return NULL;
2155         }
2156         return ctx->generic_context->method_inst->type_argv [param_num]->data.generic_param;
2157         
2158 }
2159 /*
2160  * is_compatible_boxed_valuetype:
2161  * 
2162  * Returns TRUE if @candidate / @stack is a valid boxed valuetype. 
2163  * 
2164  * @type The source type. It it tested to be of the proper type.    
2165  * @candidate type of the boxed valuetype.
2166  * @stack stack slot of the boxed valuetype, separate from @candidade since one could be changed before calling this function
2167  * @strict if TRUE candidate must be boxed compatible to the target type
2168  * 
2169  */
2170 static gboolean
2171 is_compatible_boxed_valuetype (VerifyContext *ctx, MonoType *type, MonoType *candidate, ILStackDesc *stack, gboolean strict)
2172 {
2173         if (!stack_slot_is_boxed_value (stack))
2174                 return FALSE;
2175         if (type->byref || candidate->byref)
2176                 return FALSE;
2177
2178         if (mono_type_is_generic_argument (candidate)) {
2179                 MonoGenericParam *param = get_generic_param (ctx, candidate);
2180                 MonoClass **class;
2181                 for (class = mono_generic_param_info (param)->constraints; class && *class; ++class) {
2182                         if (verify_type_compatibility_full (ctx, type, mono_type_get_type_byval (& (*class)->byval_arg), FALSE))
2183                                 return TRUE;
2184                 }
2185         }
2186
2187         if (mono_type_is_generic_argument (type))
2188                 return FALSE;
2189
2190         if (!strict)
2191                 return TRUE;
2192
2193         return MONO_TYPE_IS_REFERENCE (type) && mono_class_is_assignable_from (mono_class_from_mono_type (type), mono_class_from_mono_type (candidate));
2194 }
2195
2196 static int
2197 verify_stack_type_compatibility_full (VerifyContext *ctx, MonoType *type, ILStackDesc *stack, gboolean drop_byref, gboolean valuetype_must_be_boxed)
2198 {
2199         MonoType *candidate = mono_type_from_stack_slot (stack);
2200         if (MONO_TYPE_IS_REFERENCE (type) && !type->byref && stack_slot_is_null_literal (stack))
2201                 return TRUE;
2202
2203         if (is_compatible_boxed_valuetype (ctx, type, candidate, stack, TRUE))
2204                 return TRUE;
2205
2206         if (valuetype_must_be_boxed && !stack_slot_is_boxed_value (stack) && !MONO_TYPE_IS_REFERENCE (candidate))
2207                 return FALSE;
2208
2209         if (!valuetype_must_be_boxed && stack_slot_is_boxed_value (stack))
2210                 return FALSE;
2211
2212         if (drop_byref)
2213                 return verify_type_compatibility_full (ctx, type, mono_type_get_type_byval (candidate), FALSE);
2214
2215         return verify_type_compatibility_full (ctx, type, candidate, FALSE);
2216 }
2217
2218 static int
2219 verify_stack_type_compatibility (VerifyContext *ctx, MonoType *type, ILStackDesc *stack)
2220 {
2221         return verify_stack_type_compatibility_full (ctx, type, stack, FALSE, FALSE);
2222 }
2223
2224 static gboolean
2225 mono_delegate_type_equal (MonoType *target, MonoType *candidate)
2226 {
2227         if (candidate->byref ^ target->byref)
2228                 return FALSE;
2229
2230         switch (target->type) {
2231         case MONO_TYPE_VOID:
2232         case MONO_TYPE_I1:
2233         case MONO_TYPE_U1:
2234         case MONO_TYPE_BOOLEAN:
2235         case MONO_TYPE_I2:
2236         case MONO_TYPE_U2:
2237         case MONO_TYPE_CHAR:
2238         case MONO_TYPE_I4:
2239         case MONO_TYPE_U4:
2240         case MONO_TYPE_I8:
2241         case MONO_TYPE_U8:
2242         case MONO_TYPE_R4:
2243         case MONO_TYPE_R8:
2244         case MONO_TYPE_I:
2245         case MONO_TYPE_U:
2246         case MONO_TYPE_STRING:
2247         case MONO_TYPE_TYPEDBYREF:
2248                 return candidate->type == target->type;
2249
2250         case MONO_TYPE_PTR:
2251                 return mono_delegate_type_equal (target->data.type, candidate->data.type);
2252
2253         case MONO_TYPE_FNPTR:
2254                 if (candidate->type != MONO_TYPE_FNPTR)
2255                         return FALSE;
2256                 return mono_delegate_signature_equal (mono_type_get_signature (target), mono_type_get_signature (candidate), FALSE);
2257
2258         case MONO_TYPE_GENERICINST: {
2259                 MonoClass *target_klass;
2260                 MonoClass *candidate_klass;
2261                 target_klass = mono_class_from_mono_type (target);
2262                 candidate_klass = mono_class_from_mono_type (candidate);
2263                 /*FIXME handle nullables and enum*/
2264                 return mono_class_is_assignable_from (target_klass, candidate_klass);
2265         }
2266         case MONO_TYPE_OBJECT:
2267                 return MONO_TYPE_IS_REFERENCE (candidate);
2268
2269         case MONO_TYPE_CLASS:
2270                 return mono_class_is_assignable_from(target->data.klass, mono_class_from_mono_type (candidate));
2271
2272         case MONO_TYPE_SZARRAY:
2273                 if (candidate->type != MONO_TYPE_SZARRAY)
2274                         return FALSE;
2275                 return mono_class_is_assignable_from (mono_class_from_mono_type (target)->element_class, mono_class_from_mono_type (candidate)->element_class);
2276
2277         case MONO_TYPE_ARRAY:
2278                 if (candidate->type != MONO_TYPE_ARRAY)
2279                         return FALSE;
2280                 return is_array_type_compatible (target, candidate);
2281
2282         case MONO_TYPE_VALUETYPE:
2283                 /*FIXME handle nullables and enum*/
2284                 return mono_class_from_mono_type (candidate) == mono_class_from_mono_type (target);
2285
2286         case MONO_TYPE_VAR:
2287                 return candidate->type == MONO_TYPE_VAR && mono_type_get_generic_param_num (target) == mono_type_get_generic_param_num (candidate);
2288                 return FALSE;
2289
2290         case MONO_TYPE_MVAR:
2291                 return candidate->type == MONO_TYPE_MVAR && mono_type_get_generic_param_num (target) == mono_type_get_generic_param_num (candidate);
2292                 return FALSE;
2293
2294         default:
2295                 VERIFIER_DEBUG ( printf ("Unknown type %d. Implement me!\n", target->type); );
2296                 g_assert_not_reached ();
2297                 return FALSE;
2298         }
2299 }
2300
2301 static gboolean
2302 mono_delegate_param_equal (MonoType *delegate, MonoType *method)
2303 {
2304         if (mono_metadata_type_equal_full (delegate, method, TRUE))
2305                 return TRUE;
2306
2307         return mono_delegate_type_equal (method, delegate);
2308 }
2309
2310 static gboolean
2311 mono_delegate_ret_equal (MonoType *delegate, MonoType *method)
2312 {
2313         if (mono_metadata_type_equal_full (delegate, method, TRUE))
2314                 return TRUE;
2315
2316         return mono_delegate_type_equal (delegate, method);
2317 }
2318
2319 /*
2320  * mono_delegate_signature_equal:
2321  * 
2322  * Compare two signatures in the way expected by delegates.
2323  * 
2324  * This function only exists due to the fact that it should ignore the 'has_this' part of the signature.
2325  *
2326  * FIXME can this function be eliminated and proper metadata functionality be used?
2327  */
2328 static gboolean
2329 mono_delegate_signature_equal (MonoMethodSignature *delegate_sig, MonoMethodSignature *method_sig, gboolean is_static_ldftn)
2330 {
2331         int i;
2332         int method_offset = is_static_ldftn ? 1 : 0;
2333
2334         if (delegate_sig->param_count + method_offset != method_sig->param_count) 
2335                 return FALSE;
2336
2337         if (delegate_sig->call_convention != method_sig->call_convention)
2338                 return FALSE;
2339
2340         for (i = 0; i < delegate_sig->param_count; i++) { 
2341                 MonoType *p1 = delegate_sig->params [i];
2342                 MonoType *p2 = method_sig->params [i + method_offset];
2343
2344                 if (!mono_delegate_param_equal (p1, p2))
2345                         return FALSE;
2346         }
2347
2348         if (!mono_delegate_ret_equal (delegate_sig->ret, method_sig->ret))
2349                 return FALSE;
2350
2351         return TRUE;
2352 }
2353
2354 /* 
2355  * verify_ldftn_delegate:
2356  * 
2357  * Verify properties of ldftn based delegates.
2358  */
2359 static void
2360 verify_ldftn_delegate (VerifyContext *ctx, MonoClass *delegate, ILStackDesc *value, ILStackDesc *funptr)
2361 {
2362         MonoMethod *method = funptr->method;
2363
2364         /*ldftn non-final virtuals only allowed if method is not static,
2365          * the object is a this arg (comes from a ldarg.0), and there is no starg.0.
2366          * This rules doesn't apply if the object on stack is a boxed valuetype.
2367          */
2368         if ((method->flags & METHOD_ATTRIBUTE_VIRTUAL) && !(method->flags & METHOD_ATTRIBUTE_FINAL) && !(method->klass->flags & TYPE_ATTRIBUTE_SEALED) && !stack_slot_is_boxed_value (value)) {
2369                 /*A stdarg 0 must not happen, we fail here only in fail fast mode to avoid double error reports*/
2370                 if (IS_FAIL_FAST_MODE (ctx) && ctx->has_this_store)
2371                         CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid ldftn with virtual function in method with stdarg 0 at  0x%04x", ctx->ip_offset));
2372
2373                 /*current method must not be static*/
2374                 if (ctx->method->flags & METHOD_ATTRIBUTE_STATIC)
2375                         CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid ldftn with virtual function at 0x%04x", ctx->ip_offset));
2376
2377                 /*value is the this pointer, loaded using ldarg.0 */
2378                 if (!stack_slot_is_this_pointer (value))
2379                         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));
2380
2381                 ctx->code [ctx->ip_offset].flags |= IL_CODE_LDFTN_DELEGATE_NONFINAL_VIRTUAL;
2382         }
2383 }
2384
2385 /*
2386  * verify_delegate_compatibility:
2387  * 
2388  * Verify delegate creation sequence.
2389  * 
2390  */
2391 static void
2392 verify_delegate_compatibility (VerifyContext *ctx, MonoClass *delegate, ILStackDesc *value, ILStackDesc *funptr)
2393 {
2394 #define IS_VALID_OPCODE(offset, opcode) (ip [ip_offset - offset] == opcode && (ctx->code [ip_offset - offset].flags & IL_CODE_FLAG_SEEN))
2395 #define IS_LOAD_FUN_PTR(kind) (IS_VALID_OPCODE (6, CEE_PREFIX1) && ip [ip_offset - 5] == kind)
2396
2397         MonoMethod *invoke, *method;
2398         const guint8 *ip = ctx->header->code;
2399         guint32 ip_offset = ctx->ip_offset;
2400         gboolean is_static_ldftn = FALSE, is_first_arg_bound = FALSE;
2401         
2402         if (stack_slot_get_type (funptr) != TYPE_PTR || !funptr->method) {
2403                 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid function pointer parameter for delegate constructor at 0x%04x", ctx->ip_offset));
2404                 return;
2405         }
2406         
2407         invoke = mono_get_delegate_invoke (delegate);
2408         method = funptr->method;
2409
2410         if (!method || !mono_method_signature (method)) {
2411                 char *name = mono_type_get_full_name (delegate);
2412                 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid method on stack to create delegate %s construction at 0x%04x", name, ctx->ip_offset));
2413                 g_free (name);
2414                 return;
2415         }
2416
2417         if (!invoke || !mono_method_signature (invoke)) {
2418                 char *name = mono_type_get_full_name (delegate);
2419                 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Delegate type %s with bad Invoke method at 0x%04x", name, ctx->ip_offset));
2420                 g_free (name);
2421                 return;
2422         }
2423
2424         is_static_ldftn = (ip_offset > 5 && IS_LOAD_FUN_PTR (CEE_LDFTN)) && method->flags & METHOD_ATTRIBUTE_STATIC;
2425
2426         if (is_static_ldftn)
2427                 is_first_arg_bound = mono_method_signature (invoke)->param_count + 1 ==  mono_method_signature (method)->param_count;
2428
2429         if (!mono_delegate_signature_equal (mono_method_signature (invoke), mono_method_signature (method), is_first_arg_bound)) {
2430                 char *fun_sig = mono_signature_get_desc (mono_method_signature (method), FALSE);
2431                 char *invoke_sig = mono_signature_get_desc (mono_method_signature (invoke), FALSE);
2432                 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));
2433                 g_free (fun_sig);
2434                 g_free (invoke_sig);
2435         }
2436
2437         /* 
2438          * Delegate code sequences:
2439          * [-6] ldftn token
2440          * newobj ...
2441          * 
2442          * 
2443          * [-7] dup
2444          * [-6] ldvirtftn token
2445          * newobj ...
2446          * 
2447          * ldftn sequence:*/
2448         if (ip_offset > 5 && IS_LOAD_FUN_PTR (CEE_LDFTN)) {
2449                 verify_ldftn_delegate (ctx, delegate, value, funptr);
2450         } else if (ip_offset > 6 && IS_VALID_OPCODE (7, CEE_DUP) && IS_LOAD_FUN_PTR (CEE_LDVIRTFTN)) {
2451                 ctx->code [ip_offset - 6].flags |= IL_CODE_DELEGATE_SEQUENCE;   
2452         }else {
2453                 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid code sequence for delegate creation at 0x%04x", ctx->ip_offset));
2454         }
2455         ctx->code [ip_offset].flags |= IL_CODE_DELEGATE_SEQUENCE;
2456
2457         //general tests
2458         if (is_first_arg_bound) {
2459                 if (mono_method_signature (method)->param_count == 0 || !verify_stack_type_compatibility_full (ctx, mono_method_signature (method)->params [0], value, FALSE, TRUE))
2460                         CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("This object not compatible with function pointer for delegate creation at 0x%04x", ctx->ip_offset));
2461         } else {
2462                 if (method->flags & METHOD_ATTRIBUTE_STATIC) {
2463                         if (!stack_slot_is_null_literal (value) && !is_first_arg_bound)
2464                                 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Non-null this args used with static function for delegate creation at 0x%04x", ctx->ip_offset));
2465                 } else {
2466                         if (!verify_stack_type_compatibility_full (ctx, &method->klass->byval_arg, value, FALSE, TRUE) && !stack_slot_is_null_literal (value))
2467                                 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("This object not compatible with function pointer for delegate creation at 0x%04x", ctx->ip_offset));
2468                 }
2469         }
2470
2471         if (stack_slot_get_type (value) != TYPE_COMPLEX)
2472                 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid first parameter for delegate creation at 0x%04x", ctx->ip_offset));
2473
2474 #undef IS_VALID_OPCODE
2475 #undef IS_LOAD_FUN_PTR
2476 }
2477
2478 /* implement the opcode checks*/
2479 static void
2480 push_arg (VerifyContext *ctx, unsigned int arg, int take_addr) 
2481 {
2482         ILStackDesc *top;
2483
2484         if (arg >= ctx->max_args) {
2485                 if (take_addr) 
2486                         ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Method doesn't have argument %d", arg + 1));
2487                 else {
2488                         CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Method doesn't have argument %d", arg + 1));
2489                         if (check_overflow (ctx)) //FIXME: what sane value could we ever push?
2490                                 stack_push_val (ctx, TYPE_I4, &mono_defaults.int32_class->byval_arg);
2491                 }
2492         } else if (check_overflow (ctx)) {
2493                 /*We must let the value be pushed, otherwise we would get an underflow error*/
2494                 check_unverifiable_type (ctx, ctx->params [arg]);
2495                 if (ctx->params [arg]->byref && take_addr)
2496                         CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("ByRef of ByRef at 0x%04x", ctx->ip_offset));
2497                 top = stack_push (ctx);
2498                 if (!set_stack_value (ctx, top, ctx->params [arg], take_addr))
2499                         return;
2500
2501                 if (arg == 0 && !(ctx->method->flags & METHOD_ATTRIBUTE_STATIC)) {
2502                         if (take_addr)
2503                                 ctx->has_this_store = TRUE;
2504                         else
2505                                 top->stype |= THIS_POINTER_MASK;
2506                         if (mono_method_is_constructor (ctx->method) && !ctx->super_ctor_called && !ctx->method->klass->valuetype)
2507                                 top->stype |= UNINIT_THIS_MASK;
2508                 }
2509         } 
2510 }
2511
2512 static void
2513 push_local (VerifyContext *ctx, guint32 arg, int take_addr) 
2514 {
2515         if (arg >= ctx->num_locals) {
2516                 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Method doesn't have local %d", arg + 1));
2517         } else if (check_overflow (ctx)) {
2518                 /*We must let the value be pushed, otherwise we would get an underflow error*/
2519                 check_unverifiable_type (ctx, ctx->locals [arg]);
2520                 if (ctx->locals [arg]->byref && take_addr)
2521                         CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("ByRef of ByRef at 0x%04x", ctx->ip_offset));
2522
2523                 set_stack_value (ctx, stack_push (ctx), ctx->locals [arg], take_addr);
2524         } 
2525 }
2526
2527 static void
2528 store_arg (VerifyContext *ctx, guint32 arg)
2529 {
2530         ILStackDesc *value;
2531
2532         if (arg >= ctx->max_args) {
2533                 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Method doesn't have argument %d at 0x%04x", arg + 1, ctx->ip_offset));
2534                 if (check_underflow (ctx, 1))
2535                         stack_pop (ctx);
2536                 return;
2537         }
2538
2539         if (check_underflow (ctx, 1)) {
2540                 value = stack_pop (ctx);
2541                 if (!verify_stack_type_compatibility (ctx, ctx->params [arg], value)) {
2542                         CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Incompatible type %s in argument store at 0x%04x", stack_slot_get_name (value), ctx->ip_offset));
2543                 }
2544         }
2545         if (arg == 0 && !(ctx->method->flags & METHOD_ATTRIBUTE_STATIC))
2546                 ctx->has_this_store = 1;
2547 }
2548
2549 static void
2550 store_local (VerifyContext *ctx, guint32 arg)
2551 {
2552         ILStackDesc *value;
2553         if (arg >= ctx->num_locals) {
2554                 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Method doesn't have local var %d at 0x%04x", arg + 1, ctx->ip_offset));
2555                 return;
2556         }
2557
2558         /*TODO verify definite assigment */             
2559         if (check_underflow (ctx, 1)) {
2560                 value = stack_pop(ctx);
2561                 if (!verify_stack_type_compatibility (ctx, ctx->locals [arg], value)) {
2562                         char *expected = mono_type_full_name (ctx->locals [arg]);
2563                         char *found = stack_slot_full_name (value);
2564                         CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Incompatible type '%s' on stack cannot be stored to local %d with type '%s' at 0x%04x",
2565                                         found,
2566                                         arg,
2567                                         expected,
2568                                         ctx->ip_offset));
2569                         g_free (expected);
2570                         g_free (found); 
2571                 }
2572         }
2573 }
2574
2575 /*FIXME add and sub needs special care here*/
2576 static void
2577 do_binop (VerifyContext *ctx, unsigned int opcode, const unsigned char table [TYPE_MAX][TYPE_MAX])
2578 {
2579         ILStackDesc *a, *b, *top;
2580         int idxa, idxb, complexMerge = 0;
2581         unsigned char res;
2582
2583         if (!check_underflow (ctx, 2))
2584                 return;
2585         b = stack_pop (ctx);
2586         a = stack_pop (ctx);
2587
2588         idxa = stack_slot_get_underlying_type (a);
2589         if (stack_slot_is_managed_pointer (a)) {
2590                 idxa = TYPE_PTR;
2591                 complexMerge = 1;
2592         }
2593
2594         idxb = stack_slot_get_underlying_type (b);
2595         if (stack_slot_is_managed_pointer (b)) {
2596                 idxb = TYPE_PTR;
2597                 complexMerge = 2;
2598         }
2599
2600         --idxa;
2601         --idxb;
2602         res = table [idxa][idxb];
2603
2604         VERIFIER_DEBUG ( printf ("binop res %d\n", res); );
2605         VERIFIER_DEBUG ( printf ("idxa %d idxb %d\n", idxa, idxb); );
2606
2607         top = stack_push (ctx);
2608         if (res == TYPE_INV) {
2609                 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)));
2610                 copy_stack_value (top, a);
2611                 return;
2612         }
2613
2614         if (res & NON_VERIFIABLE_RESULT) {
2615                 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)));
2616
2617                 res = res & ~NON_VERIFIABLE_RESULT;
2618         }
2619
2620         if (complexMerge && res == TYPE_PTR) {
2621                 if (complexMerge == 1) 
2622                         copy_stack_value (top, a);
2623                 else if (complexMerge == 2)
2624                         copy_stack_value (top, b);
2625                 /*
2626                  * There is no need to merge the type of two pointers.
2627                  * The only valid operation is subtraction, that returns a native
2628                  *  int as result and can be used with any 2 pointer kinds.
2629                  * This is valid acording to Patition III 1.1.4
2630                  */
2631         } else
2632                 top->stype = res;
2633         
2634 }
2635
2636
2637 static void
2638 do_boolean_branch_op (VerifyContext *ctx, int delta)
2639 {
2640         int target = ctx->ip_offset + delta;
2641         ILStackDesc *top;
2642
2643         VERIFIER_DEBUG ( printf ("boolean branch offset %d delta %d target %d\n", ctx->ip_offset, delta, target); );
2644  
2645         if (target < 0 || target >= ctx->code_size) {
2646                 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Boolean branch target out of code at 0x%04x", ctx->ip_offset));
2647                 return;
2648         }
2649
2650         switch (is_valid_branch_instruction (ctx->header, ctx->ip_offset, target)) {
2651         case 1:
2652                 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Branch target escapes out of exception block at 0x%04x", ctx->ip_offset));
2653                 break;
2654         case 2:
2655                 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Branch target escapes out of exception block at 0x%04x", ctx->ip_offset));
2656                 return;
2657         }
2658
2659         ctx->target = target;
2660
2661         if (!check_underflow (ctx, 1))
2662                 return;
2663
2664         top = stack_pop (ctx);
2665         if (!is_valid_bool_arg (top))
2666                 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));
2667
2668         check_unmanaged_pointer (ctx, top);
2669 }
2670
2671 static gboolean
2672 stack_slot_is_complex_type_not_reference_type (ILStackDesc *slot)
2673 {
2674         return stack_slot_get_type (slot) == TYPE_COMPLEX && !MONO_TYPE_IS_REFERENCE (slot->type) && !stack_slot_is_boxed_value (slot);
2675 }
2676
2677 static void
2678 do_branch_op (VerifyContext *ctx, signed int delta, const unsigned char table [TYPE_MAX][TYPE_MAX])
2679 {
2680         ILStackDesc *a, *b;
2681         int idxa, idxb;
2682         unsigned char res;
2683         int target = ctx->ip_offset + delta;
2684
2685         VERIFIER_DEBUG ( printf ("branch offset %d delta %d target %d\n", ctx->ip_offset, delta, target); );
2686  
2687         if (target < 0 || target >= ctx->code_size) {
2688                 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Branch target out of code at 0x%04x", ctx->ip_offset));
2689                 return;
2690         }
2691
2692         switch (is_valid_cmp_branch_instruction (ctx->header, ctx->ip_offset, target)) {
2693         case 1: /*FIXME use constants and not magic numbers.*/
2694                 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Branch target escapes out of exception block at 0x%04x", ctx->ip_offset));
2695                 break;
2696         case 2:
2697                 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Branch target escapes out of exception block at 0x%04x", ctx->ip_offset));
2698                 return;
2699         }
2700
2701         ctx->target = target;
2702
2703         if (!check_underflow (ctx, 2))
2704                 return;
2705
2706         b = stack_pop (ctx);
2707         a = stack_pop (ctx);
2708
2709         idxa = stack_slot_get_underlying_type (a);
2710         if (stack_slot_is_managed_pointer (a))
2711                 idxa = TYPE_PTR;
2712
2713         idxb = stack_slot_get_underlying_type (b);
2714         if (stack_slot_is_managed_pointer (b))
2715                 idxb = TYPE_PTR;
2716
2717         if (stack_slot_is_complex_type_not_reference_type (a) || stack_slot_is_complex_type_not_reference_type (b)) {
2718                 res = TYPE_INV;
2719         } else {
2720                 --idxa;
2721                 --idxb;
2722                 res = table [idxa][idxb];
2723         }
2724
2725         VERIFIER_DEBUG ( printf ("branch res %d\n", res); );
2726         VERIFIER_DEBUG ( printf ("idxa %d idxb %d\n", idxa, idxb); );
2727
2728         if (res == TYPE_INV) {
2729                 CODE_NOT_VERIFIABLE (ctx,
2730                         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));
2731         } else if (res & NON_VERIFIABLE_RESULT) {
2732                         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)); 
2733                 res = res & ~NON_VERIFIABLE_RESULT;
2734         }
2735 }
2736
2737 static void
2738 do_cmp_op (VerifyContext *ctx, const unsigned char table [TYPE_MAX][TYPE_MAX], guint32 opcode)
2739 {
2740         ILStackDesc *a, *b;
2741         int idxa, idxb;
2742         unsigned char res;
2743
2744         if (!check_underflow (ctx, 2))
2745                 return;
2746         b = stack_pop (ctx);
2747         a = stack_pop (ctx);
2748
2749         if (opcode == CEE_CGT_UN) {
2750                 if (stack_slot_get_type (a) == TYPE_COMPLEX && stack_slot_get_type (b) == TYPE_COMPLEX) {
2751                         stack_push_val (ctx, TYPE_I4, &mono_defaults.int32_class->byval_arg);
2752                         return;
2753                 }
2754         }
2755
2756         idxa = stack_slot_get_underlying_type (a);
2757         if (stack_slot_is_managed_pointer (a))
2758                 idxa = TYPE_PTR;
2759
2760         idxb = stack_slot_get_underlying_type (b);
2761         if (stack_slot_is_managed_pointer (b)) 
2762                 idxb = TYPE_PTR;
2763
2764         if (stack_slot_is_complex_type_not_reference_type (a) || stack_slot_is_complex_type_not_reference_type (b)) {
2765                 res = TYPE_INV;
2766         } else {
2767                 --idxa;
2768                 --idxb;
2769                 res = table [idxa][idxb];
2770         }
2771
2772         if(res == TYPE_INV) {
2773                 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));
2774         } else if (res & NON_VERIFIABLE_RESULT) {
2775                 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)); 
2776                 res = res & ~NON_VERIFIABLE_RESULT;
2777         }
2778         stack_push_val (ctx, TYPE_I4, &mono_defaults.int32_class->byval_arg);
2779 }
2780
2781 static void
2782 do_ret (VerifyContext *ctx)
2783 {
2784         MonoType *ret = ctx->signature->ret;
2785         VERIFIER_DEBUG ( printf ("checking ret\n"); );
2786         if (ret->type != MONO_TYPE_VOID) {
2787                 ILStackDesc *top;
2788                 if (!check_underflow (ctx, 1))
2789                         return;
2790
2791                 top = stack_pop(ctx);
2792
2793                 if (!verify_stack_type_compatibility (ctx, ctx->signature->ret, top)) {
2794                         CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Incompatible return value on stack with method signature ret at 0x%04x", ctx->ip_offset));
2795                         return;
2796                 }
2797
2798                 if (ret->byref || ret->type == MONO_TYPE_TYPEDBYREF || mono_type_is_value_type (ret, "System", "ArgIterator") || mono_type_is_value_type (ret, "System", "RuntimeArgumentHandle"))
2799                         CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Method returns byref, TypedReference, ArgIterator or RuntimeArgumentHandle at 0x%04x", ctx->ip_offset));
2800         }
2801
2802         if (ctx->eval.size > 0) {
2803                 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Stack not empty (%d) after ret at 0x%04x", ctx->eval.size, ctx->ip_offset));
2804         } 
2805         if (in_any_block (ctx->header, ctx->ip_offset))
2806                 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("ret cannot escape exception blocks at 0x%04x", ctx->ip_offset));
2807 }
2808
2809 /*
2810  * 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.
2811  *      This is illegal but mono_get_method_full decoded it.
2812  * TODO handle calling .ctor outside one or calling the .ctor for other class but super  
2813  */
2814 static void
2815 do_invoke_method (VerifyContext *ctx, int method_token, gboolean virtual)
2816 {
2817         int param_count, i;
2818         MonoMethodSignature *sig;
2819         ILStackDesc *value;
2820         MonoMethod *method;
2821         gboolean virt_check_this = FALSE;
2822         gboolean constrained = ctx->prefix_set & PREFIX_CONSTRAINED;
2823
2824         if (!(method = verifier_load_method (ctx, method_token, virtual ? "callvirt" : "call")))
2825                 return;
2826
2827         if (virtual) {
2828                 CLEAR_PREFIX (ctx, PREFIX_CONSTRAINED);
2829
2830                 if (method->klass->valuetype) // && !constrained ???
2831                         CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use callvirtual with valuetype method at 0x%04x", ctx->ip_offset));
2832
2833                 if ((method->flags & METHOD_ATTRIBUTE_STATIC))
2834                         CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use callvirtual with static method at 0x%04x", ctx->ip_offset));
2835
2836         } else {
2837                 if (method->flags & METHOD_ATTRIBUTE_ABSTRACT) 
2838                         CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use call with an abstract method at 0x%04x", ctx->ip_offset));
2839                 
2840                 if ((method->flags & METHOD_ATTRIBUTE_VIRTUAL) && !(method->flags & METHOD_ATTRIBUTE_FINAL) && !(method->klass->flags & TYPE_ATTRIBUTE_SEALED)) {
2841                         virt_check_this = TRUE;
2842                         ctx->code [ctx->ip_offset].flags |= IL_CODE_CALL_NONFINAL_VIRTUAL;
2843                 }
2844         }
2845
2846         if (!(sig = mono_method_get_signature_full (method, ctx->image, method_token, ctx->generic_context)))
2847                 sig = mono_method_get_signature (method, ctx->image, method_token);
2848
2849         if (!sig) {
2850                 char *name = mono_type_get_full_name (method->klass);
2851                 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Could not resolve signature of %s:%s at 0x%04x", name, method->name, ctx->ip_offset));
2852                 g_free (name);
2853                 return;
2854         }
2855
2856         param_count = sig->param_count + sig->hasthis;
2857         if (!check_underflow (ctx, param_count))
2858                 return;
2859
2860         for (i = sig->param_count - 1; i >= 0; --i) {
2861                 VERIFIER_DEBUG ( printf ("verifying argument %d\n", i); );
2862                 value = stack_pop (ctx);
2863                 if (!verify_stack_type_compatibility (ctx, sig->params[i], value)) {
2864                         char *stack_name = stack_slot_full_name (value);
2865                         char *sig_name = mono_type_full_name (sig->params [i]);
2866                         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));
2867                         g_free (stack_name);
2868                         g_free (sig_name);
2869                 }
2870
2871                 if (stack_slot_is_managed_mutability_pointer (value))
2872                         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));
2873
2874                 if ((ctx->prefix_set & PREFIX_TAIL) && stack_slot_is_managed_pointer (value)) {
2875                         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));
2876                         return;
2877                 }
2878         }
2879
2880         if (sig->hasthis) {
2881                 MonoType *type = &method->klass->byval_arg;
2882                 ILStackDesc copy;
2883
2884                 if (mono_method_is_constructor (method) && !method->klass->valuetype) {
2885                         if (!mono_method_is_constructor (ctx->method))
2886                                 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot call a constructor outside one at 0x%04x", ctx->ip_offset));
2887                         if (method->klass != ctx->method->klass->parent && method->klass != ctx->method->klass)
2888                                 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));
2889
2890                         ctx->super_ctor_called = TRUE;
2891                         value = stack_pop_safe (ctx);
2892                         if ((value->stype & THIS_POINTER_MASK) != THIS_POINTER_MASK)
2893                                 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid 'this ptr' argument for constructor at 0x%04x", ctx->ip_offset));
2894                 } else {
2895                         value = stack_pop (ctx);
2896                 }
2897                         
2898                 copy_stack_value (&copy, value);
2899                 //TODO we should extract this to a 'drop_byref_argument' and use everywhere
2900                 //Other parts of the code suffer from the same issue of 
2901                 copy.type = mono_type_get_type_byval (copy.type);
2902                 copy.stype &= ~POINTER_MASK;
2903
2904                 if (virt_check_this && !stack_slot_is_this_pointer (value) && !(method->klass->valuetype || stack_slot_is_boxed_value (value)))
2905                         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));
2906
2907                 if (constrained && virtual) {
2908                         if (!stack_slot_is_managed_pointer (value))
2909                                 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Object is not a managed pointer for a constrained call at 0x%04x", ctx->ip_offset));
2910                         if (!mono_metadata_type_equal_full (mono_type_get_type_byval (value->type), ctx->constrained_type, TRUE))
2911                                 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Object not compatible with constrained type at 0x%04x", ctx->ip_offset));
2912                         copy.stype |= BOXED_MASK;
2913                 } else {
2914                         if (stack_slot_is_managed_pointer (value) && !mono_class_from_mono_type (value->type)->valuetype)
2915                                 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));
2916         
2917                         if (!virtual && mono_class_from_mono_type (value->type)->valuetype && !method->klass->valuetype && !stack_slot_is_boxed_value (value))
2918                                 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot call a valuetype baseclass at 0x%04x", ctx->ip_offset));
2919         
2920                         if (virtual && mono_class_from_mono_type (value->type)->valuetype && !stack_slot_is_boxed_value (value))
2921                                 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use a valuetype with callvirt at 0x%04x", ctx->ip_offset));
2922         
2923                         if (method->klass->valuetype && (stack_slot_is_boxed_value (value) || !stack_slot_is_managed_pointer (value)))
2924                                 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));
2925                 }
2926                 if (!verify_stack_type_compatibility (ctx, type, &copy))
2927                         CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Incompatible this argument on stack with method signature at 0x%04x", ctx->ip_offset));
2928
2929                 if (!IS_SKIP_VISIBILITY (ctx) && !mono_method_can_access_method_full (ctx->method, method, mono_class_from_mono_type (value->type))) {
2930                         char *name = mono_method_full_name (method, TRUE);
2931                         CODE_NOT_VERIFIABLE2 (ctx, g_strdup_printf ("Method %s is not accessible at 0x%04x", name, ctx->ip_offset), MONO_EXCEPTION_METHOD_ACCESS);
2932                         g_free (name);
2933                 }
2934
2935         } else if (!IS_SKIP_VISIBILITY (ctx) && !mono_method_can_access_method_full (ctx->method, method, NULL)) {
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         if (sig->ret->type != MONO_TYPE_VOID) {
2942                 if (check_overflow (ctx)) {
2943                         value = stack_push (ctx);
2944                         set_stack_value (ctx, value, sig->ret, FALSE);
2945                         if ((ctx->prefix_set & PREFIX_READONLY) && method->klass->rank && !strcmp (method->name, "Address")) {
2946                                 ctx->prefix_set &= ~PREFIX_READONLY;
2947                                 value->stype |= CMMP_MASK;
2948                         }
2949                 }
2950         }
2951
2952         if ((ctx->prefix_set & PREFIX_TAIL)) {
2953                 if (!mono_delegate_ret_equal (mono_method_signature (ctx->method)->ret, sig->ret))
2954                         CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Tail call with incompatible return type at 0x%04x", ctx->ip_offset));
2955                 if (ctx->header->code [ctx->ip_offset + 5] != CEE_RET)
2956                         CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Tail call not followed by ret at 0x%04x", ctx->ip_offset));
2957         }
2958
2959 }
2960
2961 static void
2962 do_push_static_field (VerifyContext *ctx, int token, gboolean take_addr)
2963 {
2964         MonoClassField *field;
2965         MonoClass *klass;
2966         if (!check_overflow (ctx))
2967                 return;
2968         if (!take_addr)
2969                 CLEAR_PREFIX (ctx, PREFIX_VOLATILE);
2970
2971         if (!(field = verifier_load_field (ctx, token, &klass, take_addr ? "ldsflda" : "ldsfld")))
2972                 return;
2973
2974         if (!(field->type->attrs & FIELD_ATTRIBUTE_STATIC)) { 
2975                 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Cannot load non static field at 0x%04x", ctx->ip_offset));
2976                 return;
2977         }
2978         /*taking the address of initonly field only works from the static constructor */
2979         if (take_addr && (field->type->attrs & FIELD_ATTRIBUTE_INIT_ONLY) &&
2980                 !(field->parent == ctx->method->klass && (ctx->method->flags & (METHOD_ATTRIBUTE_SPECIAL_NAME | METHOD_ATTRIBUTE_STATIC)) && !strcmp (".cctor", ctx->method->name)))
2981                 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot take the address of a init-only field at 0x%04x", ctx->ip_offset));
2982
2983         if (!IS_SKIP_VISIBILITY (ctx) && !mono_method_can_access_field_full (ctx->method, field, NULL))
2984                 CODE_NOT_VERIFIABLE2 (ctx, g_strdup_printf ("Type at stack is not accessible at 0x%04x", ctx->ip_offset), MONO_EXCEPTION_FIELD_ACCESS);
2985
2986         set_stack_value (ctx, stack_push (ctx), field->type, take_addr);
2987 }
2988
2989 static void
2990 do_store_static_field (VerifyContext *ctx, int token) {
2991         MonoClassField *field;
2992         MonoClass *klass;
2993         ILStackDesc *value;
2994         CLEAR_PREFIX (ctx, PREFIX_VOLATILE);
2995
2996         if (!check_underflow (ctx, 1))
2997                 return;
2998
2999         value = stack_pop (ctx);
3000
3001         if (!(field = verifier_load_field (ctx, token, &klass, "stsfld")))
3002                 return;
3003
3004         if (!(field->type->attrs & FIELD_ATTRIBUTE_STATIC)) { 
3005                 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Cannot store non static field at 0x%04x", ctx->ip_offset));
3006                 return;
3007         }
3008
3009         if (field->type->type == MONO_TYPE_TYPEDBYREF) {
3010                 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Typedbyref field is an unverfiable type in store static field at 0x%04x", ctx->ip_offset));
3011                 return;
3012         }
3013
3014         if (!IS_SKIP_VISIBILITY (ctx) && !mono_method_can_access_field_full (ctx->method, field, NULL))
3015                 CODE_NOT_VERIFIABLE2 (ctx, g_strdup_printf ("Type at stack is not accessible at 0x%04x", ctx->ip_offset), MONO_EXCEPTION_FIELD_ACCESS);
3016
3017         if (!verify_stack_type_compatibility (ctx, field->type, value))
3018                 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));       
3019 }
3020
3021 static gboolean
3022 check_is_valid_type_for_field_ops (VerifyContext *ctx, int token, ILStackDesc *obj, MonoClassField **ret_field, const char *opcode)
3023 {
3024         MonoClassField *field;
3025         MonoClass *klass;
3026         gboolean is_pointer;
3027
3028         /*must be a reference type, a managed pointer, an unamanaged pointer, or a valuetype*/
3029         if (!(field = verifier_load_field (ctx, token, &klass, opcode)))
3030                 return FALSE;
3031
3032         *ret_field = field;
3033         //the value on stack is going to be used as a pointer
3034         is_pointer = stack_slot_get_type (obj) == TYPE_PTR || (stack_slot_get_type (obj) == TYPE_NATIVE_INT && !get_stack_type (&field->parent->byval_arg));
3035
3036         if (field->type->type == MONO_TYPE_TYPEDBYREF) {
3037                 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Typedbyref field is an unverfiable type at 0x%04x", ctx->ip_offset));
3038                 return FALSE;
3039         }
3040         g_assert (obj->type);
3041
3042         /*The value on the stack must be a subclass of the defining type of the field*/ 
3043         /* we need to check if we can load the field from the stack value*/
3044         if (is_pointer) {
3045                 if (stack_slot_get_underlying_type (obj) == TYPE_NATIVE_INT)
3046                         CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Native int is not a verifiable type to reference a field at 0x%04x", ctx->ip_offset));
3047
3048                 if (!IS_SKIP_VISIBILITY (ctx) && !mono_method_can_access_field_full (ctx->method, field, NULL))
3049                                 CODE_NOT_VERIFIABLE2 (ctx, g_strdup_printf ("Type at stack is not accessible at 0x%04x", ctx->ip_offset), MONO_EXCEPTION_FIELD_ACCESS);
3050         } else {
3051                 if (!field->parent->valuetype && stack_slot_is_managed_pointer (obj))
3052                         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));
3053
3054                 /*a value type can be loaded from a value or a managed pointer, but not a boxed object*/
3055                 if (field->parent->valuetype && stack_slot_is_boxed_value (obj))
3056                         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));
3057
3058                 if (!stack_slot_is_null_literal (obj) && !verify_stack_type_compatibility_full (ctx, &field->parent->byval_arg, obj, TRUE, FALSE)) {
3059                         char *found = stack_slot_full_name (obj);
3060                         char *expected = mono_type_full_name (&field->parent->byval_arg);
3061                         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));
3062                         g_free (found);
3063                         g_free (expected);
3064                 }
3065
3066                 if (!IS_SKIP_VISIBILITY (ctx) && !mono_method_can_access_field_full (ctx->method, field, mono_class_from_mono_type (obj->type)))
3067                         CODE_NOT_VERIFIABLE2 (ctx, g_strdup_printf ("Type at stack is not accessible at 0x%04x", ctx->ip_offset), MONO_EXCEPTION_FIELD_ACCESS);
3068         } 
3069
3070         check_unmanaged_pointer (ctx, obj);
3071         return TRUE;
3072 }
3073
3074 static void
3075 do_push_field (VerifyContext *ctx, int token, gboolean take_addr)
3076 {
3077         ILStackDesc *obj;
3078         MonoClassField *field;
3079
3080         if (!take_addr)
3081                 CLEAR_PREFIX (ctx, PREFIX_UNALIGNED | PREFIX_VOLATILE);
3082
3083         if (!check_underflow (ctx, 1))
3084                 return;
3085         obj = stack_pop_safe (ctx);
3086
3087         if (!check_is_valid_type_for_field_ops (ctx, token, obj, &field, take_addr ? "ldflda" : "ldfld"))
3088                 return;
3089
3090         if (take_addr && field->parent->valuetype && !stack_slot_is_managed_pointer (obj))
3091                 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot take the address of a temporary value-type at 0x%04x", ctx->ip_offset));
3092
3093         if (take_addr && (field->type->attrs & FIELD_ATTRIBUTE_INIT_ONLY) &&
3094                 !(field->parent == ctx->method->klass && mono_method_is_constructor (ctx->method)))
3095                 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot take the address of a init-only field at 0x%04x", ctx->ip_offset));
3096
3097         set_stack_value (ctx, stack_push (ctx), field->type, take_addr);
3098 }
3099
3100 static void
3101 do_store_field (VerifyContext *ctx, int token)
3102 {
3103         ILStackDesc *value, *obj;
3104         MonoClassField *field;
3105         CLEAR_PREFIX (ctx, PREFIX_UNALIGNED | PREFIX_VOLATILE);
3106
3107         if (!check_underflow (ctx, 2))
3108                 return;
3109
3110         value = stack_pop (ctx);
3111         obj = stack_pop_safe (ctx);
3112
3113         if (!check_is_valid_type_for_field_ops (ctx, token, obj, &field, "stfld"))
3114                 return;
3115
3116         if (!verify_stack_type_compatibility (ctx, field->type, value))
3117                 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Incompatible type %s in field store at 0x%04x", stack_slot_get_name (value), ctx->ip_offset));      
3118 }
3119
3120 /*TODO proper handle for Nullable<T>*/
3121 static void
3122 do_box_value (VerifyContext *ctx, int klass_token)
3123 {
3124         ILStackDesc *value;
3125         MonoType *type = get_boxable_mono_type (ctx, klass_token, "box");
3126         MonoClass *klass;       
3127
3128         if (!type)
3129                 return;
3130
3131         if (!check_underflow (ctx, 1))
3132                 return;
3133
3134         value = stack_pop (ctx);
3135         /*box is a nop for reference types*/
3136
3137         if (stack_slot_get_underlying_type (value) == TYPE_COMPLEX && MONO_TYPE_IS_REFERENCE (value->type) && MONO_TYPE_IS_REFERENCE (type)) {
3138                 stack_push_stack_val (ctx, value)->stype |= BOXED_MASK;
3139                 return;
3140         }
3141
3142
3143         if (!verify_stack_type_compatibility (ctx, type, value))
3144                 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid type at stack for boxing operation at 0x%04x", ctx->ip_offset));
3145
3146         klass = mono_class_from_mono_type (type);
3147         if (mono_class_is_nullable (klass))
3148                 type = &mono_class_get_nullable_param (klass)->byval_arg;
3149         stack_push_val (ctx, TYPE_COMPLEX | BOXED_MASK, type);
3150 }
3151
3152 static void
3153 do_unbox_value (VerifyContext *ctx, int klass_token)
3154 {
3155         ILStackDesc *value;
3156         MonoType *type = get_boxable_mono_type (ctx, klass_token, "unbox");
3157
3158         if (!type)
3159                 return;
3160  
3161         if (!check_underflow (ctx, 1))
3162                 return;
3163
3164         if (!mono_class_from_mono_type (type)->valuetype)
3165                 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid reference type for unbox at 0x%04x", ctx->ip_offset));
3166
3167         value = stack_pop (ctx);
3168
3169         /*Value should be: a boxed valuetype or a reference type*/
3170         if (!(stack_slot_get_type (value) == TYPE_COMPLEX &&
3171                 (stack_slot_is_boxed_value (value) || !mono_class_from_mono_type (value->type)->valuetype)))
3172                 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));
3173
3174         set_stack_value (ctx, value = stack_push (ctx), mono_type_get_type_byref (type), FALSE);
3175         value->stype |= CMMP_MASK;
3176 }
3177
3178 static void
3179 do_unbox_any (VerifyContext *ctx, int klass_token)
3180 {
3181         ILStackDesc *value;
3182         MonoType *type = get_boxable_mono_type (ctx, klass_token, "unbox.any");
3183
3184         if (!type)
3185                 return;
3186  
3187         if (!check_underflow (ctx, 1))
3188                 return;
3189
3190         value = stack_pop (ctx);
3191
3192         /*Value should be: a boxed valuetype or a reference type*/
3193         if (!(stack_slot_get_type (value) == TYPE_COMPLEX &&
3194                 (stack_slot_is_boxed_value (value) || !mono_class_from_mono_type (value->type)->valuetype)))
3195                 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));
3196  
3197         set_stack_value (ctx, stack_push (ctx), type, FALSE);
3198 }
3199
3200 static void
3201 do_unary_math_op (VerifyContext *ctx, int op)
3202 {
3203         ILStackDesc *value;
3204         if (!check_underflow (ctx, 1))
3205                 return;
3206         value = stack_pop (ctx);
3207         switch (stack_slot_get_type (value)) {
3208         case TYPE_I4:
3209         case TYPE_I8:
3210         case TYPE_NATIVE_INT:
3211                 break;
3212         case TYPE_R8:
3213                 if (op == CEE_NEG)
3214                         break;
3215         case TYPE_COMPLEX: /*only enums are ok*/
3216                 if (mono_type_is_enum_type (value->type))
3217                         break;
3218         default:
3219                 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid type at stack for unary not at 0x%04x", ctx->ip_offset));
3220         }
3221         stack_push_stack_val (ctx, value);
3222 }
3223
3224 static void
3225 do_conversion (VerifyContext *ctx, int kind) 
3226 {
3227         ILStackDesc *value;
3228         if (!check_underflow (ctx, 1))
3229                 return;
3230         value = stack_pop (ctx);
3231
3232         switch (stack_slot_get_type (value)) {
3233         case TYPE_I4:
3234         case TYPE_I8:
3235         case TYPE_NATIVE_INT:
3236         case TYPE_R8:
3237                 break;
3238         default:
3239                 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));
3240         }
3241
3242         switch (kind) {
3243         case TYPE_I4:
3244                 stack_push_val (ctx, TYPE_I4, &mono_defaults.int32_class->byval_arg);
3245                 break;
3246         case TYPE_I8:
3247                 stack_push_val (ctx,TYPE_I8, &mono_defaults.int64_class->byval_arg);
3248                 break;
3249         case TYPE_R8:
3250                 stack_push_val (ctx, TYPE_R8, &mono_defaults.double_class->byval_arg);
3251                 break;
3252         case TYPE_NATIVE_INT:
3253                 stack_push_val (ctx, TYPE_NATIVE_INT, &mono_defaults.int_class->byval_arg);
3254                 break;
3255         default:
3256                 g_error ("unknown type %02x in conversion", kind);
3257
3258         }
3259 }
3260
3261 static void
3262 do_load_token (VerifyContext *ctx, int token) 
3263 {
3264         gpointer handle;
3265         MonoClass *handle_class;
3266         if (!check_overflow (ctx))
3267                 return;
3268         handle = mono_ldtoken (ctx->image, token, &handle_class, ctx->generic_context);
3269         if (!handle) {
3270                 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid token 0x%x for ldtoken at 0x%04x", token, ctx->ip_offset));
3271                 return;
3272         }
3273         if (handle_class == mono_defaults.typehandle_class) {
3274                 mono_type_is_valid_in_context (ctx, (MonoType*)handle);
3275         } else if (handle_class == mono_defaults.methodhandle_class) {
3276                 mono_method_is_valid_in_context (ctx, (MonoMethod*)handle);             
3277         } else if (handle_class == mono_defaults.fieldhandle_class) {
3278                 mono_type_is_valid_in_context (ctx, &((MonoClassField*)handle)->parent->byval_arg);                             
3279         } else {
3280                 ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid ldtoken type %x at 0x%04x", token, ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE);
3281         }
3282         stack_push_val (ctx, TYPE_COMPLEX, mono_class_get_type (handle_class));
3283 }
3284
3285 static void
3286 do_ldobj_value (VerifyContext *ctx, int token) 
3287 {
3288         ILStackDesc *value;
3289         MonoType *type = get_boxable_mono_type (ctx, token, "ldobj");
3290         CLEAR_PREFIX (ctx, PREFIX_UNALIGNED | PREFIX_VOLATILE);
3291
3292         if (!type)
3293                 return;
3294
3295         if (!check_underflow (ctx, 1))
3296                 return;
3297
3298         value = stack_pop (ctx);
3299         if (!stack_slot_is_managed_pointer (value) 
3300                         && stack_slot_get_type (value) != TYPE_NATIVE_INT
3301                         && !(stack_slot_get_type (value) == TYPE_PTR && value->type->type != MONO_TYPE_FNPTR)) {
3302                 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid argument %s to ldobj at 0x%04x", stack_slot_get_name (value), ctx->ip_offset));
3303                 return;
3304         }
3305
3306         if (stack_slot_get_type (value) == TYPE_NATIVE_INT)
3307                 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Using native pointer to ldobj at 0x%04x", ctx->ip_offset));
3308
3309         /*We have a byval on the stack, but the comparison must be strict. */
3310         if (!verify_type_compatibility_full (ctx, type, mono_type_get_type_byval (value->type), TRUE))
3311                 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid type at stack for ldojb operation at 0x%04x", ctx->ip_offset));
3312
3313         set_stack_value (ctx, stack_push (ctx), type, FALSE);
3314 }
3315
3316 static void
3317 do_stobj (VerifyContext *ctx, int token) 
3318 {
3319         ILStackDesc *dest, *src;
3320         MonoType *type = get_boxable_mono_type (ctx, token, "stobj");
3321         CLEAR_PREFIX (ctx, PREFIX_UNALIGNED | PREFIX_VOLATILE);
3322
3323         if (!type)
3324                 return;
3325
3326         if (!check_underflow (ctx, 2))
3327                 return;
3328
3329         src = stack_pop (ctx);
3330         dest = stack_pop (ctx);
3331
3332         if (stack_slot_is_managed_mutability_pointer (dest))
3333                 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use a readonly pointer with stobj at 0x%04x", ctx->ip_offset));
3334
3335         if (!stack_slot_is_managed_pointer (dest)) 
3336                 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid destination of stobj operation at 0x%04x", ctx->ip_offset));
3337
3338         if (stack_slot_is_boxed_value (src) && !MONO_TYPE_IS_REFERENCE (src->type) && !MONO_TYPE_IS_REFERENCE (type))
3339                 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));
3340
3341         if (!verify_stack_type_compatibility (ctx, type, src))
3342                 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Token and source types of stobj don't match at 0x%04x", ctx->ip_offset));
3343
3344         if (!verify_type_compatibility (ctx, mono_type_get_type_byval (dest->type), type))
3345                 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Destination and token types of stobj don't match at 0x%04x", ctx->ip_offset));
3346 }
3347
3348 static void
3349 do_cpobj (VerifyContext *ctx, int token)
3350 {
3351         ILStackDesc *dest, *src;
3352         MonoType *type = get_boxable_mono_type (ctx, token, "cpobj");
3353         if (!type)
3354                 return;
3355
3356         if (!check_underflow (ctx, 2))
3357                 return;
3358
3359         src = stack_pop (ctx);
3360         dest = stack_pop (ctx);
3361
3362         if (!stack_slot_is_managed_pointer (src)) 
3363                 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid source of cpobj operation at 0x%04x", ctx->ip_offset));
3364
3365         if (!stack_slot_is_managed_pointer (dest)) 
3366                 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid destination of cpobj operation at 0x%04x", ctx->ip_offset));
3367
3368         if (stack_slot_is_managed_mutability_pointer (dest))
3369                 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use a readonly pointer with cpobj at 0x%04x", ctx->ip_offset));
3370
3371         if (!verify_type_compatibility (ctx, type, mono_type_get_type_byval (src->type)))
3372                 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Token and source types of cpobj don't match at 0x%04x", ctx->ip_offset));
3373
3374         if (!verify_type_compatibility (ctx, mono_type_get_type_byval (dest->type), type))
3375                 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Destination and token types of cpobj don't match at 0x%04x", ctx->ip_offset));
3376 }
3377
3378 static void
3379 do_initobj (VerifyContext *ctx, int token)
3380 {
3381         ILStackDesc *obj;
3382         MonoType *stack, *type = get_boxable_mono_type (ctx, token, "initobj");
3383         if (!type)
3384                 return;
3385
3386         if (!check_underflow (ctx, 1))
3387                 return;
3388
3389         obj = stack_pop (ctx);
3390
3391         if (!stack_slot_is_managed_pointer (obj)) 
3392                 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid object address for initobj at 0x%04x", ctx->ip_offset));
3393
3394         if (stack_slot_is_managed_mutability_pointer (obj))
3395                 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use a readonly pointer with initobj at 0x%04x", ctx->ip_offset));
3396
3397         stack = mono_type_get_type_byval (obj->type);
3398         if (MONO_TYPE_IS_REFERENCE (stack)) {
3399                 if (!verify_type_compatibility (ctx, stack, type)) 
3400                         CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Type token of initobj not compatible with value on stack at 0x%04x", ctx->ip_offset));
3401                 else if (IS_STRICT_MODE (ctx) && !mono_metadata_type_equal (type, stack)) 
3402                         CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Type token of initobj not compatible with value on stack at 0x%04x", ctx->ip_offset));
3403         } else if (!verify_type_compatibility (ctx, stack, type)) {
3404                 char *expected_name = mono_type_full_name (type);
3405                 char *stack_name = mono_type_full_name (stack);
3406
3407                 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));
3408                 g_free (expected_name);
3409                 g_free (stack_name);
3410         }
3411 }
3412
3413 static void
3414 do_newobj (VerifyContext *ctx, int token) 
3415 {
3416         ILStackDesc *value;
3417         int i;
3418         MonoMethodSignature *sig;
3419         MonoMethod *method;
3420         gboolean is_delegate = FALSE;
3421
3422         if (!(method = verifier_load_method (ctx, token, "newobj")))
3423                 return;
3424
3425         if (!mono_method_is_constructor (method)) {
3426                 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Method from token 0x%08x not a constructor at 0x%04x", token, ctx->ip_offset));
3427                 return;
3428         }
3429
3430         if (method->klass->flags & (TYPE_ATTRIBUTE_ABSTRACT | TYPE_ATTRIBUTE_INTERFACE))
3431                 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Trying to instantiate an abstract or interface type at 0x%04x", ctx->ip_offset));
3432
3433         if (!mono_method_can_access_method_full (ctx->method, method, NULL)) {
3434                 char *from = mono_method_full_name (ctx->method, TRUE);
3435                 char *to = mono_method_full_name (method, TRUE);
3436                 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);
3437                 g_free (from);
3438                 g_free (to);
3439         }
3440
3441         //FIXME use mono_method_get_signature_full
3442         sig = mono_method_signature (method);
3443         if (!sig) {
3444                 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid constructor signature to newobj at 0x%04x", ctx->ip_offset));
3445                 return;
3446         }
3447
3448         if (!check_underflow (ctx, sig->param_count))
3449                 return;
3450
3451         is_delegate = method->klass->parent == mono_defaults.multicastdelegate_class;
3452
3453         if (is_delegate) {
3454                 ILStackDesc *funptr;
3455                 //first arg is object, second arg is fun ptr
3456                 if (sig->param_count != 2) {
3457                         ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid delegate constructor at 0x%04x", ctx->ip_offset));
3458                         return;
3459                 }
3460                 funptr = stack_pop (ctx);
3461                 value = stack_pop (ctx);
3462                 verify_delegate_compatibility (ctx, method->klass, value, funptr);
3463         } else {
3464                 for (i = sig->param_count - 1; i >= 0; --i) {
3465                         VERIFIER_DEBUG ( printf ("verifying constructor argument %d\n", i); );
3466                         value = stack_pop (ctx);
3467                         if (!verify_stack_type_compatibility (ctx, sig->params [i], value)) {
3468                                 char *stack_name = stack_slot_full_name (value);
3469                                 char *sig_name = mono_type_full_name (sig->params [i]);
3470                                 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));
3471                                 g_free (stack_name);
3472                                 g_free (sig_name);
3473                         }
3474
3475                         if (stack_slot_is_managed_mutability_pointer (value))
3476                                 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use a readonly pointer as argument of newobj at 0x%04x", ctx->ip_offset));
3477                 }
3478         }
3479
3480         if (check_overflow (ctx))
3481                 set_stack_value (ctx, stack_push (ctx),  &method->klass->byval_arg, FALSE);
3482 }
3483
3484 static void
3485 do_cast (VerifyContext *ctx, int token, const char *opcode) {
3486         ILStackDesc *value;
3487         MonoType *type;
3488         gboolean is_boxed;
3489         gboolean do_box;
3490
3491         if (!check_underflow (ctx, 1))
3492                 return;
3493
3494         if (!(type = verifier_load_type (ctx, token, opcode)))
3495                 return;
3496
3497         if (type->byref) {
3498                 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid %s type at 0x%04x", opcode, ctx->ip_offset));
3499                 return;
3500         }
3501
3502         value = stack_pop (ctx);
3503         is_boxed = stack_slot_is_boxed_value (value);
3504
3505         if (stack_slot_is_managed_pointer (value))
3506                 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid value for %s at 0x%04x", opcode, ctx->ip_offset));
3507         else if (!MONO_TYPE_IS_REFERENCE  (value->type) && !is_boxed) {
3508                 char *name = stack_slot_full_name (value);
3509                 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));
3510                 g_free (name);
3511         }
3512
3513         switch (value->type->type) {
3514         case MONO_TYPE_FNPTR:
3515         case MONO_TYPE_PTR:
3516         case MONO_TYPE_TYPEDBYREF: 
3517                 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid value for %s at 0x%04x", opcode, ctx->ip_offset));
3518         }
3519
3520         do_box = is_boxed || mono_type_is_generic_argument(type) || mono_class_from_mono_type (type)->valuetype;
3521         stack_push_val (ctx, TYPE_COMPLEX | (do_box ? BOXED_MASK : 0), type);
3522 }
3523
3524 static MonoType *
3525 mono_type_from_opcode (int opcode) {
3526         switch (opcode) {
3527         case CEE_LDIND_I1:
3528         case CEE_LDIND_U1:
3529         case CEE_STIND_I1:
3530         case CEE_LDELEM_I1:
3531         case CEE_LDELEM_U1:
3532         case CEE_STELEM_I1:
3533                 return &mono_defaults.sbyte_class->byval_arg;
3534
3535         case CEE_LDIND_I2:
3536         case CEE_LDIND_U2:
3537         case CEE_STIND_I2:
3538         case CEE_LDELEM_I2:
3539         case CEE_LDELEM_U2:
3540         case CEE_STELEM_I2:
3541                 return &mono_defaults.int16_class->byval_arg;
3542
3543         case CEE_LDIND_I4:
3544         case CEE_LDIND_U4:
3545         case CEE_STIND_I4:
3546         case CEE_LDELEM_I4:
3547         case CEE_LDELEM_U4:
3548         case CEE_STELEM_I4:
3549                 return &mono_defaults.int32_class->byval_arg;
3550
3551         case CEE_LDIND_I8:
3552         case CEE_STIND_I8:
3553         case CEE_LDELEM_I8:
3554         case CEE_STELEM_I8:
3555                 return &mono_defaults.int64_class->byval_arg;
3556
3557         case CEE_LDIND_R4:
3558         case CEE_STIND_R4:
3559         case CEE_LDELEM_R4:
3560         case CEE_STELEM_R4:
3561                 return &mono_defaults.single_class->byval_arg;
3562
3563         case CEE_LDIND_R8:
3564         case CEE_STIND_R8:
3565         case CEE_LDELEM_R8:
3566         case CEE_STELEM_R8:
3567                 return &mono_defaults.double_class->byval_arg;
3568
3569         case CEE_LDIND_I:
3570         case CEE_STIND_I:
3571         case CEE_LDELEM_I:
3572         case CEE_STELEM_I:
3573                 return &mono_defaults.int_class->byval_arg;
3574
3575         case CEE_LDIND_REF:
3576         case CEE_STIND_REF:
3577         case CEE_LDELEM_REF:
3578         case CEE_STELEM_REF:
3579                 return &mono_defaults.object_class->byval_arg;
3580
3581         default:
3582                 g_error ("unknown opcode %02x in mono_type_from_opcode ", opcode);
3583                 return NULL;
3584         }
3585 }
3586
3587 static void
3588 do_load_indirect (VerifyContext *ctx, int opcode)
3589 {
3590         ILStackDesc *value;
3591         CLEAR_PREFIX (ctx, PREFIX_UNALIGNED | PREFIX_VOLATILE);
3592
3593         if (!check_underflow (ctx, 1))
3594                 return;
3595         
3596         value = stack_pop (ctx);
3597         if (!stack_slot_is_managed_pointer (value)) {
3598                 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Load indirect not using a manager pointer at 0x%04x", ctx->ip_offset));
3599                 set_stack_value (ctx, stack_push (ctx), mono_type_from_opcode (opcode), FALSE);
3600                 return;
3601         }
3602
3603         if (opcode == CEE_LDIND_REF) {
3604                 if (stack_slot_get_underlying_type (value) != TYPE_COMPLEX || mono_class_from_mono_type (value->type)->valuetype)
3605                         CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid type at stack for ldind_ref expected object byref operation at 0x%04x", ctx->ip_offset));
3606                 set_stack_value (ctx, stack_push (ctx), mono_type_get_type_byval (value->type), FALSE);
3607         } else {
3608                 if (!verify_type_compatibility_full (ctx, mono_type_from_opcode (opcode), mono_type_get_type_byval (value->type), TRUE))
3609                         CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid type at stack for ldind 0x%x operation at 0x%04x", opcode, ctx->ip_offset));
3610                 set_stack_value (ctx, stack_push (ctx), mono_type_from_opcode (opcode), FALSE);
3611         }
3612 }
3613
3614 static void
3615 do_store_indirect (VerifyContext *ctx, int opcode)
3616 {
3617         ILStackDesc *addr, *val;
3618         CLEAR_PREFIX (ctx, PREFIX_UNALIGNED | PREFIX_VOLATILE);
3619
3620         if (!check_underflow (ctx, 2))
3621                 return;
3622
3623         val = stack_pop (ctx);
3624         addr = stack_pop (ctx); 
3625
3626         check_unmanaged_pointer (ctx, addr);
3627
3628         if (!stack_slot_is_managed_pointer (addr) && stack_slot_get_type (addr) != TYPE_PTR) {
3629                 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid non-pointer argument to stind at 0x%04x", ctx->ip_offset));
3630                 return;
3631         }
3632
3633         if (stack_slot_is_managed_mutability_pointer (addr)) {
3634                 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use a readonly pointer with stind at 0x%04x", ctx->ip_offset));
3635                 return;
3636         }
3637
3638         if (!verify_type_compatibility_full (ctx, mono_type_from_opcode (opcode), mono_type_get_type_byval (addr->type), TRUE))
3639                 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid addr type at stack for stind 0x%x operation at 0x%04x", opcode, ctx->ip_offset));
3640
3641         if (!verify_stack_type_compatibility (ctx, mono_type_from_opcode (opcode), val))
3642                 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid value type at stack for stind 0x%x operation at 0x%04x", opcode, ctx->ip_offset));
3643 }
3644
3645 static void
3646 do_newarr (VerifyContext *ctx, int token) 
3647 {
3648         ILStackDesc *value;
3649         MonoType *type = get_boxable_mono_type (ctx, token, "newarr");
3650
3651         if (!type)
3652                 return;
3653
3654         if (!check_underflow (ctx, 1))
3655                 return;
3656
3657         value = stack_pop (ctx);
3658         if (stack_slot_get_type (value) != TYPE_I4 && stack_slot_get_type (value) != TYPE_NATIVE_INT)
3659                 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));
3660
3661         set_stack_value (ctx, stack_push (ctx), mono_class_get_type (mono_array_class_get (mono_class_from_mono_type (type), 1)), FALSE);
3662 }
3663
3664 /*FIXME handle arrays that are not 0-indexed*/
3665 static void
3666 do_ldlen (VerifyContext *ctx)
3667 {
3668         ILStackDesc *value;
3669
3670         if (!check_underflow (ctx, 1))
3671                 return;
3672
3673         value = stack_pop (ctx);
3674
3675         if (stack_slot_get_type (value) != TYPE_COMPLEX || value->type->type != MONO_TYPE_SZARRAY)
3676                 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type for ldlen at 0x%04x", ctx->ip_offset));
3677
3678         stack_push_val (ctx, TYPE_NATIVE_INT, &mono_defaults.int_class->byval_arg);     
3679 }
3680
3681 /*FIXME handle arrays that are not 0-indexed*/
3682 /*FIXME handle readonly prefix and CMMP*/
3683 static void
3684 do_ldelema (VerifyContext *ctx, int klass_token)
3685 {
3686         ILStackDesc *index, *array, *res;
3687         MonoType *type = get_boxable_mono_type (ctx, klass_token, "ldelema");
3688         gboolean valid; 
3689
3690         if (!type)
3691                 return;
3692
3693         if (!check_underflow (ctx, 2))
3694                 return;
3695
3696         index = stack_pop (ctx);
3697         array = stack_pop (ctx);
3698
3699         if (stack_slot_get_type (index) != TYPE_I4 && stack_slot_get_type (index) != TYPE_NATIVE_INT)
3700                 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));
3701
3702         if (!stack_slot_is_null_literal (array)) {
3703                 if (stack_slot_get_type (array) != TYPE_COMPLEX || array->type->type != MONO_TYPE_SZARRAY)
3704                         CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type(%s) for ldelema at 0x%04x", stack_slot_get_name (array), ctx->ip_offset));
3705                 else {
3706                         if (get_stack_type (type) == TYPE_I4 || get_stack_type (type) == TYPE_NATIVE_INT) {
3707                                         valid = verify_type_compatibility_full (ctx, type, &array->type->data.klass->byval_arg, TRUE);
3708                         } else {
3709                                 valid = mono_metadata_type_equal (type, &array->type->data.klass->byval_arg);
3710                         }
3711                         if (!valid)
3712                                 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type on stack for ldelema at 0x%04x", ctx->ip_offset));
3713                 }
3714         }
3715
3716         res = stack_push (ctx);
3717         set_stack_value (ctx, res, type, TRUE);
3718         if (ctx->prefix_set & PREFIX_READONLY) {
3719                 ctx->prefix_set &= ~PREFIX_READONLY;
3720                 res->stype |= CMMP_MASK;
3721         }
3722 }
3723
3724 /*
3725  * FIXME handle arrays that are not 0-indexed
3726  * FIXME handle readonly prefix and CMMP
3727  */
3728 static void
3729 do_ldelem (VerifyContext *ctx, int opcode, int token)
3730 {
3731 #define IS_ONE_OF2(T, A, B) (T == A || T == B)
3732         ILStackDesc *index, *array;
3733         MonoType *type;
3734         if (!check_underflow (ctx, 2))
3735                 return;
3736
3737         if (opcode == CEE_LDELEM) {
3738                 if (!(type = verifier_load_type (ctx, token, "ldelem.any"))) {
3739                         ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Type (0x%08x) not found at 0x%04x", token, ctx->ip_offset));
3740                         return;
3741                 }
3742         } else {
3743                 type = mono_type_from_opcode (opcode);
3744         }
3745
3746         index = stack_pop (ctx);
3747         array = stack_pop (ctx);
3748
3749         if (stack_slot_get_type (index) != TYPE_I4 && stack_slot_get_type (index) != TYPE_NATIVE_INT)
3750                 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));
3751
3752         if (!stack_slot_is_null_literal (array)) {
3753                 if (stack_slot_get_type (array) != TYPE_COMPLEX || array->type->type != MONO_TYPE_SZARRAY)
3754                         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));
3755                 else {
3756                         if (opcode == CEE_LDELEM_REF) {
3757                                 if (array->type->data.klass->valuetype)
3758                                         CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type is not a reference type for ldelem.ref 0x%04x", ctx->ip_offset));
3759                                 type = &array->type->data.klass->byval_arg;
3760                         } else {
3761                                 MonoType *candidate = &array->type->data.klass->byval_arg;
3762                                 if (IS_STRICT_MODE (ctx)) {
3763                                         MonoType *underlying_type = mono_type_get_underlying_type_any (type);
3764                                         MonoType *underlying_candidate = mono_type_get_underlying_type_any (candidate);
3765                                         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)) ||
3766                                                 (IS_ONE_OF2 (underlying_candidate->type, MONO_TYPE_I4, MONO_TYPE_U4) && IS_ONE_OF2 (underlying_type->type, MONO_TYPE_I, MONO_TYPE_U)))
3767                                                 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type on stack for ldelem.X at 0x%04x", ctx->ip_offset));
3768                                 }
3769                                 if (!verify_type_compatibility_full (ctx, type, candidate, TRUE))
3770                                         CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type on stack for ldelem.X at 0x%04x", ctx->ip_offset));
3771                         }
3772                 }
3773         }
3774
3775         set_stack_value (ctx, stack_push (ctx), type, FALSE);
3776 #undef IS_ONE_OF2
3777 }
3778
3779 /*
3780  * FIXME handle arrays that are not 0-indexed
3781  */
3782 static void
3783 do_stelem (VerifyContext *ctx, int opcode, int token)
3784 {
3785         ILStackDesc *index, *array, *value;
3786         MonoType *type;
3787         if (!check_underflow (ctx, 3))
3788                 return;
3789
3790         if (opcode == CEE_STELEM) {
3791                 if (!(type = verifier_load_type (ctx, token, "stelem.any"))) {
3792                         ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Type (0x%08x) not found at 0x%04x", token, ctx->ip_offset));
3793                         return;
3794                 }
3795         } else {
3796                 type = mono_type_from_opcode (opcode);
3797         }
3798         
3799         value = stack_pop (ctx);
3800         index = stack_pop (ctx);
3801         array = stack_pop (ctx);
3802
3803         if (stack_slot_get_type (index) != TYPE_I4 && stack_slot_get_type (index) != TYPE_NATIVE_INT)
3804                 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));
3805
3806         if (!stack_slot_is_null_literal (array)) {
3807                 if (stack_slot_get_type (array) != TYPE_COMPLEX || array->type->type != MONO_TYPE_SZARRAY) {
3808                         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));
3809                 } else {
3810                         if (opcode == CEE_STELEM_REF) {
3811                                 if (array->type->data.klass->valuetype)
3812                                         CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type is not a reference type for stelem.ref 0x%04x", ctx->ip_offset));
3813                         } else if (!verify_type_compatibility_full (ctx, &array->type->data.klass->byval_arg, type, TRUE)) {
3814                                         CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type on stack for stdelem.X at 0x%04x", ctx->ip_offset));
3815                         }
3816                 }
3817         }
3818         if (opcode == CEE_STELEM_REF) {
3819                 if (!stack_slot_is_boxed_value (value) && mono_class_from_mono_type (value->type)->valuetype)
3820                         CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid value is not a reference type for stelem.ref 0x%04x", ctx->ip_offset));
3821         } else if (opcode != CEE_STELEM_REF) {
3822                 if (!verify_stack_type_compatibility (ctx, type, value))
3823                         CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid value on stack for stdelem.X at 0x%04x", ctx->ip_offset));
3824
3825                 if (stack_slot_is_boxed_value (value) && !MONO_TYPE_IS_REFERENCE (value->type) && !MONO_TYPE_IS_REFERENCE (type))
3826                         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));
3827
3828         }
3829 }
3830
3831 static void
3832 do_throw (VerifyContext *ctx)
3833 {
3834         ILStackDesc *exception;
3835         if (!check_underflow (ctx, 1))
3836                 return;
3837         exception = stack_pop (ctx);
3838
3839         if (!stack_slot_is_null_literal (exception) && !(stack_slot_get_type (exception) == TYPE_COMPLEX && !mono_class_from_mono_type (exception->type)->valuetype))
3840                 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid type on stack for throw, expected reference type at 0x%04x", ctx->ip_offset));
3841
3842         if (mono_type_is_generic_argument (exception->type) && !stack_slot_is_boxed_value (exception)) {
3843                 char *name = mono_type_full_name (exception->type);
3844                 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));
3845                 g_free (name);
3846         }
3847         /*The stack is left empty after a throw*/
3848         ctx->eval.size = 0;
3849 }
3850
3851
3852 static void
3853 do_endfilter (VerifyContext *ctx)
3854 {
3855         MonoExceptionClause *clause;
3856
3857         if (IS_STRICT_MODE (ctx)) {
3858                 if (ctx->eval.size != 1)
3859                         CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Stack size must have one item for endfilter at 0x%04x", ctx->ip_offset));
3860
3861                 if (ctx->eval.size >= 1 && stack_slot_get_type (stack_pop (ctx)) != TYPE_I4)
3862                         CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Stack item type is not an int32 for endfilter at 0x%04x", ctx->ip_offset));
3863         }
3864
3865         if ((clause = is_correct_endfilter (ctx, ctx->ip_offset))) {
3866                 if (IS_STRICT_MODE (ctx)) {
3867                         if (ctx->ip_offset != clause->handler_offset - 2)
3868                                 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("endfilter is not the last instruction of the filter clause at 0x%04x", ctx->ip_offset));                       
3869                 } else {
3870                         if ((ctx->ip_offset != clause->handler_offset - 2) && !MONO_OFFSET_IN_HANDLER (clause, ctx->ip_offset))
3871                                 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("endfilter is not the last instruction of the filter clause at 0x%04x", ctx->ip_offset));
3872                 }
3873         } else {
3874                 if (IS_STRICT_MODE (ctx) && !is_unverifiable_endfilter (ctx, ctx->ip_offset))
3875                         ADD_VERIFY_ERROR (ctx, g_strdup_printf ("endfilter outside filter clause at 0x%04x", ctx->ip_offset));
3876                 else
3877                         CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("endfilter outside filter clause at 0x%04x", ctx->ip_offset));
3878         }
3879
3880         ctx->eval.size = 0;
3881 }
3882
3883 static void
3884 do_leave (VerifyContext *ctx, int delta)
3885 {
3886         int target = ((gint32)ctx->ip_offset) + delta;
3887         if (target >= ctx->code_size || target < 0)
3888                 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Branch target out of code at 0x%04x", ctx->ip_offset));
3889
3890         if (!is_correct_leave (ctx->header, ctx->ip_offset, target))
3891                 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Leave not allowed in finally block at 0x%04x", ctx->ip_offset));
3892         ctx->eval.size = 0;
3893 }
3894
3895 /* 
3896  * do_static_branch:
3897  * 
3898  * Verify br and br.s opcodes.
3899  */
3900 static void
3901 do_static_branch (VerifyContext *ctx, int delta)
3902 {
3903         int target = ctx->ip_offset + delta;
3904         if (target < 0 || target >= ctx->code_size) {
3905                 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("branch target out of code at 0x%04x", ctx->ip_offset));
3906                 return;
3907         }
3908
3909         switch (is_valid_branch_instruction (ctx->header, ctx->ip_offset, target)) {
3910         case 1:
3911                 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Branch target escapes out of exception block at 0x%04x", ctx->ip_offset));
3912                 break;
3913         case 2:
3914                 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Branch target escapes out of exception block at 0x%04x", ctx->ip_offset));
3915                 break;
3916         }
3917
3918         ctx->target = target;
3919 }
3920
3921 static void
3922 do_switch (VerifyContext *ctx, int count, const unsigned char *data)
3923 {
3924         int i, base = ctx->ip_offset + 5 + count * 4;
3925         ILStackDesc *value;
3926
3927         if (!check_underflow (ctx, 1))
3928                 return;
3929
3930         value = stack_pop (ctx);
3931
3932         if (stack_slot_get_type (value) != TYPE_I4 && stack_slot_get_type (value) != TYPE_NATIVE_INT)
3933                 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid argument to switch at 0x%04x", ctx->ip_offset));
3934
3935         for (i = 0; i < count; ++i) {
3936                 int target = base + read32 (data + i * 4);
3937
3938                 if (target < 0 || target >= ctx->code_size) {
3939                         ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Switch target %x out of code at 0x%04x", i, ctx->ip_offset));
3940                         return;
3941                 }
3942
3943                 switch (is_valid_branch_instruction (ctx->header, ctx->ip_offset, target)) {
3944                 case 1:
3945                         CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Switch target %x escapes out of exception block at 0x%04x", i, ctx->ip_offset));
3946                         break;
3947                 case 2:
3948                         ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Switch target %x escapes out of exception block at 0x%04x", i, ctx->ip_offset));
3949                         return;
3950                 }
3951                 merge_stacks (ctx, &ctx->eval, &ctx->code [target], FALSE, TRUE);
3952         }
3953 }
3954
3955 static void
3956 do_load_function_ptr (VerifyContext *ctx, guint32 token, gboolean virtual)
3957 {
3958         ILStackDesc *top;
3959         MonoMethod *method;
3960
3961         if (virtual && !check_underflow (ctx, 1))
3962                 return;
3963
3964         if (!virtual && !check_overflow (ctx))
3965                 return;
3966
3967         if (!IS_METHOD_DEF_OR_REF_OR_SPEC (token) || !token_bounds_check (ctx->image, token)) {
3968                 ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid token %x for ldftn  at 0x%04x", token, ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE);
3969                 return;
3970         }
3971
3972         if (!(method = verifier_load_method (ctx, token, virtual ? "ldvirtfrn" : "ldftn")))
3973                 return;
3974
3975         if (mono_method_is_constructor (method))
3976                 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use ldftn with a constructor at 0x%04x", ctx->ip_offset));
3977
3978         if (virtual) {
3979                 ILStackDesc *top = stack_pop (ctx);
3980         
3981                 if (stack_slot_get_type (top) != TYPE_COMPLEX || top->type->type == MONO_TYPE_VALUETYPE)
3982                         CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid argument to ldvirtftn at 0x%04x", ctx->ip_offset));
3983         
3984                 if (method->flags & METHOD_ATTRIBUTE_STATIC)
3985                         CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use ldvirtftn with a constructor at 0x%04x", ctx->ip_offset));
3986
3987                 if (!verify_stack_type_compatibility (ctx, &method->klass->byval_arg, top))
3988                         CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Unexpected object for ldvirtftn at 0x%04x", ctx->ip_offset));
3989         }
3990         
3991         if (!mono_method_can_access_method_full (ctx->method, method, NULL))
3992                 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);
3993
3994         top = stack_push_val(ctx, TYPE_PTR, mono_type_create_fnptr_from_mono_method (ctx, method));
3995         top->method = method;
3996 }
3997
3998 static void
3999 do_sizeof (VerifyContext *ctx, int token)
4000 {
4001         MonoType *type;
4002
4003         if (!IS_TYPE_DEF_OR_REF_OR_SPEC (token) || !token_bounds_check (ctx->image, token)) {
4004                 ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid type token %x at 0x%04x", token, ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE);
4005                 return;
4006         }
4007         
4008         if (!(type = verifier_load_type (ctx, token, "sizeof")))
4009                 return;
4010
4011         if (type->byref && type->type != MONO_TYPE_TYPEDBYREF) {
4012                 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid use of byref type at 0x%04x", ctx->ip_offset));
4013                 return;
4014         }
4015
4016         if (type->type == MONO_TYPE_VOID) {
4017                 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid use of void type at 0x%04x", ctx->ip_offset));
4018                 return;
4019         }
4020
4021         if (check_overflow (ctx))
4022                 set_stack_value (ctx, stack_push (ctx), &mono_defaults.uint32_class->byval_arg, FALSE);
4023 }
4024
4025 /* Stack top can be of any type, the runtime doesn't care and treat everything as an int. */
4026 static void
4027 do_localloc (VerifyContext *ctx)
4028 {
4029         ILStackDesc *top;
4030         
4031         if (ctx->eval.size != 1) {
4032                 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Stack must have only size item in localloc at 0x%04x", ctx->ip_offset));
4033                 return;         
4034         }
4035
4036         if (in_any_exception_block (ctx->header, ctx->ip_offset)) {
4037                 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Stack must have only size item in localloc at 0x%04x", ctx->ip_offset));
4038                 return;
4039         }
4040
4041         /*TODO verify top type*/
4042         top = stack_pop (ctx);
4043
4044         set_stack_value (ctx, stack_push (ctx), &mono_defaults.int_class->byval_arg, FALSE);
4045         CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Instruction localloc in never verifiable at 0x%04x", ctx->ip_offset));
4046 }
4047
4048 static void
4049 do_ldstr (VerifyContext *ctx, guint32 token)
4050 {
4051         GSList *error = NULL;
4052         if (mono_metadata_token_code (token) != MONO_TOKEN_STRING) {
4053                 ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid string token %x at 0x%04x", token, ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE);
4054                 return;
4055         }
4056
4057         if (!ctx->image->dynamic && !mono_verifier_verify_string_signature (ctx->image, mono_metadata_token_index (token), &error)) {
4058                 if (error)
4059                         ctx->list = g_slist_concat (ctx->list, error);
4060                 ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid string index %x at 0x%04x", token, ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE);
4061                 return;
4062         }
4063
4064         if (check_overflow (ctx))
4065                 stack_push_val (ctx, TYPE_COMPLEX,  &mono_defaults.string_class->byval_arg);
4066 }
4067
4068 static void
4069 do_refanyval (VerifyContext *ctx, int token)
4070 {
4071         ILStackDesc *top;
4072         MonoType *type;
4073         if (!check_underflow (ctx, 1))
4074                 return;
4075
4076         if (!(type = get_boxable_mono_type (ctx, token, "refanyval")))
4077                 return;
4078
4079         top = stack_pop (ctx);
4080
4081         if (top->stype != TYPE_PTR || top->type->type != MONO_TYPE_TYPEDBYREF)
4082                 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));
4083
4084         set_stack_value (ctx, stack_push (ctx), type, TRUE);
4085 }
4086
4087 static void
4088 do_refanytype (VerifyContext *ctx)
4089 {
4090         ILStackDesc *top;
4091
4092         if (!check_underflow (ctx, 1))
4093                 return;
4094
4095         top = stack_pop (ctx);
4096
4097         if (top->stype != TYPE_PTR || top->type->type != MONO_TYPE_TYPEDBYREF)
4098                 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));
4099
4100         set_stack_value (ctx, stack_push (ctx), &mono_defaults.typehandle_class->byval_arg, FALSE);
4101
4102 }
4103
4104 static void
4105 do_mkrefany (VerifyContext *ctx, int token)
4106 {
4107         ILStackDesc *top;
4108         MonoType *type;
4109         if (!check_underflow (ctx, 1))
4110                 return;
4111
4112         if (!(type = get_boxable_mono_type (ctx, token, "refanyval")))
4113                 return;
4114
4115         top = stack_pop (ctx);
4116
4117         if (stack_slot_is_managed_mutability_pointer (top))
4118                 CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use a readonly pointer with mkrefany at 0x%04x", ctx->ip_offset));
4119
4120         if (!stack_slot_is_managed_pointer (top)) {
4121                 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));
4122         }else {
4123                 MonoType *stack_type = mono_type_get_type_byval (top->type);
4124                 if (MONO_TYPE_IS_REFERENCE (type) && !mono_metadata_type_equal (type, stack_type))
4125                         CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Type not compatible for mkrefany at 0x%04x", ctx->ip_offset));
4126                         
4127                 if (!MONO_TYPE_IS_REFERENCE (type) && !verify_type_compatibility_full (ctx, type, stack_type, TRUE))
4128                         CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Type not compatible for mkrefany at 0x%04x", ctx->ip_offset));
4129         }
4130
4131         set_stack_value (ctx, stack_push (ctx), &mono_defaults.typed_reference_class->byval_arg, FALSE);
4132 }
4133
4134 static void
4135 do_ckfinite (VerifyContext *ctx)
4136 {
4137         ILStackDesc *top;
4138         if (!check_underflow (ctx, 1))
4139                 return;
4140
4141         top = stack_pop (ctx);
4142
4143         if (stack_slot_get_underlying_type (top) != TYPE_R8)
4144                 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)); 
4145         stack_push_stack_val (ctx, top);
4146 }
4147 /*
4148  * merge_stacks:
4149  * Merge the stacks and perform compat checks. The merge check if types of @from are mergeable with type of @to 
4150  * 
4151  * @from holds new values for a given control path
4152  * @to holds the current values of a given control path
4153  * 
4154  * TODO we can eliminate the from argument as all callers pass &ctx->eval
4155  */
4156 static void
4157 merge_stacks (VerifyContext *ctx, ILCodeDesc *from, ILCodeDesc *to, gboolean start, gboolean external) 
4158 {
4159         MonoError error;
4160         int i, j, k;
4161         stack_init (ctx, to);
4162
4163         if (start) {
4164                 if (to->flags == IL_CODE_FLAG_NOT_PROCESSED) 
4165                         from->size = 0;
4166                 else
4167                         stack_copy (&ctx->eval, to);
4168                 goto end_verify;
4169         } else if (!(to->flags & IL_CODE_STACK_MERGED)) {
4170                 stack_copy (to, &ctx->eval);
4171                 goto end_verify;
4172         }
4173         VERIFIER_DEBUG ( printf ("performing stack merge %d x %d\n", from->size, to->size); );
4174
4175         if (from->size != to->size) {
4176                 VERIFIER_DEBUG ( printf ("different stack sizes %d x %d at 0x%04x\n", from->size, to->size, ctx->ip_offset); );
4177                 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)); 
4178                 goto end_verify;
4179         }
4180
4181         //FIXME we need to preserve CMMP attributes
4182         //FIXME we must take null literals into consideration.
4183         for (i = 0; i < from->size; ++i) {
4184                 ILStackDesc *new_slot = from->stack + i;
4185                 ILStackDesc *old_slot = to->stack + i;
4186                 MonoType *new_type = mono_type_from_stack_slot (new_slot);
4187                 MonoType *old_type = mono_type_from_stack_slot (old_slot);
4188                 MonoClass *old_class = mono_class_from_mono_type (old_type);
4189                 MonoClass *new_class = mono_class_from_mono_type (new_type);
4190                 MonoClass *match_class = NULL;
4191
4192                 // S := T then U = S (new value is compatible with current value, keep current)
4193                 if (verify_stack_type_compatibility (ctx, old_type, new_slot)) {
4194                         copy_stack_value (new_slot, old_slot);
4195                         continue;
4196                 }
4197
4198                 // T := S then U = T (old value is compatible with current value, use new)
4199                 if (verify_stack_type_compatibility (ctx, new_type, old_slot)) {
4200                         copy_stack_value (old_slot, new_slot);
4201                         continue;
4202                 }
4203
4204                 if (mono_type_is_generic_argument (old_type) || mono_type_is_generic_argument (new_type)) {
4205                         char *old_name = stack_slot_full_name (old_slot); 
4206                         char *new_name = stack_slot_full_name (new_slot);
4207                         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));
4208                         g_free (old_name);
4209                         g_free (new_name);
4210                         goto end_verify;                        
4211                 } 
4212
4213                 //both are reference types, use closest common super type
4214                 if (!mono_class_from_mono_type (old_type)->valuetype 
4215                         && !mono_class_from_mono_type (new_type)->valuetype
4216                         && !stack_slot_is_managed_pointer (old_slot)
4217                         && !stack_slot_is_managed_pointer (new_slot)) {
4218                         
4219                         for (j = MIN (old_class->idepth, new_class->idepth) - 1; j > 0; --j) {
4220                                 if (mono_metadata_type_equal (&old_class->supertypes [j]->byval_arg, &new_class->supertypes [j]->byval_arg)) {
4221                                         match_class = old_class->supertypes [j];
4222                                         goto match_found;
4223                                 }
4224                         }
4225
4226                         mono_class_setup_interfaces (old_class, &error);
4227                         if (!mono_error_ok (&error)) {
4228                                 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));
4229                                 mono_error_cleanup (&error);
4230                                 goto end_verify;
4231                         }
4232                         for (j = 0; j < old_class->interface_count; ++j) {
4233                                 for (k = 0; k < new_class->interface_count; ++k) {
4234                                         if (mono_metadata_type_equal (&old_class->interfaces [j]->byval_arg, &new_class->interfaces [k]->byval_arg)) {
4235                                                 match_class = old_class->interfaces [j];
4236                                                 goto match_found;
4237                                         }
4238                                 }
4239                         }
4240
4241                         //No decent super type found, use object
4242                         match_class = mono_defaults.object_class;
4243                         goto match_found;
4244                 } 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)) {
4245                         match_class = mono_defaults.object_class;
4246                         goto match_found;
4247                 }
4248
4249                 {
4250                 char *old_name = stack_slot_full_name (old_slot); 
4251                 char *new_name = stack_slot_full_name (new_slot);
4252                 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)); 
4253                 g_free (old_name);
4254                 g_free (new_name);
4255                 }
4256                 set_stack_value (ctx, old_slot, &new_class->byval_arg, stack_slot_is_managed_pointer (old_slot));
4257                 goto end_verify;
4258
4259 match_found:
4260                 g_assert (match_class);
4261                 set_stack_value (ctx, old_slot, &match_class->byval_arg, stack_slot_is_managed_pointer (old_slot));
4262                 set_stack_value (ctx, new_slot, &match_class->byval_arg, stack_slot_is_managed_pointer (old_slot));
4263                 continue;
4264         }
4265
4266 end_verify:
4267         if (external)
4268                 to->flags |= IL_CODE_FLAG_WAS_TARGET;
4269         to->flags |= IL_CODE_STACK_MERGED;
4270 }
4271
4272 #define HANDLER_START(clause) ((clause)->flags == MONO_EXCEPTION_CLAUSE_FILTER ? (clause)->data.filter_offset : clause->handler_offset)
4273 #define IS_CATCH_OR_FILTER(clause) ((clause)->flags == MONO_EXCEPTION_CLAUSE_FILTER || (clause)->flags == MONO_EXCEPTION_CLAUSE_NONE)
4274
4275 /*
4276  * is_clause_in_range :
4277  * 
4278  * Returns TRUE if either the protected block or the handler of @clause is in the @start - @end range.  
4279  */
4280 static gboolean
4281 is_clause_in_range (MonoExceptionClause *clause, guint32 start, guint32 end)
4282 {
4283         if (clause->try_offset >= start && clause->try_offset < end)
4284                 return TRUE;
4285         if (HANDLER_START (clause) >= start && HANDLER_START (clause) < end)
4286                 return TRUE;
4287         return FALSE;
4288 }
4289
4290 /*
4291  * is_clause_inside_range :
4292  * 
4293  * Returns TRUE if @clause lies completely inside the @start - @end range.  
4294  */
4295 static gboolean
4296 is_clause_inside_range (MonoExceptionClause *clause, guint32 start, guint32 end)
4297 {
4298         if (clause->try_offset < start || (clause->try_offset + clause->try_len) > end)
4299                 return FALSE;
4300         if (HANDLER_START (clause) < start || (clause->handler_offset + clause->handler_len) > end)
4301                 return FALSE;
4302         return TRUE;
4303 }
4304
4305 /*
4306  * is_clause_nested :
4307  * 
4308  * Returns TRUE if @nested is nested in @clause.   
4309  */
4310 static gboolean
4311 is_clause_nested (MonoExceptionClause *clause, MonoExceptionClause *nested)
4312 {
4313         if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER && is_clause_inside_range (nested, clause->data.filter_offset, clause->handler_offset))
4314                 return TRUE;
4315         return is_clause_inside_range (nested, clause->try_offset, clause->try_offset + clause->try_len) ||
4316         is_clause_inside_range (nested, clause->handler_offset, clause->handler_offset + clause->handler_len);
4317 }
4318
4319 /* Test the relationship between 2 exception clauses. Follow  P.1 12.4.2.7 of ECMA
4320  * the each pair of exception must have the following properties:
4321  *  - one is fully nested on another (the outer must not be a filter clause) (the nested one must come earlier)
4322  *  - completely disjoin (none of the 3 regions of each entry overlap with the other 3)
4323  *  - mutual protection (protected block is EXACT the same, handlers are disjoin and all handler are catch or all handler are filter)
4324  */
4325 static void
4326 verify_clause_relationship (VerifyContext *ctx, MonoExceptionClause *clause, MonoExceptionClause *to_test)
4327 {
4328         /*clause is nested*/
4329         if (to_test->flags == MONO_EXCEPTION_CLAUSE_FILTER && is_clause_inside_range (clause, to_test->data.filter_offset, to_test->handler_offset)) {
4330                 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Exception clause inside filter"));
4331                 return;
4332         }
4333
4334         /*wrong nesting order.*/
4335         if (is_clause_nested (clause, to_test)) {
4336                 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Nested exception clause appears after enclosing clause"));
4337                 return;
4338         }
4339
4340         /*mutual protection*/
4341         if (clause->try_offset == to_test->try_offset && clause->try_len == to_test->try_len) {
4342                 /*handlers are not disjoint*/
4343                 if (is_clause_in_range (to_test, HANDLER_START (clause), clause->handler_offset + clause->handler_len)) {
4344                         ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Exception handlers overlap"));
4345                         return;
4346                 }
4347                 /* handlers are not catch or filter */
4348                 if (!IS_CATCH_OR_FILTER (clause) || !IS_CATCH_OR_FILTER (to_test)) {
4349                         ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Exception clauses with shared protected block are neither catch or filter"));
4350                         return;
4351                 }
4352                 /*OK*/
4353                 return;
4354         }
4355
4356         /*not completelly disjoint*/
4357         if ((is_clause_in_range (to_test, clause->try_offset, clause->try_offset + clause->try_len) ||
4358                 is_clause_in_range (to_test, HANDLER_START (clause), clause->handler_offset + clause->handler_len)) && !is_clause_nested (to_test, clause))
4359                 ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Exception clauses overlap"));
4360 }
4361
4362 #define code_bounds_check(size) \
4363         if (ADDP_IS_GREATER_OR_OVF (ip, size, end)) {\
4364                 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Code overrun starting with 0x%x at 0x%04x", *ip, ctx.ip_offset)); \
4365                 break; \
4366         } \
4367
4368 static gboolean
4369 mono_opcode_is_prefix (int op)
4370 {
4371         switch (op) {
4372         case MONO_CEE_UNALIGNED_:
4373         case MONO_CEE_VOLATILE_:
4374         case MONO_CEE_TAIL_:
4375         case MONO_CEE_CONSTRAINED_:
4376         case MONO_CEE_READONLY_:
4377                 return TRUE;
4378         }
4379         return FALSE;
4380 }
4381
4382 /*
4383  * FIXME: need to distinguish between valid and verifiable.
4384  * Need to keep track of types on the stack.
4385  * Verify types for opcodes.
4386  */
4387 GSList*
4388 mono_method_verify (MonoMethod *method, int level)
4389 {
4390         MonoError error;
4391         const unsigned char *ip, *code_start;
4392         const unsigned char *end;
4393         MonoSimpleBasicBlock *bb = NULL, *original_bb = NULL;
4394
4395         int i, n, need_merge = 0, start = 0;
4396         guint token, ip_offset = 0, prefix = 0;
4397         MonoGenericContext *generic_context = NULL;
4398         MonoImage *image;
4399         VerifyContext ctx;
4400         GSList *tmp;
4401         VERIFIER_DEBUG ( printf ("Verify IL for method %s %s %s\n",  method->klass->name_space,  method->klass->name, method->name); );
4402
4403         init_verifier_stats ();
4404
4405         if (method->iflags & (METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL | METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
4406                         (method->flags & (METHOD_ATTRIBUTE_PINVOKE_IMPL | METHOD_ATTRIBUTE_ABSTRACT))) {
4407                 return NULL;
4408         }
4409
4410         memset (&ctx, 0, sizeof (VerifyContext));
4411
4412         //FIXME use mono_method_get_signature_full
4413         ctx.signature = mono_method_signature (method);
4414         if (!ctx.signature) {
4415                 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Could not decode method signature"));
4416
4417                 finish_collect_stats ();
4418                 return ctx.list;
4419         }
4420         ctx.header = mono_method_get_header (method);
4421         if (!ctx.header) {
4422                 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Could not decode method header"));
4423                 finish_collect_stats ();
4424                 return ctx.list;
4425         }
4426         ctx.method = method;
4427         code_start = ip = ctx.header->code;
4428         end = ip + ctx.header->code_size;
4429         ctx.image = image = method->klass->image;
4430
4431
4432         ctx.max_args = ctx.signature->param_count + ctx.signature->hasthis;
4433         ctx.max_stack = ctx.header->max_stack;
4434         ctx.verifiable = ctx.valid = 1;
4435         ctx.level = level;
4436
4437         ctx.code = g_new (ILCodeDesc, ctx.header->code_size);
4438         ctx.code_size = ctx.header->code_size;
4439         MEM_ALLOC (sizeof (ILCodeDesc) * ctx.header->code_size);
4440
4441         memset(ctx.code, 0, sizeof (ILCodeDesc) * ctx.header->code_size);
4442
4443         ctx.num_locals = ctx.header->num_locals;
4444         ctx.locals = g_memdup (ctx.header->locals, sizeof (MonoType*) * ctx.header->num_locals);
4445         MEM_ALLOC (sizeof (MonoType*) * ctx.header->num_locals);
4446
4447         if (ctx.num_locals > 0 && !ctx.header->init_locals)
4448                 CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Method with locals variable but without init locals set"));
4449
4450         ctx.params = g_new (MonoType*, ctx.max_args);
4451         MEM_ALLOC (sizeof (MonoType*) * ctx.max_args);
4452
4453         if (ctx.signature->hasthis)
4454                 ctx.params [0] = method->klass->valuetype ? &method->klass->this_arg : &method->klass->byval_arg;
4455         memcpy (ctx.params + ctx.signature->hasthis, ctx.signature->params, sizeof (MonoType *) * ctx.signature->param_count);
4456
4457         if (ctx.signature->is_inflated)
4458                 ctx.generic_context = generic_context = mono_method_get_context (method);
4459
4460         if (!generic_context && (method->klass->generic_container || method->is_generic)) {
4461                 if (method->is_generic)
4462                         ctx.generic_context = generic_context = &(mono_method_get_generic_container (method)->context);
4463                 else
4464                         ctx.generic_context = generic_context = &method->klass->generic_container->context;
4465         }
4466
4467         for (i = 0; i < ctx.num_locals; ++i) {
4468                 MonoType *uninflated = ctx.locals [i];
4469                 ctx.locals [i] = mono_class_inflate_generic_type_checked (ctx.locals [i], ctx.generic_context, &error);
4470                 if (!mono_error_ok (&error)) {
4471                         char *name = mono_type_full_name (ctx.locals [i] ? ctx.locals [i] : uninflated);
4472                         ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid local %d of type %s", i, name));
4473                         g_free (name);
4474                         mono_error_cleanup (&error);
4475                         /* we must not free (in cleanup) what was not yet allocated (but only copied) */
4476                         ctx.num_locals = i;
4477                         ctx.max_args = 0;
4478                         goto cleanup;
4479                 }
4480         }
4481         for (i = 0; i < ctx.max_args; ++i) {
4482                 MonoType *uninflated = ctx.params [i];
4483                 ctx.params [i] = mono_class_inflate_generic_type_checked (ctx.params [i], ctx.generic_context, &error);
4484                 if (!mono_error_ok (&error)) {
4485                         char *name = mono_type_full_name (ctx.params [i] ? ctx.params [i] : uninflated);
4486                         ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid parameter %d of type %s", i, name));
4487                         g_free (name);
4488                         mono_error_cleanup (&error);
4489                         /* we must not free (in cleanup) what was not yet allocated (but only copied) */
4490                         ctx.max_args = i;
4491                         goto cleanup;
4492                 }
4493         }
4494         stack_init (&ctx, &ctx.eval);
4495
4496         for (i = 0; i < ctx.num_locals; ++i) {
4497                 if (!mono_type_is_valid_in_context (&ctx, ctx.locals [i]))
4498                         break;
4499                 if (get_stack_type (ctx.locals [i]) == TYPE_INV) {
4500                         char *name = mono_type_full_name (ctx.locals [i]);
4501                         ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid local %i of type %s", i, name));
4502                         g_free (name);
4503                         break;
4504                 }
4505                 
4506         }
4507
4508         for (i = 0; i < ctx.max_args; ++i) {
4509                 if (!mono_type_is_valid_in_context (&ctx, ctx.params [i]))
4510                         break;
4511
4512                 if (get_stack_type (ctx.params [i]) == TYPE_INV) {
4513                         char *name = mono_type_full_name (ctx.params [i]);
4514                         ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid parameter %i of type %s", i, name));
4515                         g_free (name);
4516                         break;
4517                 }
4518         }
4519
4520         if (!ctx.valid)
4521                 goto cleanup;
4522
4523         for (i = 0; i < ctx.header->num_clauses && ctx.valid; ++i) {
4524                 MonoExceptionClause *clause = ctx.header->clauses + i;
4525                 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); );
4526
4527                 if (clause->try_offset > ctx.code_size || ADD_IS_GREATER_OR_OVF (clause->try_offset, clause->try_len, ctx.code_size))
4528                         ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("try clause out of bounds at 0x%04x", clause->try_offset));
4529
4530                 if (clause->try_len <= 0)
4531                         ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("try clause len <= 0 at 0x%04x", clause->try_offset));
4532
4533                 if (clause->handler_offset > ctx.code_size || ADD_IS_GREATER_OR_OVF (clause->handler_offset, clause->handler_len, ctx.code_size))
4534                         ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("handler clause out of bounds at 0x%04x", clause->try_offset));
4535
4536                 if (clause->handler_len <= 0)
4537                         ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("handler clause len <= 0 at 0x%04x", clause->try_offset));
4538
4539                 if (clause->try_offset < clause->handler_offset && ADD_IS_GREATER_OR_OVF (clause->try_offset, clause->try_len, HANDLER_START (clause)))
4540                         ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("try block (at 0x%04x) includes handler block (at 0x%04x)", clause->try_offset, clause->handler_offset));
4541
4542                 if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
4543                         if (clause->data.filter_offset > ctx.code_size)
4544                                 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("filter clause out of bounds at 0x%04x", clause->try_offset));
4545
4546                         if (clause->data.filter_offset >= clause->handler_offset)
4547                                 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("filter clause must come before the handler clause at 0x%04x", clause->data.filter_offset));
4548                 }
4549
4550                 for (n = i + 1; n < ctx.header->num_clauses && ctx.valid; ++n)
4551                         verify_clause_relationship (&ctx, clause, ctx.header->clauses + n);
4552
4553                 if (!ctx.valid)
4554                         break;
4555
4556                 ctx.code [clause->try_offset].flags |= IL_CODE_FLAG_WAS_TARGET;
4557                 if (clause->try_offset + clause->try_len < ctx.code_size)
4558                         ctx.code [clause->try_offset + clause->try_len].flags |= IL_CODE_FLAG_WAS_TARGET;
4559                 if (clause->handler_offset + clause->handler_len < ctx.code_size)
4560                         ctx.code [clause->handler_offset + clause->handler_len].flags |= IL_CODE_FLAG_WAS_TARGET;
4561
4562                 if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE) {
4563                         if (!clause->data.catch_class) {
4564                                 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Catch clause %d with invalid type", i));
4565                                 break;
4566                         }
4567                 
4568                         init_stack_with_value_at_exception_boundary (&ctx, ctx.code + clause->handler_offset, clause->data.catch_class);
4569                 }
4570                 else if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
4571                         init_stack_with_value_at_exception_boundary (&ctx, ctx.code + clause->data.filter_offset, mono_defaults.exception_class);
4572                         init_stack_with_value_at_exception_boundary (&ctx, ctx.code + clause->handler_offset, mono_defaults.exception_class);   
4573                 }
4574         }
4575
4576         original_bb = bb = mono_basic_block_split (method, &error);
4577         if (!mono_error_ok (&error)) {
4578                 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid branch target: %s", mono_error_get_message (&error)));
4579                 mono_error_cleanup (&error);
4580                 goto cleanup;
4581         }
4582         g_assert (bb);
4583
4584         while (ip < end && ctx.valid) {
4585                 ip_offset = ip - code_start;
4586                 {
4587                         const unsigned char *ip_copy = ip;
4588                         int size, op;
4589
4590                         if (ip_offset > bb->end) {
4591                                 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Branch or EH block at [0x%04x] targets middle instruction at 0x%04x", bb->end, ip_offset));
4592                                 goto cleanup;
4593                         }
4594
4595                         if (ip_offset == bb->end)
4596                                 bb = bb->next;
4597         
4598                         size = mono_opcode_value_and_size (&ip_copy, end, &op);
4599                         if (size == -1) {
4600                                 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid instruction %x at 0x%04x", *ip, ip_offset));
4601                                 goto cleanup;
4602                         }
4603
4604                         if (ADD_IS_GREATER_OR_OVF (ip_offset, size, bb->end)) {
4605                                 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Branch or EH block targets middle of instruction at 0x%04x", ip_offset));
4606                                 goto cleanup;
4607                         }
4608
4609                         /*Last Instruction*/
4610                         if (ip_offset + size == bb->end && mono_opcode_is_prefix (op)) {
4611                                 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));
4612                                 goto cleanup;
4613                         }
4614
4615                         if (bb->dead) {
4616                                 /*FIXME remove this once we move all bad branch checking code to use BB only*/
4617                                 ctx.code [ip_offset].flags |= IL_CODE_FLAG_SEEN;
4618                                 ip += size;
4619                                 continue;
4620                         }
4621                 }
4622
4623                 ctx.ip_offset = ip_offset = ip - code_start;
4624
4625                 /*We need to check against fallthrou in and out of protected blocks.
4626                  * For fallout we check the once a protected block ends, if the start flag is not set.
4627                  * Likewise for fallthru in, we check if ip is the start of a protected block and start is not set
4628                  * TODO convert these checks to be done using flags and not this loop
4629                  */
4630                 for (i = 0; i < ctx.header->num_clauses && ctx.valid; ++i) {
4631                         MonoExceptionClause *clause = ctx.header->clauses + i;
4632
4633                         if ((clause->try_offset + clause->try_len == ip_offset) && start == 0) {
4634                                 CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("fallthru off try block at 0x%04x", ip_offset));
4635                                 start = 1;
4636                         }
4637
4638                         if ((clause->handler_offset + clause->handler_len == ip_offset) && start == 0) {
4639                                 if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER)
4640                                         ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("fallout of handler block at 0x%04x", ip_offset));
4641                                 else
4642                                         CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("fallout of handler block at 0x%04x", ip_offset));
4643                                 start = 1;
4644                         }
4645
4646                         if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER && clause->handler_offset == ip_offset && start == 0) {
4647                                 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("fallout of filter block at 0x%04x", ip_offset));
4648                                 start = 1;
4649                         }
4650
4651                         if (clause->handler_offset == ip_offset && start == 0) {
4652                                 CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("fallthru handler block at 0x%04x", ip_offset));
4653                                 start = 1;
4654                         }
4655
4656                         if (clause->try_offset == ip_offset && ctx.eval.size > 0 && start == 0) {
4657                                 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Try to enter try block with a non-empty stack at 0x%04x", ip_offset));
4658                                 start = 1;
4659                         }
4660                 }
4661
4662                 if (!ctx.valid)
4663                         break;
4664
4665                 if (need_merge) {
4666                         VERIFIER_DEBUG ( printf ("extra merge needed! 0x%04x \n", ctx.target); );
4667                         merge_stacks (&ctx, &ctx.eval, &ctx.code [ctx.target], FALSE, TRUE);
4668                         need_merge = 0; 
4669                 }
4670                 merge_stacks (&ctx, &ctx.eval, &ctx.code[ip_offset], start, FALSE);
4671                 start = 0;
4672
4673                 /*TODO we can fast detect a forward branch or exception block targeting code after prefix, we should fail fast*/
4674 #ifdef MONO_VERIFIER_DEBUG
4675                 {
4676                         char *discode;
4677                         discode = mono_disasm_code_one (NULL, method, ip, NULL);
4678                         discode [strlen (discode) - 1] = 0; /* no \n */
4679                         g_print ("[%d] %-29s (%d)\n",  ip_offset, discode, ctx.eval.size);
4680                         g_free (discode);
4681                 }
4682                 dump_stack_state (&ctx.code [ip_offset]);
4683                 dump_stack_state (&ctx.eval);
4684 #endif
4685
4686                 switch (*ip) {
4687                 case CEE_NOP:
4688                 case CEE_BREAK:
4689                         ++ip;
4690                         break;
4691
4692                 case CEE_LDARG_0:
4693                 case CEE_LDARG_1:
4694                 case CEE_LDARG_2:
4695                 case CEE_LDARG_3:
4696                         push_arg (&ctx, *ip - CEE_LDARG_0, FALSE);
4697                         ++ip;
4698                         break;
4699
4700                 case CEE_LDARG_S:
4701                 case CEE_LDARGA_S:
4702                         code_bounds_check (2);
4703                         push_arg (&ctx, ip [1],  *ip == CEE_LDARGA_S);
4704                         ip += 2;
4705                         break;
4706
4707                 case CEE_ADD_OVF_UN:
4708                         do_binop (&ctx, *ip, add_ovf_un_table);
4709                         ++ip;
4710                         break;
4711
4712                 case CEE_SUB_OVF_UN:
4713                         do_binop (&ctx, *ip, sub_ovf_un_table);
4714                         ++ip;
4715                         break;
4716
4717                 case CEE_ADD_OVF:
4718                 case CEE_SUB_OVF:
4719                 case CEE_MUL_OVF:
4720                 case CEE_MUL_OVF_UN:
4721                         do_binop (&ctx, *ip, bin_ovf_table);
4722                         ++ip;
4723                         break;
4724
4725                 case CEE_ADD:
4726                         do_binop (&ctx, *ip, add_table);
4727                         ++ip;
4728                         break;
4729
4730                 case CEE_SUB:
4731                         do_binop (&ctx, *ip, sub_table);
4732                         ++ip;
4733                         break;
4734
4735                 case CEE_MUL:
4736                 case CEE_DIV:
4737                 case CEE_REM:
4738                         do_binop (&ctx, *ip, bin_op_table);
4739                         ++ip;
4740                         break;
4741
4742                 case CEE_AND:
4743                 case CEE_DIV_UN:
4744                 case CEE_OR:
4745                 case CEE_REM_UN:
4746                 case CEE_XOR:
4747                         do_binop (&ctx, *ip, int_bin_op_table);
4748                         ++ip;
4749                         break;
4750
4751                 case CEE_SHL:
4752                 case CEE_SHR:
4753                 case CEE_SHR_UN:
4754                         do_binop (&ctx, *ip, shift_op_table);
4755                         ++ip;
4756                         break;
4757
4758                 case CEE_POP:
4759                         if (!check_underflow (&ctx, 1))
4760                                 break;
4761                         stack_pop_safe (&ctx);
4762                         ++ip;
4763                         break;
4764
4765                 case CEE_RET:
4766                         do_ret (&ctx);
4767                         ++ip;
4768                         start = 1;
4769                         break;
4770
4771                 case CEE_LDLOC_0:
4772                 case CEE_LDLOC_1:
4773                 case CEE_LDLOC_2:
4774                 case CEE_LDLOC_3:
4775                         /*TODO support definite assignment verification? */
4776                         push_local (&ctx, *ip - CEE_LDLOC_0, FALSE);
4777                         ++ip;
4778                         break;
4779
4780                 case CEE_STLOC_0:
4781                 case CEE_STLOC_1:
4782                 case CEE_STLOC_2:
4783                 case CEE_STLOC_3:
4784                         store_local (&ctx, *ip - CEE_STLOC_0);
4785                         ++ip;
4786                         break;
4787
4788                 case CEE_STLOC_S:
4789                         code_bounds_check (2);
4790                         store_local (&ctx, ip [1]);
4791                         ip += 2;
4792                         break;
4793
4794                 case CEE_STARG_S:
4795                         code_bounds_check (2);
4796                         store_arg (&ctx, ip [1]);
4797                         ip += 2;
4798                         break;
4799
4800                 case CEE_LDC_I4_M1:
4801                 case CEE_LDC_I4_0:
4802                 case CEE_LDC_I4_1:
4803                 case CEE_LDC_I4_2:
4804                 case CEE_LDC_I4_3:
4805                 case CEE_LDC_I4_4:
4806                 case CEE_LDC_I4_5:
4807                 case CEE_LDC_I4_6:
4808                 case CEE_LDC_I4_7:
4809                 case CEE_LDC_I4_8:
4810                         if (check_overflow (&ctx))
4811                                 stack_push_val (&ctx, TYPE_I4, &mono_defaults.int32_class->byval_arg);
4812                         ++ip;
4813                         break;
4814
4815                 case CEE_LDC_I4_S:
4816                         code_bounds_check (2);
4817                         if (check_overflow (&ctx))
4818                                 stack_push_val (&ctx, TYPE_I4, &mono_defaults.int32_class->byval_arg);
4819                         ip += 2;
4820                         break;
4821
4822                 case CEE_LDC_I4:
4823                         code_bounds_check (5);
4824                         if (check_overflow (&ctx))
4825                                 stack_push_val (&ctx,TYPE_I4, &mono_defaults.int32_class->byval_arg);
4826                         ip += 5;
4827                         break;
4828
4829                 case CEE_LDC_I8:
4830                         code_bounds_check (9);
4831                         if (check_overflow (&ctx))
4832                                 stack_push_val (&ctx,TYPE_I8, &mono_defaults.int64_class->byval_arg);
4833                         ip += 9;
4834                         break;
4835
4836                 case CEE_LDC_R4:
4837                         code_bounds_check (5);
4838                         if (check_overflow (&ctx))
4839                                 stack_push_val (&ctx, TYPE_R8, &mono_defaults.double_class->byval_arg);
4840                         ip += 5;
4841                         break;
4842
4843                 case CEE_LDC_R8:
4844                         code_bounds_check (9);
4845                         if (check_overflow (&ctx))
4846                                 stack_push_val (&ctx, TYPE_R8, &mono_defaults.double_class->byval_arg);
4847                         ip += 9;
4848                         break;
4849
4850                 case CEE_LDNULL:
4851                         if (check_overflow (&ctx))
4852                                 stack_push_val (&ctx, TYPE_COMPLEX | NULL_LITERAL_MASK, &mono_defaults.object_class->byval_arg);
4853                         ++ip;
4854                         break;
4855
4856                 case CEE_BEQ_S:
4857                 case CEE_BNE_UN_S:
4858                         code_bounds_check (2);
4859                         do_branch_op (&ctx, (signed char)ip [1] + 2, cmp_br_eq_op);
4860                         ip += 2;
4861                         need_merge = 1;
4862                         break;
4863
4864                 case CEE_BGE_S:
4865                 case CEE_BGT_S:
4866                 case CEE_BLE_S:
4867                 case CEE_BLT_S:
4868                 case CEE_BGE_UN_S:
4869                 case CEE_BGT_UN_S:
4870                 case CEE_BLE_UN_S:
4871                 case CEE_BLT_UN_S:
4872                         code_bounds_check (2);
4873                         do_branch_op (&ctx, (signed char)ip [1] + 2, cmp_br_op);
4874                         ip += 2;
4875                         need_merge = 1;
4876                         break;
4877
4878                 case CEE_BEQ:
4879                 case CEE_BNE_UN:
4880                         code_bounds_check (5);
4881                         do_branch_op (&ctx, (gint32)read32 (ip + 1) + 5, cmp_br_eq_op);
4882                         ip += 5;
4883                         need_merge = 1;
4884                         break;
4885
4886                 case CEE_BGE:
4887                 case CEE_BGT:
4888                 case CEE_BLE:
4889                 case CEE_BLT:
4890                 case CEE_BGE_UN:
4891                 case CEE_BGT_UN:
4892                 case CEE_BLE_UN:
4893                 case CEE_BLT_UN:
4894                         code_bounds_check (5);
4895                         do_branch_op (&ctx, (gint32)read32 (ip + 1) + 5, cmp_br_op);
4896                         ip += 5;
4897                         need_merge = 1;
4898                         break;
4899
4900                 case CEE_LDLOC_S:
4901                 case CEE_LDLOCA_S:
4902                         code_bounds_check (2);
4903                         push_local (&ctx, ip[1], *ip == CEE_LDLOCA_S);
4904                         ip += 2;
4905                         break;
4906
4907                 case CEE_UNUSED99:
4908                         ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Use of the `unused' opcode"));
4909                         ++ip;
4910                         break; 
4911
4912                 case CEE_DUP: {
4913                         ILStackDesc *top;
4914                         if (!check_underflow (&ctx, 1))
4915                                 break;
4916                         if (!check_overflow (&ctx))
4917                                 break;
4918                         top = stack_push (&ctx);
4919                         copy_stack_value (top, stack_peek (&ctx, 1));
4920                         ++ip;
4921                         break;
4922                 }
4923
4924                 case CEE_JMP:
4925                         code_bounds_check (5);
4926                         if (ctx.eval.size)
4927                                 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Eval stack must be empty in jmp at 0x%04x", ip_offset));
4928                         token = read32 (ip + 1);
4929                         if (in_any_block (ctx.header, ip_offset))
4930                                 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("jmp cannot escape exception blocks at 0x%04x", ip_offset));
4931
4932                         CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Intruction jmp is not verifiable at 0x%04x", ctx.ip_offset));
4933                         /*
4934                          * FIXME: check signature, retval, arguments etc.
4935                          */
4936                         ip += 5;
4937                         break;
4938                 case CEE_CALL:
4939                 case CEE_CALLVIRT:
4940                         code_bounds_check (5);
4941                         do_invoke_method (&ctx, read32 (ip + 1), *ip == CEE_CALLVIRT);
4942                         ip += 5;
4943                         break;
4944
4945                 case CEE_CALLI:
4946                         code_bounds_check (5);
4947                         token = read32 (ip + 1);
4948                         /*
4949                          * FIXME: check signature, retval, arguments etc.
4950                          * FIXME: check requirements for tail call
4951                          */
4952                         CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Intruction calli is not verifiable at 0x%04x", ctx.ip_offset));
4953                         ip += 5;
4954                         break;
4955                 case CEE_BR_S:
4956                         code_bounds_check (2);
4957                         do_static_branch (&ctx, (signed char)ip [1] + 2);
4958                         need_merge = 1;
4959                         ip += 2;
4960                         start = 1;
4961                         break;
4962
4963                 case CEE_BRFALSE_S:
4964                 case CEE_BRTRUE_S:
4965                         code_bounds_check (2);
4966                         do_boolean_branch_op (&ctx, (signed char)ip [1] + 2);
4967                         ip += 2;
4968                         need_merge = 1;
4969                         break;
4970
4971                 case CEE_BR:
4972                         code_bounds_check (5);
4973                         do_static_branch (&ctx, (gint32)read32 (ip + 1) + 5);
4974                         need_merge = 1;
4975                         ip += 5;
4976                         start = 1;
4977                         break;
4978
4979                 case CEE_BRFALSE:
4980                 case CEE_BRTRUE:
4981                         code_bounds_check (5);
4982                         do_boolean_branch_op (&ctx, (gint32)read32 (ip + 1) + 5);
4983                         ip += 5;
4984                         need_merge = 1;
4985                         break;
4986
4987                 case CEE_SWITCH: {
4988                         guint32 entries;
4989                         code_bounds_check (5);
4990                         entries = read32 (ip + 1);
4991
4992                         if (entries > 0xFFFFFFFFU / sizeof (guint32))
4993                                 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Too many switch entries %x at 0x%04x", entries, ctx.ip_offset));
4994
4995                         ip += 5;
4996                         code_bounds_check (sizeof (guint32) * entries);
4997                         
4998                         do_switch (&ctx, entries, ip);
4999                         ip += sizeof (guint32) * entries;
5000                         break;
5001                 }
5002                 case CEE_LDIND_I1:
5003                 case CEE_LDIND_U1:
5004                 case CEE_LDIND_I2:
5005                 case CEE_LDIND_U2:
5006                 case CEE_LDIND_I4:
5007                 case CEE_LDIND_U4:
5008                 case CEE_LDIND_I8:
5009                 case CEE_LDIND_I:
5010                 case CEE_LDIND_R4:
5011                 case CEE_LDIND_R8:
5012                 case CEE_LDIND_REF:
5013                         do_load_indirect (&ctx, *ip);
5014                         ++ip;
5015                         break;
5016                         
5017                 case CEE_STIND_REF:
5018                 case CEE_STIND_I1:
5019                 case CEE_STIND_I2:
5020                 case CEE_STIND_I4:
5021                 case CEE_STIND_I8:
5022                 case CEE_STIND_R4:
5023                 case CEE_STIND_R8:
5024                 case CEE_STIND_I:
5025                         do_store_indirect (&ctx, *ip);
5026                         ++ip;
5027                         break;
5028
5029                 case CEE_NOT:
5030                 case CEE_NEG:
5031                         do_unary_math_op (&ctx, *ip);
5032                         ++ip;
5033                         break;
5034
5035                 case CEE_CONV_I1:
5036                 case CEE_CONV_I2:
5037                 case CEE_CONV_I4:
5038                 case CEE_CONV_U1:
5039                 case CEE_CONV_U2:
5040                 case CEE_CONV_U4:
5041                         do_conversion (&ctx, TYPE_I4);
5042                         ++ip;
5043                         break;                  
5044
5045                 case CEE_CONV_I8:
5046                 case CEE_CONV_U8:
5047                         do_conversion (&ctx, TYPE_I8);
5048                         ++ip;
5049                         break;                  
5050
5051                 case CEE_CONV_R4:
5052                 case CEE_CONV_R8:
5053                 case CEE_CONV_R_UN:
5054                         do_conversion (&ctx, TYPE_R8);
5055                         ++ip;
5056                         break;                  
5057
5058                 case CEE_CONV_I:
5059                 case CEE_CONV_U:
5060                         do_conversion (&ctx, TYPE_NATIVE_INT);
5061                         ++ip;
5062                         break;
5063
5064                 case CEE_CPOBJ:
5065                         code_bounds_check (5);
5066                         do_cpobj (&ctx, read32 (ip + 1));
5067                         ip += 5;
5068                         break;
5069
5070                 case CEE_LDOBJ:
5071                         code_bounds_check (5);
5072                         do_ldobj_value (&ctx, read32 (ip + 1));
5073                         ip += 5;
5074                         break;
5075
5076                 case CEE_LDSTR:
5077                         code_bounds_check (5);
5078                         do_ldstr (&ctx, read32 (ip + 1));
5079                         ip += 5;
5080                         break;
5081
5082                 case CEE_NEWOBJ:
5083                         code_bounds_check (5);
5084                         do_newobj (&ctx, read32 (ip + 1));
5085                         ip += 5;
5086                         break;
5087
5088                 case CEE_CASTCLASS:
5089                 case CEE_ISINST:
5090                         code_bounds_check (5);
5091                         do_cast (&ctx, read32 (ip + 1), *ip == CEE_CASTCLASS ? "castclass" : "isinst");
5092                         ip += 5;
5093                         break;
5094
5095                 case CEE_UNUSED58:
5096                 case CEE_UNUSED1:
5097                         ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Use of the `unused' opcode"));
5098                         ++ip;
5099                         break;
5100
5101                 case CEE_UNBOX:
5102                         code_bounds_check (5);
5103                         do_unbox_value (&ctx, read32 (ip + 1));
5104                         ip += 5;
5105                         break;
5106
5107                 case CEE_THROW:
5108                         do_throw (&ctx);
5109                         start = 1;
5110                         ++ip;
5111                         break;
5112
5113                 case CEE_LDFLD:
5114                 case CEE_LDFLDA:
5115                         code_bounds_check (5);
5116                         do_push_field (&ctx, read32 (ip + 1), *ip == CEE_LDFLDA);
5117                         ip += 5;
5118                         break;
5119
5120                 case CEE_LDSFLD:
5121                 case CEE_LDSFLDA:
5122                         code_bounds_check (5);
5123                         do_push_static_field (&ctx, read32 (ip + 1), *ip == CEE_LDSFLDA);
5124                         ip += 5;
5125                         break;
5126
5127                 case CEE_STFLD:
5128                         code_bounds_check (5);
5129                         do_store_field (&ctx, read32 (ip + 1));
5130                         ip += 5;
5131                         break;
5132
5133                 case CEE_STSFLD:
5134                         code_bounds_check (5);
5135                         do_store_static_field (&ctx, read32 (ip + 1));
5136                         ip += 5;
5137                         break;
5138
5139                 case CEE_STOBJ:
5140                         code_bounds_check (5);
5141                         do_stobj (&ctx, read32 (ip + 1));
5142                         ip += 5;
5143                         break;
5144
5145                 case CEE_CONV_OVF_I1_UN:
5146                 case CEE_CONV_OVF_I2_UN:
5147                 case CEE_CONV_OVF_I4_UN:
5148                 case CEE_CONV_OVF_U1_UN:
5149                 case CEE_CONV_OVF_U2_UN:
5150                 case CEE_CONV_OVF_U4_UN:
5151                         do_conversion (&ctx, TYPE_I4);
5152                         ++ip;
5153                         break;                  
5154
5155                 case CEE_CONV_OVF_I8_UN:
5156                 case CEE_CONV_OVF_U8_UN:
5157                         do_conversion (&ctx, TYPE_I8);
5158                         ++ip;
5159                         break;                  
5160
5161                 case CEE_CONV_OVF_I_UN:
5162                 case CEE_CONV_OVF_U_UN:
5163                         do_conversion (&ctx, TYPE_NATIVE_INT);
5164                         ++ip;
5165                         break;
5166
5167                 case CEE_BOX:
5168                         code_bounds_check (5);
5169                         do_box_value (&ctx, read32 (ip + 1));
5170                         ip += 5;
5171                         break;
5172
5173                 case CEE_NEWARR:
5174                         code_bounds_check (5);
5175                         do_newarr (&ctx, read32 (ip + 1));
5176                         ip += 5;
5177                         break;
5178
5179                 case CEE_LDLEN:
5180                         do_ldlen (&ctx);
5181                         ++ip;
5182                         break;
5183
5184                 case CEE_LDELEMA:
5185                         code_bounds_check (5);
5186                         do_ldelema (&ctx, read32 (ip + 1));
5187                         ip += 5;
5188                         break;
5189
5190                 case CEE_LDELEM_I1:
5191                 case CEE_LDELEM_U1:
5192                 case CEE_LDELEM_I2:
5193                 case CEE_LDELEM_U2:
5194                 case CEE_LDELEM_I4:
5195                 case CEE_LDELEM_U4:
5196                 case CEE_LDELEM_I8:
5197                 case CEE_LDELEM_I:
5198                 case CEE_LDELEM_R4:
5199                 case CEE_LDELEM_R8:
5200                 case CEE_LDELEM_REF:
5201                         do_ldelem (&ctx, *ip, 0);
5202                         ++ip;
5203                         break;
5204
5205                 case CEE_STELEM_I:
5206                 case CEE_STELEM_I1:
5207                 case CEE_STELEM_I2:
5208                 case CEE_STELEM_I4:
5209                 case CEE_STELEM_I8:
5210                 case CEE_STELEM_R4:
5211                 case CEE_STELEM_R8:
5212                 case CEE_STELEM_REF:
5213                         do_stelem (&ctx, *ip, 0);
5214                         ++ip;
5215                         break;
5216
5217                 case CEE_LDELEM:
5218                         code_bounds_check (5);
5219                         do_ldelem (&ctx, *ip, read32 (ip + 1));
5220                         ip += 5;
5221                         break;
5222
5223                 case CEE_STELEM:
5224                         code_bounds_check (5);
5225                         do_stelem (&ctx, *ip, read32 (ip + 1));
5226                         ip += 5;
5227                         break;
5228                         
5229                 case CEE_UNBOX_ANY:
5230                         code_bounds_check (5);
5231                         do_unbox_any (&ctx, read32 (ip + 1));
5232                         ip += 5;
5233                         break;
5234
5235                 case CEE_CONV_OVF_I1:
5236                 case CEE_CONV_OVF_U1:
5237                 case CEE_CONV_OVF_I2:
5238                 case CEE_CONV_OVF_U2:
5239                 case CEE_CONV_OVF_I4:
5240                 case CEE_CONV_OVF_U4:
5241                         do_conversion (&ctx, TYPE_I4);
5242                         ++ip;
5243                         break;
5244
5245                 case CEE_CONV_OVF_I8:
5246                 case CEE_CONV_OVF_U8:
5247                         do_conversion (&ctx, TYPE_I8);
5248                         ++ip;
5249                         break;
5250
5251                 case CEE_CONV_OVF_I:
5252                 case CEE_CONV_OVF_U:
5253                         do_conversion (&ctx, TYPE_NATIVE_INT);
5254                         ++ip;
5255                         break;
5256
5257                 case CEE_REFANYVAL:
5258                         code_bounds_check (5);
5259                         do_refanyval (&ctx, read32 (ip + 1));
5260                         ip += 5;
5261                         break;
5262
5263                 case CEE_CKFINITE:
5264                         do_ckfinite (&ctx);
5265                         ++ip;
5266                         break;
5267
5268                 case CEE_MKREFANY:
5269                         code_bounds_check (5);
5270                         do_mkrefany (&ctx,  read32 (ip + 1));
5271                         ip += 5;
5272                         break;
5273
5274                 case CEE_LDTOKEN:
5275                         code_bounds_check (5);
5276                         do_load_token (&ctx, read32 (ip + 1));
5277                         ip += 5;
5278                         break;
5279
5280                 case CEE_ENDFINALLY:
5281                         if (!is_correct_endfinally (ctx.header, ip_offset))
5282                                 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("endfinally must be used inside a finally/fault handler at 0x%04x", ctx.ip_offset));
5283                         ctx.eval.size = 0;
5284                         start = 1;
5285                         ++ip;
5286                         break;
5287
5288                 case CEE_LEAVE:
5289                         code_bounds_check (5);
5290                         do_leave (&ctx, read32 (ip + 1) + 5);
5291                         ip += 5;
5292                         start = 1;
5293                         break;
5294
5295                 case CEE_LEAVE_S:
5296                         code_bounds_check (2);
5297                         do_leave (&ctx, (signed char)ip [1] + 2);
5298                         ip += 2;
5299                         start = 1;
5300                         break;
5301
5302                 case CEE_PREFIX1:
5303                         code_bounds_check (2);
5304                         ++ip;
5305                         switch (*ip) {
5306                         case CEE_STLOC:
5307                                 code_bounds_check (3);
5308                                 store_local (&ctx, read16 (ip + 1));
5309                                 ip += 3;
5310                                 break;
5311
5312                         case CEE_CEQ:
5313                                 do_cmp_op (&ctx, cmp_br_eq_op, *ip);
5314                                 ++ip;
5315                                 break;
5316
5317                         case CEE_CGT:
5318                         case CEE_CGT_UN:
5319                         case CEE_CLT:
5320                         case CEE_CLT_UN:
5321                                 do_cmp_op (&ctx, cmp_br_op, *ip);
5322                                 ++ip;
5323                                 break;
5324
5325                         case CEE_STARG:
5326                                 code_bounds_check (3);
5327                                 store_arg (&ctx, read16 (ip + 1) );
5328                                 ip += 3;
5329                                 break;
5330
5331
5332                         case CEE_ARGLIST:
5333                                 check_overflow (&ctx);
5334                                 if (ctx.signature->call_convention != MONO_CALL_VARARG)
5335                                         ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Cannot use arglist on method without VARGARG calling convention at 0x%04x", ctx.ip_offset));
5336                                 set_stack_value (&ctx, stack_push (&ctx), &mono_defaults.argumenthandle_class->byval_arg, FALSE);
5337                                 ++ip;
5338                                 break;
5339         
5340                         case CEE_LDFTN:
5341                                 code_bounds_check (5);
5342                                 do_load_function_ptr (&ctx, read32 (ip + 1), FALSE);
5343                                 ip += 5;
5344                                 break;
5345
5346                         case CEE_LDVIRTFTN:
5347                                 code_bounds_check (5);
5348                                 do_load_function_ptr (&ctx, read32 (ip + 1), TRUE);
5349                                 ip += 5;
5350                                 break;
5351
5352                         case CEE_LDARG:
5353                         case CEE_LDARGA:
5354                                 code_bounds_check (3);
5355                                 push_arg (&ctx, read16 (ip + 1),  *ip == CEE_LDARGA);
5356                                 ip += 3;
5357                                 break;
5358
5359                         case CEE_LDLOC:
5360                         case CEE_LDLOCA:
5361                                 code_bounds_check (3);
5362                                 push_local (&ctx, read16 (ip + 1), *ip == CEE_LDLOCA);
5363                                 ip += 3;
5364                                 break;
5365
5366                         case CEE_LOCALLOC:
5367                                 do_localloc (&ctx);
5368                                 ++ip;
5369                                 break;
5370
5371                         case CEE_UNUSED56:
5372                         case CEE_UNUSED57:
5373                         case CEE_UNUSED70:
5374                         case CEE_UNUSED:
5375                                 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Use of the `unused' opcode"));
5376                                 ++ip;
5377                                 break;
5378                         case CEE_ENDFILTER:
5379                                 do_endfilter (&ctx);
5380                                 start = 1;
5381                                 ++ip;
5382                                 break;
5383                         case CEE_UNALIGNED_:
5384                                 code_bounds_check (2);
5385                                 prefix |= PREFIX_UNALIGNED;
5386                                 ip += 2;
5387                                 break;
5388                         case CEE_VOLATILE_:
5389                                 prefix |= PREFIX_VOLATILE;
5390                                 ++ip;
5391                                 break;
5392                         case CEE_TAIL_:
5393                                 prefix |= PREFIX_TAIL;
5394                                 ++ip;
5395                                 if (ip < end && (*ip != CEE_CALL && *ip != CEE_CALLI && *ip != CEE_CALLVIRT))
5396                                         ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("tail prefix must be used only with call opcodes at 0x%04x", ip_offset));
5397                                 break;
5398
5399                         case CEE_INITOBJ:
5400                                 code_bounds_check (5);
5401                                 do_initobj (&ctx, read32 (ip + 1));
5402                                 ip += 5;
5403                                 break;
5404
5405                         case CEE_CONSTRAINED_:
5406                                 code_bounds_check (5);
5407                                 ctx.constrained_type = get_boxable_mono_type (&ctx, read32 (ip + 1), "constrained.");
5408                                 prefix |= PREFIX_CONSTRAINED;
5409                                 ip += 5;
5410                                 break;
5411         
5412                         case CEE_READONLY_:
5413                                 prefix |= PREFIX_READONLY;
5414                                 ip++;
5415                                 break;
5416
5417                         case CEE_CPBLK:
5418                                 CLEAR_PREFIX (&ctx, PREFIX_UNALIGNED | PREFIX_VOLATILE);
5419                                 if (!check_underflow (&ctx, 3))
5420                                         break;
5421                                 CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Instruction cpblk is not verifiable at 0x%04x", ctx.ip_offset));
5422                                 ip++;
5423                                 break;
5424                                 
5425                         case CEE_INITBLK:
5426                                 CLEAR_PREFIX (&ctx, PREFIX_UNALIGNED | PREFIX_VOLATILE);
5427                                 if (!check_underflow (&ctx, 3))
5428                                         break;
5429                                 CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Instruction initblk is not verifiable at 0x%04x", ctx.ip_offset));
5430                                 ip++;
5431                                 break;
5432                                 
5433                         case CEE_NO_:
5434                                 ip += 2;
5435                                 break;
5436                         case CEE_RETHROW:
5437                                 if (!is_correct_rethrow (ctx.header, ip_offset))
5438                                         ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("rethrow must be used inside a catch handler at 0x%04x", ctx.ip_offset));
5439                                 ctx.eval.size = 0;
5440                                 start = 1;
5441                                 ++ip;
5442                                 break;
5443
5444                         case CEE_SIZEOF:
5445                                 code_bounds_check (5);
5446                                 do_sizeof (&ctx, read32 (ip + 1));
5447                                 ip += 5;
5448                                 break;
5449
5450                         case CEE_REFANYTYPE:
5451                                 do_refanytype (&ctx);
5452                                 ++ip;
5453                                 break;
5454
5455                         default:
5456                                 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid instruction FE %x at 0x%04x", *ip, ctx.ip_offset));
5457                                 ++ip;
5458                         }
5459                         break;
5460
5461                 default:
5462                         ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid instruction %x at 0x%04x", *ip, ctx.ip_offset));
5463                         ++ip;
5464                 }
5465
5466                 /*TODO we can fast detect a forward branch or exception block targeting code after prefix, we should fail fast*/
5467                 if (prefix) {
5468                         if (!ctx.prefix_set) //first prefix
5469                                 ctx.code [ctx.ip_offset].flags |= IL_CODE_FLAG_SEEN;
5470                         ctx.prefix_set |= prefix;
5471                         ctx.has_flags = TRUE;
5472                         prefix = 0;
5473                 } else {
5474                         if (!ctx.has_flags)
5475                                 ctx.code [ctx.ip_offset].flags |= IL_CODE_FLAG_SEEN;
5476
5477                         if (ctx.prefix_set & PREFIX_CONSTRAINED)
5478                                 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid instruction after constrained prefix at 0x%04x", ctx.ip_offset));
5479                         if (ctx.prefix_set & PREFIX_READONLY)
5480                                 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid instruction after readonly prefix at 0x%04x", ctx.ip_offset));
5481                         if (ctx.prefix_set & PREFIX_VOLATILE)
5482                                 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid instruction after volatile prefix at 0x%04x", ctx.ip_offset));
5483                         if (ctx.prefix_set & PREFIX_UNALIGNED)
5484                                 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid instruction after unaligned prefix at 0x%04x", ctx.ip_offset));
5485                         ctx.prefix_set = prefix = 0;
5486                         ctx.has_flags = FALSE;
5487                 }
5488         }
5489         /*
5490          * if ip != end we overflowed: mark as error.
5491          */
5492         if ((ip != end || !start) && ctx.verifiable && !ctx.list) {
5493                 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Run ahead of method code at 0x%04x", ip_offset));
5494         }
5495
5496         /*We should guard against the last decoded opcode, otherwise we might add errors that doesn't make sense.*/
5497         for (i = 0; i < ctx.code_size && i < ip_offset; ++i) {
5498                 if (ctx.code [i].flags & IL_CODE_FLAG_WAS_TARGET) {
5499                         if (!(ctx.code [i].flags & IL_CODE_FLAG_SEEN))
5500                                 ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Branch or exception block target middle of intruction at 0x%04x", i));
5501
5502                         if (ctx.code [i].flags & IL_CODE_DELEGATE_SEQUENCE)
5503                                 CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Branch to delegate code sequence at 0x%04x", i));
5504                 }
5505                 if ((ctx.code [i].flags & IL_CODE_LDFTN_DELEGATE_NONFINAL_VIRTUAL) && ctx.has_this_store)
5506                         CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Invalid ldftn with virtual function in method with stdarg 0 at  0x%04x", i));
5507
5508                 if ((ctx.code [i].flags & IL_CODE_CALL_NONFINAL_VIRTUAL) && ctx.has_this_store)
5509                         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));
5510         }
5511
5512         if (mono_method_is_constructor (ctx.method) && !ctx.super_ctor_called && !ctx.method->klass->valuetype && ctx.method->klass != mono_defaults.object_class) {
5513                 char *method_name = mono_method_full_name (ctx.method, TRUE);
5514                 char *type = mono_type_get_full_name (ctx.method->klass);
5515                 if (ctx.method->klass->parent && ctx.method->klass->parent->exception_type != MONO_EXCEPTION_NONE)
5516                         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));
5517                 else
5518                         CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Constructor %s for type %s not calling base type ctor.", method_name, type));
5519                 g_free (method_name);
5520                 g_free (type);
5521         }
5522
5523 cleanup:
5524         if (ctx.code) {
5525                 for (i = 0; i < ctx.header->code_size; ++i) {
5526                         if (ctx.code [i].stack)
5527                                 g_free (ctx.code [i].stack);
5528                 }
5529         }
5530
5531         for (tmp = ctx.funptrs; tmp; tmp = tmp->next)
5532                 g_free (tmp->data);
5533         g_slist_free (ctx.funptrs);
5534
5535         for (tmp = ctx.exception_types; tmp; tmp = tmp->next)
5536                 mono_metadata_free_type (tmp->data);
5537         g_slist_free (ctx.exception_types);
5538
5539         for (i = 0; i < ctx.num_locals; ++i) {
5540                 if (ctx.locals [i])
5541                         mono_metadata_free_type (ctx.locals [i]);
5542         }
5543         for (i = 0; i < ctx.max_args; ++i) {
5544                 if (ctx.params [i])
5545                         mono_metadata_free_type (ctx.params [i]);
5546         }
5547
5548         if (ctx.eval.stack)
5549                 g_free (ctx.eval.stack);
5550         if (ctx.code)
5551                 g_free (ctx.code);
5552         g_free (ctx.locals);
5553         g_free (ctx.params);
5554         mono_basic_block_free (original_bb);
5555         mono_metadata_free_mh (ctx.header);
5556
5557         finish_collect_stats ();
5558         return ctx.list;
5559 }
5560
5561 char*
5562 mono_verify_corlib ()
5563 {
5564         /* This is a public API function so cannot be removed */
5565         return NULL;
5566 }
5567
5568 /*
5569  * Returns true if @method needs to be verified.
5570  * 
5571  */
5572 gboolean
5573 mono_verifier_is_enabled_for_method (MonoMethod *method)
5574 {
5575         return mono_verifier_is_enabled_for_class (method->klass) && method->wrapper_type == MONO_WRAPPER_NONE;
5576 }
5577
5578 /*
5579  * Returns true if @klass need to be verified.
5580  * 
5581  */
5582 gboolean
5583 mono_verifier_is_enabled_for_class (MonoClass *klass)
5584 {
5585         return verify_all || (verifier_mode > MONO_VERIFIER_MODE_OFF && !(klass->image->assembly && klass->image->assembly->in_gac) && klass->image != mono_defaults.corlib);
5586 }
5587
5588 gboolean
5589 mono_verifier_is_enabled_for_image (MonoImage *image)
5590 {
5591         return verify_all || verifier_mode > MONO_VERIFIER_MODE_OFF;
5592 }
5593
5594 gboolean
5595 mono_verifier_is_method_full_trust (MonoMethod *method)
5596 {
5597         return mono_verifier_is_class_full_trust (method->klass);
5598 }
5599
5600 /*
5601  * Returns if @klass is under full trust or not.
5602  * 
5603  * TODO This code doesn't take CAS into account.
5604  * 
5605  * Under verify_all all user code must be verifiable if no security option was set 
5606  * 
5607  */
5608 gboolean
5609 mono_verifier_is_class_full_trust (MonoClass *klass)
5610 {
5611         /* under CoreCLR code is trusted if it is part of the "platform" otherwise all code inside the GAC is trusted */
5612         gboolean trusted_location = (mono_security_get_mode () != MONO_SECURITY_MODE_CORE_CLR) ? 
5613                 (klass->image->assembly && klass->image->assembly->in_gac) : mono_security_core_clr_is_platform_image (klass->image);
5614
5615         if (verify_all && verifier_mode == MONO_VERIFIER_MODE_OFF)
5616                 return trusted_location || klass->image == mono_defaults.corlib;
5617         return verifier_mode < MONO_VERIFIER_MODE_VERIFIABLE || trusted_location || klass->image == mono_defaults.corlib;
5618 }
5619
5620 GSList*
5621 mono_method_verify_with_current_settings (MonoMethod *method, gboolean skip_visibility)
5622 {
5623         return mono_method_verify (method, 
5624                         (verifier_mode != MONO_VERIFIER_MODE_STRICT ? MONO_VERIFY_NON_STRICT: 0)
5625                         | (!mono_verifier_is_method_full_trust (method) ? MONO_VERIFY_FAIL_FAST : 0)
5626                         | (skip_visibility ? MONO_VERIFY_SKIP_VISIBILITY : 0));
5627 }
5628
5629 static int
5630 get_field_end (MonoClassField *field)
5631 {
5632         int align;
5633         int size = mono_type_size (field->type, &align);
5634         if (size == 0)
5635                 size = 4; /*FIXME Is this a safe bet?*/
5636         return size + field->offset;
5637 }
5638
5639 static gboolean
5640 verify_class_for_overlapping_reference_fields (MonoClass *class)
5641 {
5642         int i = 0, j;
5643         gpointer iter = NULL;
5644         MonoClassField *field;
5645         gboolean is_fulltrust = mono_verifier_is_class_full_trust (class);
5646         /*We can't skip types with !has_references since this is calculated after we have run.*/
5647         if (!((class->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_EXPLICIT_LAYOUT))
5648                 return TRUE;
5649
5650
5651         /*We must check for stuff overlapping reference fields.
5652           The outer loop uses mono_class_get_fields to ensure that MonoClass:fields get inited.
5653         */
5654         while ((field = mono_class_get_fields (class, &iter))) {
5655                 int fieldEnd = get_field_end (field);
5656                 gboolean is_valuetype = !MONO_TYPE_IS_REFERENCE (field->type);
5657                 ++i;
5658
5659                 if (mono_field_is_deleted (field) || (field->type->attrs & FIELD_ATTRIBUTE_STATIC))
5660                         continue;
5661
5662                 for (j = i; j < class->field.count; ++j) {
5663                         MonoClassField *other = &class->fields [j];
5664                         int otherEnd = get_field_end (other);
5665                         if (mono_field_is_deleted (other) || (is_valuetype && !MONO_TYPE_IS_REFERENCE (other->type)) || (other->type->attrs & FIELD_ATTRIBUTE_STATIC))
5666                                 continue;
5667
5668                         if (!is_valuetype && MONO_TYPE_IS_REFERENCE (other->type) && field->offset == other->offset && is_fulltrust)
5669                                 continue;
5670
5671                         if ((otherEnd > field->offset && otherEnd <= fieldEnd) || (other->offset >= field->offset && other->offset < fieldEnd))
5672                                 return FALSE;
5673                 }
5674         }
5675         return TRUE;
5676 }
5677
5678 static guint
5679 field_hash (gconstpointer key)
5680 {
5681         const MonoClassField *field = key;
5682         return g_str_hash (field->name) ^ mono_metadata_type_hash (field->type); /**/
5683 }
5684
5685 static gboolean
5686 field_equals (gconstpointer _a, gconstpointer _b)
5687 {
5688         const MonoClassField *a = _a;
5689         const MonoClassField *b = _b;
5690         return !strcmp (a->name, b->name) && mono_metadata_type_equal (a->type, b->type);
5691 }
5692
5693
5694 static gboolean
5695 verify_class_fields (MonoClass *class)
5696 {
5697         gpointer iter = NULL;
5698         MonoClassField *field;
5699         MonoGenericContext *context = mono_class_get_context (class);
5700         GHashTable *unique_fields = g_hash_table_new_full (&field_hash, &field_equals, NULL, NULL);
5701         if (class->generic_container)
5702                 context = &class->generic_container->context;
5703
5704         while ((field = mono_class_get_fields (class, &iter)) != NULL) {
5705                 if (!mono_type_is_valid_type_in_context (field->type, context)) {
5706                         g_hash_table_destroy (unique_fields);
5707                         return FALSE;
5708                 }
5709                 if (g_hash_table_lookup (unique_fields, field)) {
5710                         g_hash_table_destroy (unique_fields);
5711                         return FALSE;
5712                 }
5713                 g_hash_table_insert (unique_fields, field, field);
5714         }
5715         g_hash_table_destroy (unique_fields);
5716         return TRUE;
5717 }
5718
5719 static gboolean
5720 verify_interfaces (MonoClass *class)
5721 {
5722         int i;
5723         for (i = 0; i < class->interface_count; ++i) {
5724                 MonoClass *iface = class->interfaces [i];
5725                 if (!(iface->flags & TYPE_ATTRIBUTE_INTERFACE))
5726                         return FALSE;
5727         }
5728         return TRUE;
5729 }
5730
5731 static gboolean
5732 verify_valuetype_layout_with_target (MonoClass *class, MonoClass *target_class)
5733 {
5734         int type;
5735         gpointer iter = NULL;
5736         MonoClassField *field;
5737         MonoClass *field_class;
5738
5739         if (!class->valuetype)
5740                 return TRUE;
5741
5742         type = class->byval_arg.type;
5743         /*primitive type fields are not properly decoded*/
5744         if ((type >= MONO_TYPE_BOOLEAN && type <= MONO_TYPE_R8) || (type >= MONO_TYPE_I && type <= MONO_TYPE_U))
5745                 return TRUE;
5746
5747         while ((field = mono_class_get_fields (class, &iter)) != NULL) {
5748                 if (!field->type)
5749                         return FALSE;
5750
5751                 if (field->type->attrs & (FIELD_ATTRIBUTE_STATIC | FIELD_ATTRIBUTE_HAS_FIELD_RVA))
5752                         continue;
5753
5754                 field_class = mono_class_get_generic_type_definition (mono_class_from_mono_type (field->type));
5755
5756                 if (field_class == target_class || class == field_class || !verify_valuetype_layout_with_target (field_class, target_class))
5757                         return FALSE;
5758         }
5759
5760         return TRUE;
5761 }
5762
5763 static gboolean
5764 verify_valuetype_layout (MonoClass *class)
5765 {
5766         gboolean res;
5767         res = verify_valuetype_layout_with_target (class, class);
5768         return res;
5769 }
5770
5771 /*
5772  * Check if the class is verifiable.
5773  * 
5774  * Right now there are no conditions that make a class a valid but not verifiable. Both overlapping reference
5775  * field and invalid generic instantiation are fatal errors.
5776  * 
5777  * This method must be safe to be called from mono_class_init and all code must be carefull about that.
5778  * 
5779  */
5780 gboolean
5781 mono_verifier_verify_class (MonoClass *class)
5782 {
5783         /*Neither <Module>, object or ifaces have parent.*/
5784         if (!class->parent &&
5785                 class != mono_defaults.object_class && 
5786                 !MONO_CLASS_IS_INTERFACE (class) &&
5787                 (!class->image->dynamic && class->type_token != 0x2000001)) /*<Module> is the first type in the assembly*/
5788                 return FALSE;
5789         if (class->parent && MONO_CLASS_IS_INTERFACE (class->parent))
5790                 return FALSE;
5791         if (class->generic_container && (class->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_EXPLICIT_LAYOUT)
5792                 return FALSE;
5793         if (!verify_class_for_overlapping_reference_fields (class))
5794                 return FALSE;
5795         if (class->generic_class && !mono_class_is_valid_generic_instantiation (NULL, class))
5796                 return FALSE;
5797         if (class->generic_class == NULL && !verify_class_fields (class))
5798                 return FALSE;
5799         if (class->valuetype && !verify_valuetype_layout (class))
5800                 return FALSE;
5801         if (!verify_interfaces (class))
5802                 return FALSE;
5803         return TRUE;
5804 }
5805 #else
5806
5807 gboolean
5808 mono_verifier_verify_class (MonoClass *class)
5809 {
5810         /* The verifier was disabled at compile time */
5811         return TRUE;
5812 }
5813
5814 GSList*
5815 mono_method_verify_with_current_settings (MonoMethod *method, gboolean skip_visibility)
5816 {
5817         /* The verifier was disabled at compile time */
5818         return NULL;
5819 }
5820
5821 gboolean
5822 mono_verifier_is_class_full_trust (MonoClass *klass)
5823 {
5824         /* The verifier was disabled at compile time */
5825         return TRUE;
5826 }
5827
5828 gboolean
5829 mono_verifier_is_method_full_trust (MonoMethod *method)
5830 {
5831         /* The verifier was disabled at compile time */
5832         return TRUE;
5833 }
5834
5835 gboolean
5836 mono_verifier_is_enabled_for_image (MonoImage *image)
5837 {
5838         /* The verifier was disabled at compile time */
5839         return FALSE;
5840 }
5841
5842 gboolean
5843 mono_verifier_is_enabled_for_class (MonoClass *klass)
5844 {
5845         /* The verifier was disabled at compile time */
5846         return FALSE;
5847 }
5848
5849 gboolean
5850 mono_verifier_is_enabled_for_method (MonoMethod *method)
5851 {
5852         /* The verifier was disabled at compile time */
5853         return FALSE;
5854 }
5855
5856 GSList*
5857 mono_method_verify (MonoMethod *method, int level)
5858 {
5859         /* The verifier was disabled at compile time */
5860         return NULL;
5861 }
5862
5863 void
5864 mono_free_verify_list (GSList *list)
5865 {
5866         /* The verifier was disabled at compile time */
5867         /* will always be null if verifier is disabled */
5868 }
5869
5870 #endif