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