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