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