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