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