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