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