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