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