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