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