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