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