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