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