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