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