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