[runtime] Use mono_assembly_get_object_handle instead of mono_assembly_get_object_che...
[mono.git] / mono / metadata / reflection.c
1 /*
2  * reflection.c: System.Type icalls and related reflection queries.
3  * 
4  * Author:
5  *   Paolo Molaro (lupus@ximian.com)
6  *
7  * Copyright 2001-2003 Ximian, Inc (http://www.ximian.com)
8  * Copyright 2004-2009 Novell, Inc (http://www.novell.com)
9  * Copyright 2011 Rodrigo Kumpera
10  * Copyright 2016 Microsoft
11  *
12  * Licensed under the MIT license. See LICENSE file in the project root for full license information.
13  */
14 #include <config.h>
15 #include "mono/utils/mono-membar.h"
16 #include "mono/metadata/reflection-internals.h"
17 #include "mono/metadata/tabledefs.h"
18 #include "mono/metadata/metadata-internals.h"
19 #include <mono/metadata/profiler-private.h>
20 #include "mono/metadata/class-internals.h"
21 #include "mono/metadata/gc-internals.h"
22 #include "mono/metadata/domain-internals.h"
23 #include "mono/metadata/opcodes.h"
24 #include "mono/metadata/assembly.h"
25 #include "mono/metadata/object-internals.h"
26 #include <mono/metadata/exception.h>
27 #include <mono/metadata/marshal.h>
28 #include <mono/metadata/security-manager.h>
29 #include <mono/metadata/reflection-cache.h>
30 #include <mono/metadata/sre-internals.h>
31 #include <stdio.h>
32 #include <glib.h>
33 #include <errno.h>
34 #include <time.h>
35 #include <string.h>
36 #include <ctype.h>
37 #include "image.h"
38 #include "cil-coff.h"
39 #include "mono-endian.h"
40 #include <mono/metadata/gc-internals.h>
41 #include <mono/metadata/mempool-internals.h>
42 #include <mono/metadata/security-core-clr.h>
43 #include <mono/metadata/debug-helpers.h>
44 #include <mono/metadata/verify-internals.h>
45 #include <mono/metadata/mono-ptr-array.h>
46 #include <mono/utils/mono-string.h>
47 #include <mono/utils/mono-error-internals.h>
48 #include <mono/utils/checked-build.h>
49 #include <mono/utils/mono-counters.h>
50
51 static void get_default_param_value_blobs (MonoMethod *method, char **blobs, guint32 *types);
52 static MonoType* mono_reflection_get_type_with_rootimage (MonoImage *rootimage, MonoImage* image, MonoTypeNameParse *info, gboolean ignorecase, gboolean *type_resolve, MonoError *error);
53
54 /* Class lazy loading functions */
55 static GENERATE_GET_CLASS_WITH_CACHE (mono_assembly, System.Reflection, MonoAssembly)
56 static GENERATE_GET_CLASS_WITH_CACHE (mono_module, System.Reflection, MonoModule)
57 static GENERATE_GET_CLASS_WITH_CACHE (mono_method, System.Reflection, MonoMethod);
58 static GENERATE_GET_CLASS_WITH_CACHE (mono_cmethod, System.Reflection, MonoCMethod);
59 static GENERATE_GET_CLASS_WITH_CACHE (mono_field, System.Reflection, MonoField);
60 static GENERATE_GET_CLASS_WITH_CACHE (mono_event, System.Reflection, MonoEvent);
61 static GENERATE_GET_CLASS_WITH_CACHE (mono_property, System.Reflection, MonoProperty);
62 static GENERATE_GET_CLASS_WITH_CACHE (mono_parameter_info, System.Reflection, MonoParameterInfo);
63 static GENERATE_GET_CLASS_WITH_CACHE (missing, System.Reflection, Missing);
64 static GENERATE_GET_CLASS_WITH_CACHE (method_body, System.Reflection, MethodBody);
65 static GENERATE_GET_CLASS_WITH_CACHE (local_variable_info, System.Reflection, LocalVariableInfo);
66 static GENERATE_GET_CLASS_WITH_CACHE (exception_handling_clause, System.Reflection, ExceptionHandlingClause);
67 static GENERATE_GET_CLASS_WITH_CACHE (type_builder, System.Reflection.Emit, TypeBuilder);
68 static GENERATE_GET_CLASS_WITH_CACHE (dbnull, System, DBNull);
69
70
71 static int class_ref_info_handle_count;
72
73 void
74 mono_reflection_init (void)
75 {
76         mono_reflection_emit_init ();
77
78         mono_counters_register ("MonoClass::ref_info_handle count",
79                                                         MONO_COUNTER_METADATA | MONO_COUNTER_INT, &class_ref_info_handle_count);
80
81 }
82
83 /*
84  * mono_class_get_ref_info:
85  *
86  *   Return the type builder/generic param builder corresponding to KLASS, if it exists.
87  */
88 gpointer
89 mono_class_get_ref_info (MonoClass *klass)
90 {
91         MONO_REQ_GC_UNSAFE_MODE;
92         guint32 ref_info_handle = mono_class_get_ref_info_handle (klass);
93
94         if (ref_info_handle == 0)
95                 return NULL;
96         else
97                 return mono_gchandle_get_target (ref_info_handle);
98 }
99
100 void
101 mono_class_set_ref_info (MonoClass *klass, gpointer obj)
102 {
103         MONO_REQ_GC_UNSAFE_MODE;
104
105         guint32 candidate = mono_gchandle_new ((MonoObject*)obj, FALSE);
106         guint32 handle = mono_class_set_ref_info_handle (klass, candidate);
107         ++class_ref_info_handle_count;
108
109         if (handle != candidate)
110                 mono_gchandle_free (candidate);
111 }
112
113 void
114 mono_class_free_ref_info (MonoClass *klass)
115 {
116         MONO_REQ_GC_NEUTRAL_MODE;
117         guint32 handle = mono_class_get_ref_info_handle (klass);
118
119         if (handle) {
120                 mono_gchandle_free (handle);
121                 mono_class_set_ref_info_handle (klass, 0);
122         }
123 }
124
125
126 void
127 mono_custom_attrs_free (MonoCustomAttrInfo *ainfo)
128 {
129         MONO_REQ_GC_NEUTRAL_MODE;
130
131         if (ainfo && !ainfo->cached)
132                 g_free (ainfo);
133 }
134
135
136 gboolean
137 reflected_equal (gconstpointer a, gconstpointer b)
138 {
139         const ReflectedEntry *ea = (const ReflectedEntry *)a;
140         const ReflectedEntry *eb = (const ReflectedEntry *)b;
141
142         return (ea->item == eb->item) && (ea->refclass == eb->refclass);
143 }
144
145 guint
146 reflected_hash (gconstpointer a) {
147         const ReflectedEntry *ea = (const ReflectedEntry *)a;
148         return mono_aligned_addr_hash (ea->item);
149 }
150
151
152 static void
153 clear_cached_object (MonoDomain *domain, gpointer o, MonoClass *klass)
154 {
155         mono_domain_lock (domain);
156         if (domain->refobject_hash) {
157         ReflectedEntry pe;
158                 gpointer orig_pe, orig_value;
159
160                 pe.item = o;
161                 pe.refclass = klass;
162                 if (mono_g_hash_table_lookup_extended (domain->refobject_hash, &pe, &orig_pe, &orig_value)) {
163                         mono_g_hash_table_remove (domain->refobject_hash, &pe);
164                         FREE_REFENTRY (orig_pe);
165                 }
166         }
167         mono_domain_unlock (domain);
168 }
169
170 #ifdef REFENTRY_REQUIRES_CLEANUP
171 static void
172 cleanup_refobject_hash (gpointer key, gpointer value, gpointer user_data)
173 {
174         FREE_REFENTRY (key);
175 }
176 #endif
177
178 void
179 mono_reflection_cleanup_domain (MonoDomain *domain)
180 {
181         if (domain->refobject_hash) {
182 /*let's avoid scanning the whole hashtable if not needed*/
183 #ifdef REFENTRY_REQUIRES_CLEANUP
184                 mono_g_hash_table_foreach (domain->refobject_hash, cleanup_refobject_hash, NULL);
185 #endif
186                 mono_g_hash_table_destroy (domain->refobject_hash);
187                 domain->refobject_hash = NULL;
188         }
189 }
190
191
192 /*
193  * mono_assembly_get_object:
194  * @domain: an app domain
195  * @assembly: an assembly
196  *
197  * Return an System.Reflection.Assembly object representing the MonoAssembly @assembly.
198  */
199 MonoReflectionAssembly*
200 mono_assembly_get_object (MonoDomain *domain, MonoAssembly *assembly)
201 {
202         HANDLE_FUNCTION_ENTER ();
203         MonoError error;
204         MonoReflectionAssemblyHandle result = mono_assembly_get_object_handle (domain, assembly, &error);
205         mono_error_cleanup (&error); /* FIXME new API that doesn't swallow the error */
206         HANDLE_FUNCTION_RETURN_OBJ (result);
207 }
208
209 static MonoReflectionAssemblyHandle
210 assembly_object_construct (MonoDomain *domain, MonoClass *unused_klass, MonoAssembly *assembly, gpointer user_data, MonoError *error)
211 {
212         mono_error_init (error);
213         MonoReflectionAssemblyHandle res = MONO_HANDLE_NEW (MonoReflectionAssembly, mono_object_new_checked (domain, mono_class_get_mono_assembly_class (), error));
214         return_val_if_nok (error, MONO_HANDLE_CAST (MonoReflectionAssembly, NULL_HANDLE));
215         MONO_HANDLE_SETVAL (res, assembly, MonoAssembly*, assembly);
216         return res;
217 }
218
219 /*
220  * mono_assembly_get_object_handle:
221  * @domain: an app domain
222  * @assembly: an assembly
223  *
224  * Return an System.Reflection.Assembly object representing the MonoAssembly @assembly.
225  */
226 MonoReflectionAssemblyHandle
227 mono_assembly_get_object_handle (MonoDomain *domain, MonoAssembly *assembly, MonoError *error)
228 {
229         mono_error_init (error);
230         return CHECK_OR_CONSTRUCT_HANDLE (MonoReflectionAssemblyHandle, assembly, NULL, assembly_object_construct, NULL);
231 }
232
233 MonoReflectionModule*   
234 mono_module_get_object   (MonoDomain *domain, MonoImage *image)
235 {
236         HANDLE_FUNCTION_ENTER ();
237         MonoError error;
238         MonoReflectionModuleHandle result = mono_module_get_object_handle (domain, image, &error);
239         mono_error_cleanup (&error);
240         HANDLE_FUNCTION_RETURN_OBJ (result);
241 }
242
243 static MonoReflectionModuleHandle
244 module_object_construct (MonoDomain *domain, MonoClass *unused_klass, MonoImage *image, gpointer user_data, MonoError *error)
245 {
246         char* basename;
247         
248         mono_error_init (error);
249         MonoReflectionModuleHandle res = MONO_HANDLE_NEW (MonoReflectionModule, mono_object_new_checked (domain, mono_class_get_mono_module_class (), error));
250         if (!is_ok (error))
251                 goto fail;
252
253         MONO_HANDLE_SETVAL (res, image, MonoImage *, image);
254         MonoReflectionAssemblyHandle assm_obj = mono_assembly_get_object_handle (domain, image->assembly, error);
255         if (!is_ok (error))
256                 goto fail;
257         MONO_HANDLE_SET (res, assembly, assm_obj);
258
259         MONO_HANDLE_SET (res, fqname, mono_string_new_handle (domain, image->name, error));
260         if (!is_ok (error))
261                 goto fail;
262         basename = g_path_get_basename (image->name);
263         MONO_HANDLE_SET (res, name, mono_string_new_handle (domain, basename, error));
264         if (!is_ok (error))
265                 goto fail;
266         MONO_HANDLE_SET (res, scopename, mono_string_new_handle (domain, image->module_name, error));
267         if (!is_ok (error))
268                 goto fail;
269
270         g_free (basename);
271
272         guint32 token = 0;
273         if (image->assembly->image == image) {
274                 token  = mono_metadata_make_token (MONO_TABLE_MODULE, 1);
275         } else {
276                 int i;
277                 if (image->assembly->image->modules) {
278                         for (i = 0; i < image->assembly->image->module_count; i++) {
279                                 if (image->assembly->image->modules [i] == image)
280                                         token = mono_metadata_make_token (MONO_TABLE_MODULEREF, i + 1);
281                         }
282                         g_assert (token != 0);
283                 }
284         }
285         MONO_HANDLE_SETVAL (res, token, guint32, token);
286
287         return res;
288 fail:
289         return MONO_HANDLE_CAST (MonoReflectionModule, NULL_HANDLE);
290 }
291
292 MonoReflectionModuleHandle
293 mono_module_get_object_handle (MonoDomain *domain, MonoImage *image, MonoError *error)
294 {
295         mono_error_init (error);
296         return CHECK_OR_CONSTRUCT_HANDLE (MonoReflectionModuleHandle, image, NULL, module_object_construct, NULL);
297 }
298
299 MonoReflectionModule*
300 mono_module_file_get_object (MonoDomain *domain, MonoImage *image, int table_index)
301 {
302         HANDLE_FUNCTION_ENTER ();
303         MonoError error;
304         MonoReflectionModuleHandle result = mono_module_file_get_object_handle (domain, image, table_index, &error);
305         mono_error_cleanup (&error);
306         HANDLE_FUNCTION_RETURN_OBJ (result);
307 }
308
309 MonoReflectionModuleHandle
310 mono_module_file_get_object_handle (MonoDomain *domain, MonoImage *image, int table_index, MonoError *error)
311 {
312         MonoTableInfo *table;
313         guint32 cols [MONO_FILE_SIZE];
314         const char *name;
315         guint32 i, name_idx;
316         const char *val;
317         
318         mono_error_init (error);
319
320         MonoReflectionModuleHandle res = MONO_HANDLE_NEW (MonoReflectionModule, mono_object_new_checked (domain, mono_class_get_mono_module_class (), error));
321         if (!is_ok (error))
322                 goto fail;
323
324         table = &image->tables [MONO_TABLE_FILE];
325         g_assert (table_index < table->rows);
326         mono_metadata_decode_row (table, table_index, cols, MONO_FILE_SIZE);
327
328         MONO_HANDLE_SETVAL (res, image, MonoImage*, NULL);
329         MonoReflectionAssemblyHandle assm_obj = mono_assembly_get_object_handle (domain, image->assembly, error);
330         if (!is_ok (error))
331                 goto fail;
332         MONO_HANDLE_SET (res, assembly, assm_obj);
333         name = mono_metadata_string_heap (image, cols [MONO_FILE_NAME]);
334
335         /* Check whenever the row has a corresponding row in the moduleref table */
336         table = &image->tables [MONO_TABLE_MODULEREF];
337         for (i = 0; i < table->rows; ++i) {
338                 name_idx = mono_metadata_decode_row_col (table, i, MONO_MODULEREF_NAME);
339                 val = mono_metadata_string_heap (image, name_idx);
340                 if (strcmp (val, name) == 0)
341                         MONO_HANDLE_SETVAL (res, image, MonoImage*, image->modules [i]);
342         }
343
344         MONO_HANDLE_SET (res, fqname, mono_string_new_handle (domain, name, error));
345         if (!is_ok (error))
346                 goto fail;
347         MONO_HANDLE_SET (res, name, mono_string_new_handle (domain, name, error));
348         if (!is_ok (error))
349                 goto fail;
350         MONO_HANDLE_SET (res, scopename, mono_string_new_handle (domain, name, error));
351         if (!is_ok (error))
352                 goto fail;
353         MONO_HANDLE_SETVAL (res, is_resource, MonoBoolean, cols [MONO_FILE_FLAGS] & FILE_CONTAINS_NO_METADATA);
354         MONO_HANDLE_SETVAL (res, token, guint32, mono_metadata_make_token (MONO_TABLE_FILE, table_index + 1));
355
356         return res;
357 fail:
358         return MONO_HANDLE_CAST (MonoReflectionModule, NULL_HANDLE);
359 }
360
361 static MonoType*
362 mono_type_normalize (MonoType *type)
363 {
364         int i;
365         MonoGenericClass *gclass;
366         MonoGenericInst *ginst;
367         MonoClass *gtd;
368         MonoGenericContainer *gcontainer;
369         MonoType **argv = NULL;
370         gboolean is_denorm_gtd = TRUE, requires_rebind = FALSE;
371
372         if (type->type != MONO_TYPE_GENERICINST)
373                 return type;
374
375         gclass = type->data.generic_class;
376         ginst = gclass->context.class_inst;
377         if (!ginst->is_open)
378                 return type;
379
380         gtd = gclass->container_class;
381         gcontainer = mono_class_get_generic_container (gtd);
382         argv = g_newa (MonoType*, ginst->type_argc);
383
384         for (i = 0; i < ginst->type_argc; ++i) {
385                 MonoType *t = ginst->type_argv [i], *norm;
386                 if (t->type != MONO_TYPE_VAR || t->data.generic_param->num != i || t->data.generic_param->owner != gcontainer)
387                         is_denorm_gtd = FALSE;
388                 norm = mono_type_normalize (t);
389                 argv [i] = norm;
390                 if (norm != t)
391                         requires_rebind = TRUE;
392         }
393
394         if (is_denorm_gtd)
395                 return type->byref == gtd->byval_arg.byref ? &gtd->byval_arg : &gtd->this_arg;
396
397         if (requires_rebind) {
398                 MonoClass *klass = mono_class_bind_generic_parameters (gtd, ginst->type_argc, argv, gclass->is_dynamic);
399                 return type->byref == klass->byval_arg.byref ? &klass->byval_arg : &klass->this_arg;
400         }
401
402         return type;
403 }
404 /*
405  * mono_type_get_object:
406  * @domain: an app domain
407  * @type: a type
408  *
409  * Return an System.MonoType object representing the type @type.
410  */
411 MonoReflectionType*
412 mono_type_get_object (MonoDomain *domain, MonoType *type)
413 {
414         MonoError error;
415         MonoReflectionType *ret = mono_type_get_object_checked (domain, type, &error);
416         mono_error_cleanup (&error);
417
418         return ret;
419 }
420
421 MonoReflectionType*
422 mono_type_get_object_checked (MonoDomain *domain, MonoType *type, MonoError *error)
423 {
424         MonoType *norm_type;
425         MonoReflectionType *res;
426         MonoClass *klass;
427
428         mono_error_init (error);
429
430         g_assert (type != NULL);
431         klass = mono_class_from_mono_type (type);
432
433         /*we must avoid using @type as it might have come
434          * from a mono_metadata_type_dup and the caller
435          * expects that is can be freed.
436          * Using the right type from 
437          */
438         type = klass->byval_arg.byref == type->byref ? &klass->byval_arg : &klass->this_arg;
439
440         /* void is very common */
441         if (type->type == MONO_TYPE_VOID && domain->typeof_void)
442                 return (MonoReflectionType*)domain->typeof_void;
443
444         /*
445          * If the vtable of the given class was already created, we can use
446          * the MonoType from there and avoid all locking and hash table lookups.
447          * 
448          * We cannot do this for TypeBuilders as mono_reflection_create_runtime_class expects
449          * that the resulting object is different.   
450          */
451         if (type == &klass->byval_arg && !image_is_dynamic (klass->image)) {
452                 MonoVTable *vtable = mono_class_try_get_vtable (domain, klass);
453                 if (vtable && vtable->type)
454                         return (MonoReflectionType *)vtable->type;
455         }
456
457         mono_loader_lock (); /*FIXME mono_class_init and mono_class_vtable acquire it*/
458         mono_domain_lock (domain);
459         if (!domain->type_hash)
460                 domain->type_hash = mono_g_hash_table_new_type ((GHashFunc)mono_metadata_type_hash, 
461                                 (GCompareFunc)mono_metadata_type_equal, MONO_HASH_VALUE_GC, MONO_ROOT_SOURCE_DOMAIN, "domain reflection types table");
462         if ((res = (MonoReflectionType *)mono_g_hash_table_lookup (domain->type_hash, type))) {
463                 mono_domain_unlock (domain);
464                 mono_loader_unlock ();
465                 return res;
466         }
467
468         /*Types must be normalized so a generic instance of the GTD get's the same inner type.
469          * For example in: Foo<A,B>; Bar<A> : Foo<A, Bar<A>>
470          * The second Bar will be encoded a generic instance of Bar with <A> as parameter.
471          * On all other places, Bar<A> will be encoded as the GTD itself. This is an implementation
472          * artifact of how generics are encoded and should be transparent to managed code so we
473          * need to weed out this diference when retrieving managed System.Type objects.
474          */
475         norm_type = mono_type_normalize (type);
476         if (norm_type != type) {
477                 res = mono_type_get_object_checked (domain, norm_type, error);
478                 if (!mono_error_ok (error))
479                         return NULL;
480                 mono_g_hash_table_insert (domain->type_hash, type, res);
481                 mono_domain_unlock (domain);
482                 mono_loader_unlock ();
483                 return res;
484         }
485
486         if ((type->type == MONO_TYPE_GENERICINST) && type->data.generic_class->is_dynamic && !type->data.generic_class->container_class->wastypebuilder) {
487                 /* This can happen if a TypeBuilder for a generic class K<T,U>
488                  * had reflection_create_generic_class) called on it, but not
489                  * ves_icall_TypeBuilder_create_runtime_class.  This can happen
490                  * if the K`2 is refernced from a generic instantiation
491                  * (e.g. K<int,string>) that appears as type argument
492                  * (e.g. Dict<string,K<int,string>>), field (e.g. K<int,string>
493                  * Foo) or method signature, parent class or any of the above
494                  * in a nested class of some other TypeBuilder.  Such an
495                  * occurrence caused mono_reflection_type_get_handle to be
496                  * called on the sre generic instance (K<int,string>) which
497                  * required the container_class for the generic class K`2 to be
498                  * set up, but the remainder of class construction for K`2 has
499                  * not been done. */
500                 char * full_name = mono_type_get_full_name (klass);
501                 /* I would have expected ReflectionTypeLoadException, but evidently .NET throws TLE in this case. */
502                 mono_error_set_type_load_class (error, klass, "TypeBuilder.CreateType() not called for generic class %s", full_name);
503                 g_free (full_name);
504                 mono_domain_unlock (domain);
505                 mono_loader_unlock ();
506                 return NULL;
507         }
508
509         if (mono_class_get_ref_info (klass) && !klass->wastypebuilder && !type->byref) {
510                 mono_domain_unlock (domain);
511                 mono_loader_unlock ();
512                 return (MonoReflectionType *)mono_class_get_ref_info (klass);
513         }
514         /* This is stored in vtables/JITted code so it has to be pinned */
515         res = (MonoReflectionType *)mono_object_new_pinned (domain, mono_defaults.runtimetype_class, error);
516         if (!mono_error_ok (error))
517                 return NULL;
518
519         res->type = type;
520         mono_g_hash_table_insert (domain->type_hash, type, res);
521
522         if (type->type == MONO_TYPE_VOID)
523                 domain->typeof_void = (MonoObject*)res;
524
525         mono_domain_unlock (domain);
526         mono_loader_unlock ();
527         return res;
528 }
529
530 MonoReflectionTypeHandle
531 mono_type_get_object_handle (MonoDomain *domain, MonoType *type, MonoError *error)
532 {
533         /* NOTE: We happen to know that mono_type_get_object_checked returns
534          * pinned objects, so we can just wrap its return value in a handle for
535          * uniformity.  If it ever starts returning unpinned, objects, this
536          * implementation would need to change!
537          */
538         return MONO_HANDLE_NEW (MonoReflectionType, mono_type_get_object_checked (domain, type, error));
539 }
540
541 /*
542  * mono_method_get_object:
543  * @domain: an app domain
544  * @method: a method
545  * @refclass: the reflected type (can be NULL)
546  *
547  * Return an System.Reflection.MonoMethod object representing the method @method.
548  */
549 MonoReflectionMethod*
550 mono_method_get_object (MonoDomain *domain, MonoMethod *method, MonoClass *refclass)
551 {
552         MonoError error;
553         MonoReflectionMethod *ret = NULL;
554         ret = mono_method_get_object_checked (domain, method, refclass, &error);
555         mono_error_cleanup (&error);
556         return ret;
557 }
558
559 static MonoReflectionMethod*
560 method_object_construct (MonoDomain *domain, MonoClass *refclass, MonoMethod *method, gpointer user_data, MonoError *error)
561 {
562         mono_error_init (error);
563         g_assert (refclass != NULL);
564         /*
565          * We use the same C representation for methods and constructors, but the type 
566          * name in C# is different.
567          */
568         MonoReflectionType *rt;
569         MonoClass *klass;
570         MonoReflectionMethod *ret;
571
572         mono_error_init (error);
573
574         if (*method->name == '.' && (strcmp (method->name, ".ctor") == 0 || strcmp (method->name, ".cctor") == 0)) {
575                 klass = mono_class_get_mono_cmethod_class ();
576         }
577         else {
578                 klass = mono_class_get_mono_method_class ();
579         }
580         ret = (MonoReflectionMethod*)mono_object_new_checked (domain, klass, error);
581         if (!mono_error_ok (error))
582                 goto leave;
583         ret->method = method;
584
585         rt = mono_type_get_object_checked (domain, &refclass->byval_arg, error);
586         if (!mono_error_ok (error))
587                 goto leave;
588
589         MONO_OBJECT_SETREF (ret, reftype, rt);
590
591         return ret;
592
593 leave:
594         g_assert (!mono_error_ok (error));
595         return NULL;
596 }
597
598 /*
599  * mono_method_get_object_checked:
600  * @domain: an app domain
601  * @method: a method
602  * @refclass: the reflected type (can be NULL)
603  * @error: set on error.
604  *
605  * Return an System.Reflection.MonoMethod object representing the method @method.
606  * Returns NULL and sets @error on error.
607  */
608 MonoReflectionMethod*
609 mono_method_get_object_checked (MonoDomain *domain, MonoMethod *method, MonoClass *refclass, MonoError *error)
610 {
611         mono_error_init (error);
612         if (!refclass)
613                 refclass = method->klass;
614
615         return CHECK_OR_CONSTRUCT (MonoReflectionMethod*, method, refclass, method_object_construct, NULL);
616 }
617
618 /*
619  * mono_method_clear_object:
620  *
621  *   Clear the cached reflection objects for the dynamic method METHOD.
622  */
623 void
624 mono_method_clear_object (MonoDomain *domain, MonoMethod *method)
625 {
626         MonoClass *klass;
627         g_assert (method_is_dynamic (method));
628
629         klass = method->klass;
630         while (klass) {
631                 clear_cached_object (domain, method, klass);
632                 klass = klass->parent;
633         }
634         /* Added by mono_param_get_objects () */
635         clear_cached_object (domain, &(method->signature), NULL);
636         klass = method->klass;
637         while (klass) {
638                 clear_cached_object (domain, &(method->signature), klass);
639                 klass = klass->parent;
640         }
641 }
642
643 /*
644  * mono_field_get_object:
645  * @domain: an app domain
646  * @klass: a type
647  * @field: a field
648  *
649  * Return an System.Reflection.MonoField object representing the field @field
650  * in class @klass.
651  */
652 MonoReflectionField*
653 mono_field_get_object (MonoDomain *domain, MonoClass *klass, MonoClassField *field)
654 {
655         MonoError error;
656         MonoReflectionField *result;
657         result = mono_field_get_object_checked (domain, klass, field, &error);
658         mono_error_cleanup (&error);
659         return result;
660 }
661
662 static MonoReflectionField*
663 field_object_construct (MonoDomain *domain, MonoClass *klass, MonoClassField *field, gpointer user_data, MonoError *error)
664 {
665         MonoReflectionType *rt;
666         MonoReflectionField *res;
667
668         mono_error_init (error);
669
670         res = (MonoReflectionField *)mono_object_new_checked (domain, mono_class_get_mono_field_class (), error);
671         if (!res)
672                 return NULL;
673         res->klass = klass;
674         res->field = field;
675         MONO_OBJECT_SETREF (res, name, mono_string_new (domain, mono_field_get_name (field)));
676
677         if (field->type) {
678                 rt = mono_type_get_object_checked (domain, field->type, error);
679                 if (!mono_error_ok (error))
680                         return NULL;
681
682                 MONO_OBJECT_SETREF (res, type, rt);
683         }
684         res->attrs = mono_field_get_flags (field);
685         return res;
686 }
687
688 /*
689  * mono_field_get_object_checked:
690  * @domain: an app domain
691  * @klass: a type
692  * @field: a field
693  * @error: set on error
694  *
695  * Return an System.Reflection.MonoField object representing the field @field
696  * in class @klass. On error, returns NULL and sets @error.
697  */
698 MonoReflectionField*
699 mono_field_get_object_checked (MonoDomain *domain, MonoClass *klass, MonoClassField *field, MonoError *error)
700 {
701         mono_error_init (error);
702         return CHECK_OR_CONSTRUCT (MonoReflectionField*, field, klass, field_object_construct, NULL);
703 }
704
705 /*
706  * mono_property_get_object:
707  * @domain: an app domain
708  * @klass: a type
709  * @property: a property
710  *
711  * Return an System.Reflection.MonoProperty object representing the property @property
712  * in class @klass.
713  */
714 MonoReflectionProperty*
715 mono_property_get_object (MonoDomain *domain, MonoClass *klass, MonoProperty *property)
716 {
717         MonoError error;
718         MonoReflectionProperty *result;
719         result = mono_property_get_object_checked (domain, klass, property, &error);
720         mono_error_cleanup (&error);
721         return result;
722 }
723
724 static MonoReflectionProperty*
725 property_object_construct (MonoDomain *domain, MonoClass *klass, MonoProperty *property, gpointer user_data, MonoError *error)
726 {
727         MonoReflectionProperty *res;
728
729         mono_error_init (error);
730
731         res = (MonoReflectionProperty *)mono_object_new_checked (domain, mono_class_get_mono_property_class (), error);
732         if (!res)
733                 return NULL;
734         res->klass = klass;
735         res->property = property;
736         return res;
737 }
738
739 /**
740  * mono_property_get_object:
741  * @domain: an app domain
742  * @klass: a type
743  * @property: a property
744  * @error: set on error
745  *
746  * Return an System.Reflection.MonoProperty object representing the property @property
747  * in class @klass.  On error returns NULL and sets @error.
748  */
749 MonoReflectionProperty*
750 mono_property_get_object_checked (MonoDomain *domain, MonoClass *klass, MonoProperty *property, MonoError *error)
751 {
752         mono_error_init (error);
753         return CHECK_OR_CONSTRUCT (MonoReflectionProperty*, property, klass, property_object_construct, NULL);
754 }
755
756 /*
757  * mono_event_get_object:
758  * @domain: an app domain
759  * @klass: a type
760  * @event: a event
761  *
762  * Return an System.Reflection.MonoEvent object representing the event @event
763  * in class @klass.
764  */
765 MonoReflectionEvent*
766 mono_event_get_object (MonoDomain *domain, MonoClass *klass, MonoEvent *event)
767 {
768         MonoError error;
769         MonoReflectionEvent *result;
770         result = mono_event_get_object_checked (domain, klass, event, &error);
771         mono_error_cleanup (&error);
772         return result;
773 }
774
775 static MonoReflectionEvent*
776 event_object_construct (MonoDomain *domain, MonoClass *klass, MonoEvent *event, gpointer user_data, MonoError *error)
777 {
778         MonoReflectionMonoEvent *mono_event;
779
780         mono_error_init (error);
781         mono_event = (MonoReflectionMonoEvent *)mono_object_new_checked (domain, mono_class_get_mono_event_class (), error);
782         if (!mono_event)
783                 return NULL;
784         mono_event->klass = klass;
785         mono_event->event = event;
786         return &mono_event->object;
787 }
788
789 /**
790  * mono_event_get_object_checked:
791  * @domain: an app domain
792  * @klass: a type
793  * @event: a event
794  * @error: set on error
795  *
796  * Return an System.Reflection.MonoEvent object representing the event @event
797  * in class @klass. On failure sets @error and returns NULL
798  */
799 MonoReflectionEvent*
800 mono_event_get_object_checked (MonoDomain *domain, MonoClass *klass, MonoEvent *event, MonoError *error)
801 {
802         mono_error_init (error);
803         return CHECK_OR_CONSTRUCT (MonoReflectionEvent*, event, klass, event_object_construct, NULL);
804 }
805
806 /**
807  * mono_get_reflection_missing_object:
808  * @domain: Domain where the object lives
809  *
810  * Returns the System.Reflection.Missing.Value singleton object
811  * (of type System.Reflection.Missing).
812  *
813  * Used as the value for ParameterInfo.DefaultValue when Optional
814  * is present
815  */
816 static MonoObject *
817 mono_get_reflection_missing_object (MonoDomain *domain)
818 {
819         MonoError error;
820         MonoObject *obj;
821         static MonoClassField *missing_value_field = NULL;
822         
823         if (!missing_value_field) {
824                 MonoClass *missing_klass;
825                 missing_klass = mono_class_get_missing_class ();
826                 mono_class_init (missing_klass);
827                 missing_value_field = mono_class_get_field_from_name (missing_klass, "Value");
828                 g_assert (missing_value_field);
829         }
830         obj = mono_field_get_value_object_checked (domain, missing_value_field, NULL, &error);
831         mono_error_assert_ok (&error);
832         return obj;
833 }
834
835 static MonoObject*
836 get_dbnull_object (MonoDomain *domain, MonoError *error)
837 {
838         MonoObject *obj;
839         static MonoClassField *dbnull_value_field = NULL;
840
841         mono_error_init (error);
842
843         if (!dbnull_value_field) {
844                 MonoClass *dbnull_klass;
845                 dbnull_klass = mono_class_get_dbnull_class ();
846                 dbnull_value_field = mono_class_get_field_from_name (dbnull_klass, "Value");
847                 g_assert (dbnull_value_field);
848         }
849         obj = mono_field_get_value_object_checked (domain, dbnull_value_field, NULL, error);
850         return obj;
851 }
852
853 static MonoObject*
854 get_dbnull (MonoDomain *domain, MonoObject **dbnull, MonoError *error)
855 {
856         mono_error_init (error);
857         if (!*dbnull)
858                 *dbnull = get_dbnull_object (domain, error);
859         return *dbnull;
860 }
861
862 static MonoObject*
863 get_reflection_missing (MonoDomain *domain, MonoObject **reflection_missing)
864 {
865         if (!*reflection_missing)
866                 *reflection_missing = mono_get_reflection_missing_object (domain);
867         return *reflection_missing;
868 }
869
870 static MonoArray*
871 param_objects_construct (MonoDomain *domain, MonoClass *refclass, MonoMethodSignature **addr_of_sig, gpointer user_data, MonoError *error)
872 {
873         static MonoClass *System_Reflection_ParameterInfo;
874         static MonoClass *System_Reflection_ParameterInfo_array;
875
876         MonoMethod *method = (MonoMethod*)user_data;
877         MonoMethodSignature *sig = *addr_of_sig; /* see note in mono_param_get_objects_internal */
878
879         MonoArray *res = NULL;
880         MonoReflectionMethod *member = NULL;
881         MonoReflectionParameter *param = NULL;
882         char **names = NULL, **blobs = NULL;
883         guint32 *types = NULL;
884         MonoType *type = NULL;
885         MonoObject *dbnull = NULL;
886         MonoObject *missing = NULL;
887         MonoMarshalSpec **mspecs = NULL;
888         MonoVTable *pinfo_vtable;
889         MonoReflectionType *rt;
890         int i;
891
892         mono_error_init (error);
893         
894         if (!System_Reflection_ParameterInfo_array) {
895                 MonoClass *klass;
896                 klass = mono_class_get_mono_parameter_info_class ();
897                 System_Reflection_ParameterInfo = klass; 
898                 klass = mono_array_class_get (klass, 1);
899                 System_Reflection_ParameterInfo_array = klass;
900         }
901
902         member = mono_method_get_object_checked (domain, method, refclass, error);
903         if (!member)
904                 goto leave;
905         names = g_new (char *, sig->param_count);
906         mono_method_get_param_names (method, (const char **) names);
907
908         mspecs = g_new (MonoMarshalSpec*, sig->param_count + 1);
909         mono_method_get_marshal_info (method, mspecs);
910
911         res = mono_array_new_specific_checked (mono_class_vtable (domain, System_Reflection_ParameterInfo_array), sig->param_count, error);
912         if (!res)
913                 goto leave;
914
915         pinfo_vtable = mono_class_vtable (domain, System_Reflection_ParameterInfo);
916         for (i = 0; i < sig->param_count; ++i) {
917                 param = (MonoReflectionParameter *) mono_object_new_specific_checked (pinfo_vtable, error);
918                 if (!param)
919                         goto leave;
920
921                 rt = mono_type_get_object_checked (domain, sig->params [i], error);
922                 if (!rt)
923                         goto leave;
924
925                 MONO_OBJECT_SETREF (param, ClassImpl, rt);
926
927                 MONO_OBJECT_SETREF (param, MemberImpl, (MonoObject*)member);
928
929                 MONO_OBJECT_SETREF (param, NameImpl, mono_string_new (domain, names [i]));
930
931                 param->PositionImpl = i;
932                 param->AttrsImpl = sig->params [i]->attrs;
933
934                 if (!(param->AttrsImpl & PARAM_ATTRIBUTE_HAS_DEFAULT)) {
935                         if (param->AttrsImpl & PARAM_ATTRIBUTE_OPTIONAL)
936                                 MONO_OBJECT_SETREF (param, DefaultValueImpl, get_reflection_missing (domain, &missing));
937                         else
938                                 MONO_OBJECT_SETREF (param, DefaultValueImpl, get_dbnull (domain, &dbnull, error));
939                         if (!is_ok (error))
940                                 goto leave;
941                 } else {
942
943                         if (!blobs) {
944                                 blobs = g_new0 (char *, sig->param_count);
945                                 types = g_new0 (guint32, sig->param_count);
946                                 get_default_param_value_blobs (method, blobs, types); 
947                         }
948
949                         /* Build MonoType for the type from the Constant Table */
950                         if (!type)
951                                 type = g_new0 (MonoType, 1);
952                         type->type = (MonoTypeEnum)types [i];
953                         type->data.klass = NULL;
954                         if (types [i] == MONO_TYPE_CLASS)
955                                 type->data.klass = mono_defaults.object_class;
956                         else if ((sig->params [i]->type == MONO_TYPE_VALUETYPE) && sig->params [i]->data.klass->enumtype) {
957                                 /* For enums, types [i] contains the base type */
958
959                                         type->type = MONO_TYPE_VALUETYPE;
960                                         type->data.klass = mono_class_from_mono_type (sig->params [i]);
961                         } else
962                                 type->data.klass = mono_class_from_mono_type (type);
963
964                         MonoObject *default_val_obj = mono_get_object_from_blob (domain, type, blobs [i], error);
965                         if (!is_ok (error))
966                                 goto leave;
967                         MONO_OBJECT_SETREF (param, DefaultValueImpl, default_val_obj);
968
969                         /* Type in the Constant table is MONO_TYPE_CLASS for nulls */
970                         if (types [i] != MONO_TYPE_CLASS && !param->DefaultValueImpl) {
971                                 if (param->AttrsImpl & PARAM_ATTRIBUTE_OPTIONAL)
972                                         MONO_OBJECT_SETREF (param, DefaultValueImpl, get_reflection_missing (domain, &missing));
973                                 else
974                                         MONO_OBJECT_SETREF (param, DefaultValueImpl, get_dbnull (domain, &dbnull, error));
975                                 if (!is_ok (error))
976                                         goto leave;
977                         }
978                 }
979
980                 if (mspecs [i + 1]) {
981                         MonoReflectionMarshalAsAttribute* mobj;
982                         mobj = mono_reflection_marshal_as_attribute_from_marshal_spec (domain, method->klass, mspecs [i + 1], error);
983                         if (!mobj)
984                                 goto leave;
985                         MONO_OBJECT_SETREF (param, MarshalAsImpl, (MonoObject*)mobj);
986                 }
987                 
988                 mono_array_setref (res, i, param);
989         }
990
991 leave:
992         g_free (names);
993         g_free (blobs);
994         g_free (types);
995         g_free (type);
996
997         if (sig) {
998                 for (i = sig->param_count; i >= 0; i--) {
999                         if (mspecs [i])
1000                                 mono_metadata_free_marshal_spec (mspecs [i]);
1001                 }
1002         }
1003         g_free (mspecs);
1004
1005         if (!is_ok (error))
1006                 return NULL;
1007         
1008         return res;
1009 }
1010
1011 /*
1012  * mono_param_get_objects:
1013  * @domain: an app domain
1014  * @method: a method
1015  *
1016  * Return an System.Reflection.ParameterInfo array object representing the parameters
1017  * in the method @method.
1018  */
1019 MonoArray*
1020 mono_param_get_objects_internal (MonoDomain *domain, MonoMethod *method, MonoClass *refclass, MonoError *error)
1021 {
1022         mono_error_init (error);
1023
1024         MonoMethodSignature *sig = mono_method_signature_checked (method, error);
1025         if (!mono_error_ok (error))
1026                 goto leave;
1027
1028         if (!sig->param_count) {
1029                 MonoArray *res = mono_array_new_checked (domain, mono_class_get_mono_parameter_info_class (), 0, error);
1030                 if (!res)
1031                         goto leave;
1032
1033                 return res;
1034         }
1035
1036         /* Note: the cache is based on the address of the signature into the method
1037          * since we already cache MethodInfos with the method as keys.
1038          */
1039         return CHECK_OR_CONSTRUCT (MonoArray*, &method->signature, refclass, param_objects_construct, method);
1040 leave:
1041         return NULL;
1042 }
1043
1044 MonoArray*
1045 mono_param_get_objects (MonoDomain *domain, MonoMethod *method)
1046 {
1047         MonoError error;
1048         MonoArray *result = mono_param_get_objects_internal (domain, method, NULL, &error);
1049         mono_error_assert_ok (&error);
1050         return result;
1051 }
1052
1053 /*
1054  * mono_method_body_get_object:
1055  * @domain: an app domain
1056  * @method: a method
1057  *
1058  * Return an System.Reflection.MethodBody object representing the method @method.
1059  */
1060 MonoReflectionMethodBody*
1061 mono_method_body_get_object (MonoDomain *domain, MonoMethod *method)
1062 {
1063         MonoError error;
1064         MonoReflectionMethodBody *result = mono_method_body_get_object_checked (domain, method, &error);
1065         mono_error_cleanup (&error);
1066         return result;
1067 }
1068
1069 static MonoReflectionMethodBody*
1070 method_body_object_construct (MonoDomain *domain, MonoClass *unused_class, MonoMethod *method, gpointer user_data, MonoError *error)
1071 {
1072         MonoReflectionMethodBody *ret;
1073         MonoMethodHeader *header;
1074         MonoImage *image;
1075         MonoReflectionType *rt;
1076         guint32 method_rva, local_var_sig_token;
1077         char *ptr;
1078         unsigned char format, flags;
1079         int i;
1080
1081         mono_error_init (error);
1082
1083         /* for compatibility with .net */
1084         if (method_is_dynamic (method)) {
1085                 mono_error_set_generic_error (error, "System", "InvalidOperationException", "");
1086                 return NULL;
1087         }
1088
1089         if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
1090                 (method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
1091             (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
1092                 (method->klass->image->raw_data && method->klass->image->raw_data [1] != 'Z') ||
1093             (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME))
1094                 return NULL;
1095
1096         image = method->klass->image;
1097         header = mono_method_get_header_checked (method, error);
1098         return_val_if_nok (error, NULL);
1099
1100         if (!image_is_dynamic (image)) {
1101                 /* Obtain local vars signature token */
1102                 method_rva = mono_metadata_decode_row_col (&image->tables [MONO_TABLE_METHOD], mono_metadata_token_index (method->token) - 1, MONO_METHOD_RVA);
1103                 ptr = mono_image_rva_map (image, method_rva);
1104                 flags = *(const unsigned char *) ptr;
1105                 format = flags & METHOD_HEADER_FORMAT_MASK;
1106                 switch (format){
1107                 case METHOD_HEADER_TINY_FORMAT:
1108                         local_var_sig_token = 0;
1109                         break;
1110                 case METHOD_HEADER_FAT_FORMAT:
1111                         ptr += 2;
1112                         ptr += 2;
1113                         ptr += 4;
1114                         local_var_sig_token = read32 (ptr);
1115                         break;
1116                 default:
1117                         g_assert_not_reached ();
1118                 }
1119         } else
1120                 local_var_sig_token = 0; //FIXME
1121
1122         ret = (MonoReflectionMethodBody*)mono_object_new_checked (domain, mono_class_get_method_body_class (), error);
1123         if (!is_ok (error))
1124                 goto fail;
1125
1126         ret->init_locals = header->init_locals;
1127         ret->max_stack = header->max_stack;
1128         ret->local_var_sig_token = local_var_sig_token;
1129         MonoArray *il_arr = mono_array_new_cached (domain, mono_defaults.byte_class, header->code_size, error);
1130         if (!is_ok (error))
1131                 goto fail;
1132         MONO_OBJECT_SETREF (ret, il, il_arr);
1133         memcpy (mono_array_addr (ret->il, guint8, 0), header->code, header->code_size);
1134
1135         /* Locals */
1136         MonoArray *locals_arr = mono_array_new_cached (domain, mono_class_get_local_variable_info_class (), header->num_locals, error);
1137         if (!is_ok (error))
1138                 goto fail;
1139         MONO_OBJECT_SETREF (ret, locals, locals_arr);
1140         for (i = 0; i < header->num_locals; ++i) {
1141                 MonoReflectionLocalVariableInfo *info = (MonoReflectionLocalVariableInfo*)mono_object_new_checked (domain, mono_class_get_local_variable_info_class (), error);
1142                 if (!is_ok (error))
1143                         goto fail;
1144
1145                 rt = mono_type_get_object_checked (domain, header->locals [i], error);
1146                 if (!is_ok (error))
1147                         goto fail;
1148
1149                 MONO_OBJECT_SETREF (info, local_type, rt);
1150
1151                 info->is_pinned = header->locals [i]->pinned;
1152                 info->local_index = i;
1153                 mono_array_setref (ret->locals, i, info);
1154         }
1155
1156         /* Exceptions */
1157         MonoArray *exn_clauses = mono_array_new_cached (domain, mono_class_get_exception_handling_clause_class (), header->num_clauses, error);
1158         if (!is_ok (error))
1159                 goto fail;
1160         MONO_OBJECT_SETREF (ret, clauses, exn_clauses);
1161         for (i = 0; i < header->num_clauses; ++i) {
1162                 MonoReflectionExceptionHandlingClause *info = (MonoReflectionExceptionHandlingClause*)mono_object_new_checked (domain, mono_class_get_exception_handling_clause_class (), error);
1163                 if (!is_ok (error))
1164                         goto fail;
1165                 MonoExceptionClause *clause = &header->clauses [i];
1166
1167                 info->flags = clause->flags;
1168                 info->try_offset = clause->try_offset;
1169                 info->try_length = clause->try_len;
1170                 info->handler_offset = clause->handler_offset;
1171                 info->handler_length = clause->handler_len;
1172                 if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER)
1173                         info->filter_offset = clause->data.filter_offset;
1174                 else if (clause->data.catch_class) {
1175                         rt = mono_type_get_object_checked (mono_domain_get (), &clause->data.catch_class->byval_arg, error);
1176                         if (!is_ok (error))
1177                                 goto fail;
1178
1179                         MONO_OBJECT_SETREF (info, catch_type, rt);
1180                 }
1181
1182                 mono_array_setref (ret->clauses, i, info);
1183         }
1184
1185         mono_metadata_free_mh (header);
1186         return ret;
1187 fail:
1188         mono_metadata_free_mh (header);
1189         return NULL;
1190 }
1191
1192 /**
1193  * mono_method_body_get_object_checked:
1194  * @domain: an app domain
1195  * @method: a method
1196  * @error: set on error
1197  *
1198  * Return an System.Reflection.MethodBody object representing the
1199  * method @method.  On failure, returns NULL and sets @error.
1200  */
1201 MonoReflectionMethodBody*
1202 mono_method_body_get_object_checked (MonoDomain *domain, MonoMethod *method, MonoError *error)
1203 {
1204         mono_error_init (error);
1205         return CHECK_OR_CONSTRUCT (MonoReflectionMethodBody *, method, NULL, method_body_object_construct, NULL);
1206 }
1207
1208 /**
1209  * mono_get_dbnull_object:
1210  * @domain: Domain where the object lives
1211  *
1212  * Returns the System.DBNull.Value singleton object
1213  *
1214  * Used as the value for ParameterInfo.DefaultValue 
1215  */
1216 MonoObject *
1217 mono_get_dbnull_object (MonoDomain *domain)
1218 {
1219         MonoError error;
1220         MonoObject *obj;
1221
1222         obj = get_dbnull_object (domain, &error);
1223         mono_error_assert_ok (&error);
1224         return obj;
1225 }
1226
1227 static void
1228 get_default_param_value_blobs (MonoMethod *method, char **blobs, guint32 *types)
1229 {
1230         guint32 param_index, i, lastp, crow = 0;
1231         guint32 param_cols [MONO_PARAM_SIZE], const_cols [MONO_CONSTANT_SIZE];
1232         gint32 idx;
1233
1234         MonoClass *klass = method->klass;
1235         MonoImage *image = klass->image;
1236         MonoMethodSignature *methodsig = mono_method_signature (method);
1237
1238         MonoTableInfo *constt;
1239         MonoTableInfo *methodt;
1240         MonoTableInfo *paramt;
1241
1242         if (!methodsig->param_count)
1243                 return;
1244
1245         mono_class_init (klass);
1246
1247         if (image_is_dynamic (klass->image)) {
1248                 MonoReflectionMethodAux *aux;
1249                 if (method->is_inflated)
1250                         method = ((MonoMethodInflated*)method)->declaring;
1251                 aux = (MonoReflectionMethodAux *)g_hash_table_lookup (((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
1252                 if (aux && aux->param_defaults) {
1253                         memcpy (blobs, &(aux->param_defaults [1]), methodsig->param_count * sizeof (char*));
1254                         memcpy (types, &(aux->param_default_types [1]), methodsig->param_count * sizeof (guint32));
1255                 }
1256                 return;
1257         }
1258
1259         methodt = &klass->image->tables [MONO_TABLE_METHOD];
1260         paramt = &klass->image->tables [MONO_TABLE_PARAM];
1261         constt = &image->tables [MONO_TABLE_CONSTANT];
1262
1263         idx = mono_method_get_index (method) - 1;
1264         g_assert (idx != -1);
1265
1266         param_index = mono_metadata_decode_row_col (methodt, idx, MONO_METHOD_PARAMLIST);
1267         if (idx + 1 < methodt->rows)
1268                 lastp = mono_metadata_decode_row_col (methodt, idx + 1, MONO_METHOD_PARAMLIST);
1269         else
1270                 lastp = paramt->rows + 1;
1271
1272         for (i = param_index; i < lastp; ++i) {
1273                 guint32 paramseq;
1274
1275                 mono_metadata_decode_row (paramt, i - 1, param_cols, MONO_PARAM_SIZE);
1276                 paramseq = param_cols [MONO_PARAM_SEQUENCE];
1277
1278                 if (!(param_cols [MONO_PARAM_FLAGS] & PARAM_ATTRIBUTE_HAS_DEFAULT))
1279                         continue;
1280
1281                 crow = mono_metadata_get_constant_index (image, MONO_TOKEN_PARAM_DEF | i, crow + 1);
1282                 if (!crow) {
1283                         continue;
1284                 }
1285         
1286                 mono_metadata_decode_row (constt, crow - 1, const_cols, MONO_CONSTANT_SIZE);
1287                 blobs [paramseq - 1] = (char *)mono_metadata_blob_heap (image, const_cols [MONO_CONSTANT_VALUE]);
1288                 types [paramseq - 1] = const_cols [MONO_CONSTANT_TYPE];
1289         }
1290
1291         return;
1292 }
1293
1294 MonoObject *
1295 mono_get_object_from_blob (MonoDomain *domain, MonoType *type, const char *blob, MonoError *error)
1296 {
1297         void *retval;
1298         MonoClass *klass;
1299         MonoObject *object;
1300         MonoType *basetype = type;
1301
1302         mono_error_init (error);
1303
1304         if (!blob)
1305                 return NULL;
1306         
1307         klass = mono_class_from_mono_type (type);
1308         if (klass->valuetype) {
1309                 object = mono_object_new_checked (domain, klass, error);
1310                 return_val_if_nok (error, NULL);
1311                 retval = ((gchar *) object + sizeof (MonoObject));
1312                 if (klass->enumtype)
1313                         basetype = mono_class_enum_basetype (klass);
1314         } else {
1315                 retval = &object;
1316         }
1317                         
1318         if (!mono_get_constant_value_from_blob (domain, basetype->type,  blob, retval, error))
1319                 return object;
1320         else
1321                 return NULL;
1322 }
1323
1324 static int
1325 assembly_name_to_aname (MonoAssemblyName *assembly, char *p) {
1326         int found_sep;
1327         char *s;
1328         gboolean quoted = FALSE;
1329
1330         memset (assembly, 0, sizeof (MonoAssemblyName));
1331         assembly->culture = "";
1332         memset (assembly->public_key_token, 0, MONO_PUBLIC_KEY_TOKEN_LENGTH);
1333
1334         if (*p == '"') {
1335                 quoted = TRUE;
1336                 p++;
1337         }
1338         assembly->name = p;
1339         while (*p && (isalnum (*p) || *p == '.' || *p == '-' || *p == '_' || *p == '$' || *p == '@' || g_ascii_isspace (*p)))
1340                 p++;
1341         if (quoted) {
1342                 if (*p != '"')
1343                         return 1;
1344                 *p = 0;
1345                 p++;
1346         }
1347         if (*p != ',')
1348                 return 1;
1349         *p = 0;
1350         /* Remove trailing whitespace */
1351         s = p - 1;
1352         while (*s && g_ascii_isspace (*s))
1353                 *s-- = 0;
1354         p ++;
1355         while (g_ascii_isspace (*p))
1356                 p++;
1357         while (*p) {
1358                 if (*p == 'V' && g_ascii_strncasecmp (p, "Version=", 8) == 0) {
1359                         p += 8;
1360                         assembly->major = strtoul (p, &s, 10);
1361                         if (s == p || *s != '.')
1362                                 return 1;
1363                         p = ++s;
1364                         assembly->minor = strtoul (p, &s, 10);
1365                         if (s == p || *s != '.')
1366                                 return 1;
1367                         p = ++s;
1368                         assembly->build = strtoul (p, &s, 10);
1369                         if (s == p || *s != '.')
1370                                 return 1;
1371                         p = ++s;
1372                         assembly->revision = strtoul (p, &s, 10);
1373                         if (s == p)
1374                                 return 1;
1375                         p = s;
1376                 } else if (*p == 'C' && g_ascii_strncasecmp (p, "Culture=", 8) == 0) {
1377                         p += 8;
1378                         if (g_ascii_strncasecmp (p, "neutral", 7) == 0) {
1379                                 assembly->culture = "";
1380                                 p += 7;
1381                         } else {
1382                                 assembly->culture = p;
1383                                 while (*p && *p != ',') {
1384                                         p++;
1385                                 }
1386                         }
1387                 } else if (*p == 'P' && g_ascii_strncasecmp (p, "PublicKeyToken=", 15) == 0) {
1388                         p += 15;
1389                         if (strncmp (p, "null", 4) == 0) {
1390                                 p += 4;
1391                         } else {
1392                                 int len;
1393                                 gchar *start = p;
1394                                 while (*p && *p != ',') {
1395                                         p++;
1396                                 }
1397                                 len = (p - start + 1);
1398                                 if (len > MONO_PUBLIC_KEY_TOKEN_LENGTH)
1399                                         len = MONO_PUBLIC_KEY_TOKEN_LENGTH;
1400                                 g_strlcpy ((char*)assembly->public_key_token, start, len);
1401                         }
1402                 } else {
1403                         while (*p && *p != ',')
1404                                 p++;
1405                 }
1406                 found_sep = 0;
1407                 while (g_ascii_isspace (*p) || *p == ',') {
1408                         *p++ = 0;
1409                         found_sep = 1;
1410                         continue;
1411                 }
1412                 /* failed */
1413                 if (!found_sep)
1414                         return 1;
1415         }
1416
1417         return 0;
1418 }
1419
1420 /*
1421  * mono_reflection_parse_type:
1422  * @name: type name
1423  *
1424  * Parse a type name as accepted by the GetType () method and output the info
1425  * extracted in the info structure.
1426  * the name param will be mangled, so, make a copy before passing it to this function.
1427  * The fields in info will be valid until the memory pointed to by name is valid.
1428  *
1429  * See also mono_type_get_name () below.
1430  *
1431  * Returns: 0 on parse error.
1432  */
1433 static int
1434 _mono_reflection_parse_type (char *name, char **endptr, gboolean is_recursed,
1435                              MonoTypeNameParse *info)
1436 {
1437         char *start, *p, *w, *last_point, *startn;
1438         int in_modifiers = 0;
1439         int isbyref = 0, rank = 0, isptr = 0;
1440
1441         start = p = w = name;
1442
1443         //FIXME could we just zero the whole struct? memset (&info, 0, sizeof (MonoTypeNameParse))
1444         memset (&info->assembly, 0, sizeof (MonoAssemblyName));
1445         info->name = info->name_space = NULL;
1446         info->nested = NULL;
1447         info->modifiers = NULL;
1448         info->type_arguments = NULL;
1449
1450         /* last_point separates the namespace from the name */
1451         last_point = NULL;
1452         /* Skips spaces */
1453         while (*p == ' ') p++, start++, w++, name++;
1454
1455         while (*p) {
1456                 switch (*p) {
1457                 case '+':
1458                         *p = 0; /* NULL terminate the name */
1459                         startn = p + 1;
1460                         info->nested = g_list_append (info->nested, startn);
1461                         /* we have parsed the nesting namespace + name */
1462                         if (info->name)
1463                                 break;
1464                         if (last_point) {
1465                                 info->name_space = start;
1466                                 *last_point = 0;
1467                                 info->name = last_point + 1;
1468                         } else {
1469                                 info->name_space = (char *)"";
1470                                 info->name = start;
1471                         }
1472                         break;
1473                 case '.':
1474                         last_point = p;
1475                         break;
1476                 case '\\':
1477                         ++p;
1478                         break;
1479                 case '&':
1480                 case '*':
1481                 case '[':
1482                 case ',':
1483                 case ']':
1484                         in_modifiers = 1;
1485                         break;
1486                 default:
1487                         break;
1488                 }
1489                 if (in_modifiers)
1490                         break;
1491                 // *w++ = *p++;
1492                 p++;
1493         }
1494         
1495         if (!info->name) {
1496                 if (last_point) {
1497                         info->name_space = start;
1498                         *last_point = 0;
1499                         info->name = last_point + 1;
1500                 } else {
1501                         info->name_space = (char *)"";
1502                         info->name = start;
1503                 }
1504         }
1505         while (*p) {
1506                 switch (*p) {
1507                 case '&':
1508                         if (isbyref) /* only one level allowed by the spec */
1509                                 return 0;
1510                         isbyref = 1;
1511                         isptr = 0;
1512                         info->modifiers = g_list_append (info->modifiers, GUINT_TO_POINTER (0));
1513                         *p++ = 0;
1514                         break;
1515                 case '*':
1516                         if (isbyref) /* pointer to ref not okay */
1517                                 return 0;
1518                         info->modifiers = g_list_append (info->modifiers, GUINT_TO_POINTER (-1));
1519                         isptr = 1;
1520                         *p++ = 0;
1521                         break;
1522                 case '[':
1523                         if (isbyref) /* array of ref and generic ref are not okay */
1524                                 return 0;
1525                         //Decide if it's an array of a generic argument list
1526                         *p++ = 0;
1527
1528                         if (!*p) //XXX test
1529                                 return 0;
1530                         if (*p  == ',' || *p == '*' || *p == ']') { //array
1531                                 isptr = 0;
1532                                 rank = 1;
1533                                 while (*p) {
1534                                         if (*p == ']')
1535                                                 break;
1536                                         if (*p == ',')
1537                                                 rank++;
1538                                         else if (*p == '*') /* '*' means unknown lower bound */
1539                                                 info->modifiers = g_list_append (info->modifiers, GUINT_TO_POINTER (-2));
1540                                         else
1541                                                 return 0;
1542                                         ++p;
1543                                 }
1544                                 if (*p++ != ']')
1545                                         return 0;
1546                                 info->modifiers = g_list_append (info->modifiers, GUINT_TO_POINTER (rank));
1547                         } else {
1548                                 if (rank || isptr) /* generic args after array spec or ptr*/ //XXX test
1549                                         return 0;
1550                                 isptr = 0;
1551                                 info->type_arguments = g_ptr_array_new ();
1552                                 while (*p) {
1553                                         MonoTypeNameParse *subinfo = g_new0 (MonoTypeNameParse, 1);
1554                                         gboolean fqname = FALSE;
1555
1556                                         g_ptr_array_add (info->type_arguments, subinfo);
1557
1558                                         while (*p == ' ') p++;
1559                                         if (*p == '[') {
1560                                                 p++;
1561                                                 fqname = TRUE;
1562                                         }
1563
1564                                         if (!_mono_reflection_parse_type (p, &p, TRUE, subinfo))
1565                                                 return 0;
1566
1567                                         /*MS is lenient on [] delimited parameters that aren't fqn - and F# uses them.*/
1568                                         if (fqname && (*p != ']')) {
1569                                                 char *aname;
1570
1571                                                 if (*p != ',')
1572                                                         return 0;
1573                                                 *p++ = 0;
1574
1575                                                 aname = p;
1576                                                 while (*p && (*p != ']'))
1577                                                         p++;
1578
1579                                                 if (*p != ']')
1580                                                         return 0;
1581
1582                                                 *p++ = 0;
1583                                                 while (*aname) {
1584                                                         if (g_ascii_isspace (*aname)) {
1585                                                                 ++aname;
1586                                                                 continue;
1587                                                         }
1588                                                         break;
1589                                                 }
1590                                                 if (!*aname ||
1591                                                     !assembly_name_to_aname (&subinfo->assembly, aname))
1592                                                         return 0;
1593                                         } else if (fqname && (*p == ']')) {
1594                                                 *p++ = 0;
1595                                         }
1596                                         if (*p == ']') {
1597                                                 *p++ = 0;
1598                                                 break;
1599                                         } else if (!*p) {
1600                                                 return 0;
1601                                         }
1602                                         *p++ = 0;
1603                                 }
1604                         }
1605                         break;
1606                 case ']':
1607                         if (is_recursed)
1608                                 goto end;
1609                         return 0;
1610                 case ',':
1611                         if (is_recursed)
1612                                 goto end;
1613                         *p++ = 0;
1614                         while (*p) {
1615                                 if (g_ascii_isspace (*p)) {
1616                                         ++p;
1617                                         continue;
1618                                 }
1619                                 break;
1620                         }
1621                         if (!*p)
1622                                 return 0; /* missing assembly name */
1623                         if (!assembly_name_to_aname (&info->assembly, p))
1624                                 return 0;
1625                         break;
1626                 default:
1627                         return 0;
1628                 }
1629                 if (info->assembly.name)
1630                         break;
1631         }
1632         // *w = 0; /* terminate class name */
1633  end:
1634         if (!info->name || !*info->name)
1635                 return 0;
1636         if (endptr)
1637                 *endptr = p;
1638         /* add other consistency checks */
1639         return 1;
1640 }
1641
1642
1643 /**
1644  * mono_identifier_unescape_type_name_chars:
1645  * @identifier: the display name of a mono type
1646  *
1647  * Returns:
1648  *  The name in internal form, that is without escaping backslashes.
1649  *
1650  *  The string is modified in place!
1651  */
1652 char*
1653 mono_identifier_unescape_type_name_chars(char* identifier)
1654 {
1655         char *w, *r;
1656         if (!identifier)
1657                 return NULL;
1658         for (w = r = identifier; *r != 0; r++)
1659         {
1660                 char c = *r;
1661                 if (c == '\\') {
1662                         r++;
1663                         if (*r == 0)
1664                                 break;
1665                         c = *r;
1666                 }
1667                 *w = c;
1668                 w++;
1669         }
1670         if (w != r)
1671                 *w = 0;
1672         return identifier;
1673 }
1674
1675 void
1676 mono_identifier_unescape_info (MonoTypeNameParse* info);
1677
1678 static void
1679 unescape_each_type_argument(void* data, void* user_data)
1680 {
1681         MonoTypeNameParse* info = (MonoTypeNameParse*)data;
1682         mono_identifier_unescape_info (info);
1683 }
1684
1685 static void
1686 unescape_each_nested_name (void* data, void* user_data)
1687 {
1688         char* nested_name = (char*) data;
1689         mono_identifier_unescape_type_name_chars(nested_name);
1690 }
1691
1692 /**
1693  * mono_identifier_unescape_info:
1694  *
1695  * @info: a parsed display form of an (optionally assembly qualified) full type name.
1696  *
1697  * Returns: nothing.
1698  *
1699  * Destructively updates the info by unescaping the identifiers that
1700  * comprise the type namespace, name, nested types (if any) and
1701  * generic type arguments (if any).
1702  *
1703  * The resulting info has the names in internal form.
1704  *
1705  */
1706 void
1707 mono_identifier_unescape_info (MonoTypeNameParse *info)
1708 {
1709         if (!info)
1710                 return;
1711         mono_identifier_unescape_type_name_chars(info->name_space);
1712         mono_identifier_unescape_type_name_chars(info->name);
1713         // but don't escape info->assembly
1714         if (info->type_arguments)
1715                 g_ptr_array_foreach(info->type_arguments, &unescape_each_type_argument, NULL);
1716         if (info->nested)
1717                 g_list_foreach(info->nested, &unescape_each_nested_name, NULL);
1718 }
1719
1720 int
1721 mono_reflection_parse_type (char *name, MonoTypeNameParse *info)
1722 {
1723         int ok = _mono_reflection_parse_type (name, NULL, FALSE, info);
1724         if (ok) {
1725                 mono_identifier_unescape_info (info);
1726         }
1727         return ok;
1728 }
1729
1730 static MonoType*
1731 _mono_reflection_get_type_from_info (MonoTypeNameParse *info, MonoImage *image, gboolean ignorecase, MonoError *error)
1732 {
1733         gboolean type_resolve = FALSE;
1734         MonoType *type;
1735         MonoImage *rootimage = image;
1736
1737         mono_error_init (error);
1738
1739         if (info->assembly.name) {
1740                 MonoAssembly *assembly = mono_assembly_loaded (&info->assembly);
1741                 if (!assembly && image && image->assembly && mono_assembly_names_equal (&info->assembly, &image->assembly->aname))
1742                         /* 
1743                          * This could happen in the AOT compiler case when the search hook is not
1744                          * installed.
1745                          */
1746                         assembly = image->assembly;
1747                 if (!assembly) {
1748                         /* then we must load the assembly ourselve - see #60439 */
1749                         assembly = mono_assembly_load (&info->assembly, image->assembly->basedir, NULL);
1750                         if (!assembly)
1751                                 return NULL;
1752                 }
1753                 image = assembly->image;
1754         } else if (!image) {
1755                 image = mono_defaults.corlib;
1756         }
1757
1758         type = mono_reflection_get_type_with_rootimage (rootimage, image, info, ignorecase, &type_resolve, error);
1759         if (type == NULL && !info->assembly.name && image != mono_defaults.corlib) {
1760                 /* ignore the error and try again */
1761                 mono_error_cleanup (error);
1762                 mono_error_init (error);
1763                 image = mono_defaults.corlib;
1764                 type = mono_reflection_get_type_with_rootimage (rootimage, image, info, ignorecase, &type_resolve, error);
1765         }
1766
1767         return type;
1768 }
1769
1770 /**
1771  * mono_reflection_get_type_internal:
1772  *
1773  * Returns: may return NULL on success, sets error on failure.
1774  */
1775 static MonoType*
1776 mono_reflection_get_type_internal (MonoImage *rootimage, MonoImage* image, MonoTypeNameParse *info, gboolean ignorecase, MonoError *error)
1777 {
1778         MonoClass *klass;
1779         GList *mod;
1780         int modval;
1781         gboolean bounded = FALSE;
1782         
1783         mono_error_init (error);
1784         if (!image)
1785                 image = mono_defaults.corlib;
1786
1787         if (!rootimage)
1788                 rootimage = mono_defaults.corlib;
1789
1790         if (ignorecase)
1791                 klass = mono_class_from_name_case_checked (image, info->name_space, info->name, error);
1792         else
1793                 klass = mono_class_from_name_checked (image, info->name_space, info->name, error);
1794
1795         if (!klass)
1796                 return NULL;
1797
1798         for (mod = info->nested; mod; mod = mod->next) {
1799                 gpointer iter = NULL;
1800                 MonoClass *parent;
1801
1802                 parent = klass;
1803                 mono_class_init (parent);
1804
1805                 while ((klass = mono_class_get_nested_types (parent, &iter))) {
1806                         char *lastp;
1807                         char *nested_name, *nested_nspace;
1808                         gboolean match = TRUE;
1809
1810                         lastp = strrchr ((const char *)mod->data, '.');
1811                         if (lastp) {
1812                                 /* Nested classes can have namespaces */
1813                                 int nspace_len;
1814
1815                                 nested_name = g_strdup (lastp + 1);
1816                                 nspace_len = lastp - (char*)mod->data;
1817                                 nested_nspace = (char *)g_malloc (nspace_len + 1);
1818                                 memcpy (nested_nspace, mod->data, nspace_len);
1819                                 nested_nspace [nspace_len] = '\0';
1820
1821                         } else {
1822                                 nested_name = (char *)mod->data;
1823                                 nested_nspace = NULL;
1824                         }
1825
1826                         if (nested_nspace) {
1827                                 if (ignorecase) {
1828                                         if (!(klass->name_space && mono_utf8_strcasecmp (klass->name_space, nested_nspace) == 0))
1829                                                 match = FALSE;
1830                                 } else {
1831                                         if (!(klass->name_space && strcmp (klass->name_space, nested_nspace) == 0))
1832                                                 match = FALSE;
1833                                 }
1834                         }
1835                         if (match) {
1836                                 if (ignorecase) {
1837                                         if (mono_utf8_strcasecmp (klass->name, nested_name) != 0)
1838                                                 match = FALSE;
1839                                 } else {
1840                                         if (strcmp (klass->name, nested_name) != 0)
1841                                                 match = FALSE;
1842                                 }
1843                         }
1844                         if (lastp) {
1845                                 g_free (nested_name);
1846                                 g_free (nested_nspace);
1847                         }
1848                         if (match)
1849                                 break;
1850                 }
1851
1852                 if (!klass)
1853                         break;
1854         }
1855         if (!klass)
1856                 return NULL;
1857
1858         if (info->type_arguments) {
1859                 MonoType **type_args = g_new0 (MonoType *, info->type_arguments->len);
1860                 MonoReflectionType *the_type;
1861                 MonoType *instance;
1862                 int i;
1863
1864                 for (i = 0; i < info->type_arguments->len; i++) {
1865                         MonoTypeNameParse *subinfo = (MonoTypeNameParse *)g_ptr_array_index (info->type_arguments, i);
1866
1867                         type_args [i] = _mono_reflection_get_type_from_info (subinfo, rootimage, ignorecase, error);
1868                         if (!type_args [i]) {
1869                                 g_free (type_args);
1870                                 return NULL;
1871                         }
1872                 }
1873
1874                 the_type = mono_type_get_object_checked (mono_domain_get (), &klass->byval_arg, error);
1875                 if (!the_type)
1876                         return NULL;
1877
1878                 instance = mono_reflection_bind_generic_parameters (
1879                         the_type, info->type_arguments->len, type_args, error);
1880
1881                 g_free (type_args);
1882                 if (!instance)
1883                         return NULL;
1884
1885                 klass = mono_class_from_mono_type (instance);
1886         }
1887
1888         for (mod = info->modifiers; mod; mod = mod->next) {
1889                 modval = GPOINTER_TO_UINT (mod->data);
1890                 if (!modval) { /* byref: must be last modifier */
1891                         return &klass->this_arg;
1892                 } else if (modval == -1) {
1893                         klass = mono_ptr_class_get (&klass->byval_arg);
1894                 } else if (modval == -2) {
1895                         bounded = TRUE;
1896                 } else { /* array rank */
1897                         klass = mono_bounded_array_class_get (klass, modval, bounded);
1898                 }
1899         }
1900
1901         return &klass->byval_arg;
1902 }
1903
1904 /*
1905  * mono_reflection_get_type:
1906  * @image: a metadata context
1907  * @info: type description structure
1908  * @ignorecase: flag for case-insensitive string compares
1909  * @type_resolve: whenever type resolve was already tried
1910  *
1911  * Build a MonoType from the type description in @info.
1912  * 
1913  */
1914
1915 MonoType*
1916 mono_reflection_get_type (MonoImage* image, MonoTypeNameParse *info, gboolean ignorecase, gboolean *type_resolve) {
1917         MonoError error;
1918         MonoType *result = mono_reflection_get_type_with_rootimage (image, image, info, ignorecase, type_resolve, &error);
1919         mono_error_cleanup (&error);
1920         return result;
1921 }
1922
1923 /**
1924  * mono_reflection_get_type_checked:
1925  * @rootimage: the image of the currently active managed caller
1926  * @image: a metadata context
1927  * @info: type description structure
1928  * @ignorecase: flag for case-insensitive string compares
1929  * @type_resolve: whenever type resolve was already tried
1930  * @error: set on error.
1931  *
1932  * Build a MonoType from the type description in @info. On failure returns NULL and sets @error.
1933  *
1934  */
1935 MonoType*
1936 mono_reflection_get_type_checked (MonoImage *rootimage, MonoImage* image, MonoTypeNameParse *info, gboolean ignorecase, gboolean *type_resolve, MonoError *error) {
1937         mono_error_init (error);
1938         return mono_reflection_get_type_with_rootimage (rootimage, image, info, ignorecase, type_resolve, error);
1939 }
1940
1941
1942 static MonoType*
1943 module_builder_array_get_type (MonoArrayHandle module_builders, int i, MonoImage *rootimage, MonoTypeNameParse *info, gboolean ignorecase, MonoError *error)
1944 {
1945         HANDLE_FUNCTION_ENTER ();
1946         mono_error_init (error);
1947         MonoType *type = NULL;
1948         MonoReflectionModuleBuilderHandle mb = MONO_HANDLE_NEW (MonoReflectionModuleBuilder, NULL);
1949         MONO_HANDLE_ARRAY_GETREF (mb, module_builders, i);
1950         MonoDynamicImage *dynamic_image = MONO_HANDLE_GETVAL (mb, dynamic_image);
1951         type = mono_reflection_get_type_internal (rootimage, &dynamic_image->image, info, ignorecase, error);
1952         HANDLE_FUNCTION_RETURN_VAL (type);
1953 }
1954
1955 static MonoType*
1956 module_array_get_type (MonoArrayHandle modules, int i, MonoImage *rootimage, MonoTypeNameParse *info, gboolean ignorecase, MonoError *error)
1957 {
1958         HANDLE_FUNCTION_ENTER ();
1959         mono_error_init (error);
1960         MonoType *type = NULL;
1961         MonoReflectionModuleHandle mod = MONO_HANDLE_NEW (MonoReflectionModule, NULL);
1962         MONO_HANDLE_ARRAY_GETREF (mod, modules, i);
1963         MonoImage *image = MONO_HANDLE_GETVAL (mod, image);
1964         type = mono_reflection_get_type_internal (rootimage, image, info, ignorecase, error);
1965         HANDLE_FUNCTION_RETURN_VAL (type);
1966 }
1967
1968 static MonoType*
1969 mono_reflection_get_type_internal_dynamic (MonoImage *rootimage, MonoAssembly *assembly, MonoTypeNameParse *info, gboolean ignorecase, MonoError *error)
1970 {
1971         HANDLE_FUNCTION_ENTER ();
1972         MonoType *type = NULL;
1973         int i;
1974
1975         mono_error_init (error);
1976         g_assert (assembly_is_dynamic (assembly));
1977         MonoReflectionAssemblyBuilderHandle abuilder = MONO_HANDLE_CAST (MonoReflectionAssemblyBuilder, mono_assembly_get_object_handle (((MonoDynamicAssembly*)assembly)->domain, assembly, error));
1978         if (!is_ok (error))
1979                 goto leave;
1980
1981         /* Enumerate all modules */
1982
1983         MonoArrayHandle modules = MONO_HANDLE_NEW (MonoArray, NULL);
1984         MONO_HANDLE_GET (modules, abuilder, modules);
1985         if (!MONO_HANDLE_IS_NULL (modules)) {
1986                 int n = mono_array_handle_length (modules);
1987                 for (i = 0; i < n; ++i) {
1988                         type = module_builder_array_get_type (modules, i, rootimage, info, ignorecase, error);
1989                         if (type)
1990                                 break;
1991                         if (!is_ok (error))
1992                                 goto leave;
1993                 }
1994         }
1995
1996         MonoArrayHandle loaded_modules = MONO_HANDLE_NEW (MonoArray, NULL);
1997         MONO_HANDLE_GET (loaded_modules, abuilder, loaded_modules);
1998         if (!type && !MONO_HANDLE_IS_NULL(loaded_modules)) {
1999                 int n = mono_array_handle_length (loaded_modules);
2000                 for (i = 0; i < n; ++i) {
2001                         type = module_array_get_type (loaded_modules, i, rootimage, info, ignorecase, error);
2002                         if (type)
2003                                 break;
2004                         if (!is_ok (error))
2005                                 goto leave;
2006                 }
2007         }
2008
2009 leave:
2010         HANDLE_FUNCTION_RETURN_VAL (type);
2011 }
2012         
2013 MonoType*
2014 mono_reflection_get_type_with_rootimage (MonoImage *rootimage, MonoImage* image, MonoTypeNameParse *info, gboolean ignorecase, gboolean *type_resolve, MonoError *error)
2015 {
2016         MonoType *type;
2017         MonoReflectionAssembly *assembly;
2018         GString *fullName;
2019         GList *mod;
2020
2021         mono_error_init (error);
2022
2023         if (image && image_is_dynamic (image))
2024                 type = mono_reflection_get_type_internal_dynamic (rootimage, image->assembly, info, ignorecase, error);
2025         else {
2026                 type = mono_reflection_get_type_internal (rootimage, image, info, ignorecase, error);
2027         }
2028         return_val_if_nok (error, NULL);
2029
2030         if (type)
2031                 return type;
2032         if (!mono_domain_has_type_resolve (mono_domain_get ()))
2033                 return NULL;
2034
2035         if (type_resolve) {
2036                 if (*type_resolve) 
2037                         return NULL;
2038                 else
2039                         *type_resolve = TRUE;
2040         }
2041         
2042         /* Reconstruct the type name */
2043         fullName = g_string_new ("");
2044         if (info->name_space && (info->name_space [0] != '\0'))
2045                 g_string_printf (fullName, "%s.%s", info->name_space, info->name);
2046         else
2047                 g_string_printf (fullName, "%s", info->name);
2048         for (mod = info->nested; mod; mod = mod->next)
2049                 g_string_append_printf (fullName, "+%s", (char*)mod->data);
2050
2051         assembly = mono_domain_try_type_resolve_checked ( mono_domain_get (), fullName->str, NULL, error);
2052         if (!is_ok (error)) {
2053                 g_string_free (fullName, TRUE);
2054                 return NULL;
2055         }
2056
2057         if (assembly) {
2058                 if (assembly_is_dynamic (assembly->assembly))
2059                         type = mono_reflection_get_type_internal_dynamic (rootimage, assembly->assembly,
2060                                                                           info, ignorecase, error);
2061                 else
2062                         type = mono_reflection_get_type_internal (rootimage, assembly->assembly->image, 
2063                                                                   info, ignorecase, error);
2064         }
2065         g_string_free (fullName, TRUE);
2066         return_val_if_nok (error, NULL);
2067         return type;
2068 }
2069
2070 void
2071 mono_reflection_free_type_info (MonoTypeNameParse *info)
2072 {
2073         g_list_free (info->modifiers);
2074         g_list_free (info->nested);
2075
2076         if (info->type_arguments) {
2077                 int i;
2078
2079                 for (i = 0; i < info->type_arguments->len; i++) {
2080                         MonoTypeNameParse *subinfo = (MonoTypeNameParse *)g_ptr_array_index (info->type_arguments, i);
2081
2082                         mono_reflection_free_type_info (subinfo);
2083                         /*We free the subinfo since it is allocated by _mono_reflection_parse_type*/
2084                         g_free (subinfo);
2085                 }
2086
2087                 g_ptr_array_free (info->type_arguments, TRUE);
2088         }
2089 }
2090
2091 /*
2092  * mono_reflection_type_from_name:
2093  * @name: type name.
2094  * @image: a metadata context (can be NULL).
2095  *
2096  * Retrieves a MonoType from its @name. If the name is not fully qualified,
2097  * it defaults to get the type from @image or, if @image is NULL or loading
2098  * from it fails, uses corlib.
2099  * 
2100  */
2101 MonoType*
2102 mono_reflection_type_from_name (char *name, MonoImage *image)
2103 {
2104         MonoError error;
2105         MonoType  *result = mono_reflection_type_from_name_checked (name, image, &error);
2106         mono_error_cleanup (&error);
2107         return result;
2108 }
2109
2110 /**
2111  * mono_reflection_type_from_name_checked:
2112  * @name: type name.
2113  * @image: a metadata context (can be NULL).
2114  * @error: set on errror.
2115  *
2116  * Retrieves a MonoType from its @name. If the name is not fully qualified,
2117  * it defaults to get the type from @image or, if @image is NULL or loading
2118  * from it fails, uses corlib.  On failure returns NULL and sets @error.
2119  * 
2120  */
2121 MonoType*
2122 mono_reflection_type_from_name_checked (char *name, MonoImage *image, MonoError *error)
2123 {
2124         MonoType *type = NULL;
2125         MonoTypeNameParse info;
2126         char *tmp;
2127
2128         mono_error_init (error);
2129         /* Make a copy since parse_type modifies its argument */
2130         tmp = g_strdup (name);
2131         
2132         /*g_print ("requested type %s\n", str);*/
2133         if (mono_reflection_parse_type (tmp, &info)) {
2134                 type = _mono_reflection_get_type_from_info (&info, image, FALSE, error);
2135                 if (!is_ok (error)) {
2136                         g_free (tmp);
2137                         mono_reflection_free_type_info (&info);
2138                         return NULL;
2139                 }
2140         }
2141
2142         g_free (tmp);
2143         mono_reflection_free_type_info (&info);
2144         return type;
2145 }
2146
2147 /*
2148  * mono_reflection_get_token:
2149  *
2150  *   Return the metadata token of OBJ which should be an object
2151  * representing a metadata element.
2152  */
2153 guint32
2154 mono_reflection_get_token (MonoObject *obj)
2155 {
2156         MonoError error;
2157         guint32 result = mono_reflection_get_token_checked (obj, &error);
2158         mono_error_assert_ok (&error);
2159         return result;
2160 }
2161
2162 /**
2163  * mono_reflection_get_token_checked:
2164  * @obj: the object
2165  * @error: set on error
2166  *
2167  *   Return the metadata token of @obj which should be an object
2168  * representing a metadata element.  On failure sets @error.
2169  */
2170 guint32
2171 mono_reflection_get_token_checked (MonoObject *obj, MonoError *error)
2172 {
2173         MonoClass *klass;
2174         guint32 token = 0;
2175
2176         mono_error_init (error);
2177
2178         klass = obj->vtable->klass;
2179
2180         if (strcmp (klass->name, "MethodBuilder") == 0) {
2181                 MonoReflectionMethodBuilder *mb = (MonoReflectionMethodBuilder *)obj;
2182
2183                 token = mb->table_idx | MONO_TOKEN_METHOD_DEF;
2184         } else if (strcmp (klass->name, "ConstructorBuilder") == 0) {
2185                 MonoReflectionCtorBuilder *mb = (MonoReflectionCtorBuilder *)obj;
2186
2187                 token = mb->table_idx | MONO_TOKEN_METHOD_DEF;
2188         } else if (strcmp (klass->name, "FieldBuilder") == 0) {
2189                 MonoReflectionFieldBuilder *fb = (MonoReflectionFieldBuilder *)obj;
2190
2191                 token = fb->table_idx | MONO_TOKEN_FIELD_DEF;
2192         } else if (strcmp (klass->name, "TypeBuilder") == 0) {
2193                 MonoReflectionTypeBuilder *tb = (MonoReflectionTypeBuilder *)obj;
2194                 token = tb->table_idx | MONO_TOKEN_TYPE_DEF;
2195         } else if (strcmp (klass->name, "RuntimeType") == 0) {
2196                 MonoType *type = mono_reflection_type_get_handle ((MonoReflectionType*)obj, error);
2197                 return_val_if_nok (error, 0);
2198                 MonoClass *mc = mono_class_from_mono_type (type);
2199                 if (!mono_class_init (mc)) {
2200                         mono_error_set_for_class_failure (error, mc);
2201                         return 0;
2202                 }
2203
2204                 token = mc->type_token;
2205         } else if (strcmp (klass->name, "MonoCMethod") == 0 ||
2206                            strcmp (klass->name, "MonoMethod") == 0) {
2207                 MonoReflectionMethod *m = (MonoReflectionMethod *)obj;
2208                 if (m->method->is_inflated) {
2209                         MonoMethodInflated *inflated = (MonoMethodInflated *) m->method;
2210                         return inflated->declaring->token;
2211                 } else {
2212                         token = m->method->token;
2213                 }
2214         } else if (strcmp (klass->name, "MonoField") == 0) {
2215                 MonoReflectionField *f = (MonoReflectionField*)obj;
2216
2217                 token = mono_class_get_field_token (f->field);
2218         } else if (strcmp (klass->name, "MonoProperty") == 0) {
2219                 MonoReflectionProperty *p = (MonoReflectionProperty*)obj;
2220
2221                 token = mono_class_get_property_token (p->property);
2222         } else if (strcmp (klass->name, "MonoEvent") == 0) {
2223                 MonoReflectionMonoEvent *p = (MonoReflectionMonoEvent*)obj;
2224
2225                 token = mono_class_get_event_token (p->event);
2226         } else if (strcmp (klass->name, "ParameterInfo") == 0 || strcmp (klass->name, "MonoParameterInfo") == 0) {
2227                 MonoReflectionParameter *p = (MonoReflectionParameter*)obj;
2228                 MonoClass *member_class = mono_object_class (p->MemberImpl);
2229                 g_assert (mono_class_is_reflection_method_or_constructor (member_class));
2230
2231                 token = mono_method_get_param_token (((MonoReflectionMethod*)p->MemberImpl)->method, p->PositionImpl);
2232         } else if (strcmp (klass->name, "Module") == 0 || strcmp (klass->name, "MonoModule") == 0) {
2233                 MonoReflectionModule *m = (MonoReflectionModule*)obj;
2234
2235                 token = m->token;
2236         } else if (strcmp (klass->name, "Assembly") == 0 || strcmp (klass->name, "MonoAssembly") == 0) {
2237                 token = mono_metadata_make_token (MONO_TABLE_ASSEMBLY, 1);
2238         } else {
2239                 mono_error_set_not_implemented (error, "MetadataToken is not supported for type '%s.%s'",
2240                                                 klass->name_space, klass->name);
2241                 return 0;
2242         }
2243
2244         return token;
2245 }
2246
2247
2248 gboolean
2249 mono_reflection_is_usertype (MonoReflectionType *ref)
2250 {
2251         MonoClass *klass = mono_object_class (ref);
2252         return klass->image != mono_defaults.corlib || strcmp ("TypeDelegator", klass->name) == 0;
2253 }
2254
2255 /**
2256  * mono_reflection_bind_generic_parameters:
2257  * @type: a managed type object (which should be some kind of generic (instance? definition?))
2258  * @type_args: the number of type arguments to bind
2259  * @types: array of type arguments
2260  * @error: set on error
2261  *
2262  * Given a managed type object for a generic type instance, binds each of its arguments to the specified types.
2263  * Returns the MonoType* for the resulting type instantiation.  On failure returns NULL and sets @error.
2264  */
2265 MonoType*
2266 mono_reflection_bind_generic_parameters (MonoReflectionType *type, int type_argc, MonoType **types, MonoError *error)
2267 {
2268         MonoClass *klass;
2269         gboolean is_dynamic = FALSE;
2270         MonoClass *geninst;
2271
2272         mono_error_init (error);
2273         
2274         mono_loader_lock ();
2275
2276         if (mono_is_sre_type_builder (mono_object_class (type))) {
2277                 is_dynamic = TRUE;
2278         } else if (mono_is_sre_generic_instance (mono_object_class (type))) {
2279                 /* Does this ever make sense?  what does instantiating a generic instance even mean? */
2280                 g_assert_not_reached ();
2281                 MonoReflectionGenericClass *rgi = (MonoReflectionGenericClass *) type;
2282                 MonoReflectionType *gtd = rgi->generic_type;
2283
2284                 if (mono_is_sre_type_builder (mono_object_class (gtd)))
2285                         is_dynamic = TRUE;
2286         }
2287
2288         MonoType *t = mono_reflection_type_get_handle (type, error);
2289         if (!is_ok (error)) {
2290                 mono_loader_unlock ();
2291                 return NULL;
2292         }
2293
2294         klass = mono_class_from_mono_type (t);
2295         if (!mono_class_is_gtd (klass)) {
2296                 mono_loader_unlock ();
2297                 mono_error_set_type_load_class (error, klass, "Cannot bind generic parameters of a non-generic type");
2298                 return NULL;
2299         }
2300
2301         guint gtd_type_argc = mono_class_get_generic_container (klass)->type_argc;
2302         if (gtd_type_argc != type_argc) {
2303                 mono_loader_unlock ();
2304                 mono_error_set_argument (error, "types", "The generic type definition needs %d type arguments, but was instantiated with %d ", gtd_type_argc, type_argc);
2305                 return NULL;
2306         }
2307
2308
2309         if (klass->wastypebuilder)
2310                 is_dynamic = TRUE;
2311
2312         mono_loader_unlock ();
2313
2314         geninst = mono_class_bind_generic_parameters (klass, type_argc, types, is_dynamic);
2315
2316         return &geninst->byval_arg;
2317 }
2318
2319 MonoClass*
2320 mono_class_bind_generic_parameters (MonoClass *klass, int type_argc, MonoType **types, gboolean is_dynamic)
2321 {
2322         MonoGenericClass *gclass;
2323         MonoGenericInst *inst;
2324
2325         g_assert (mono_class_is_gtd (klass));
2326
2327         inst = mono_metadata_get_generic_inst (type_argc, types);
2328         gclass = mono_metadata_lookup_generic_class (klass, inst, is_dynamic);
2329
2330         return mono_generic_class_get_class (gclass);
2331 }
2332
2333 static MonoReflectionMethod*
2334 reflection_bind_generic_method_parameters (MonoReflectionMethod *rmethod, MonoArray *types, MonoError *error)
2335 {
2336         MonoClass *klass;
2337         MonoMethod *method, *inflated;
2338         MonoMethodInflated *imethod;
2339         MonoGenericContext tmp_context;
2340         MonoGenericInst *ginst;
2341         MonoType **type_argv;
2342         int count, i;
2343
2344         mono_error_init (error);
2345
2346         g_assert (strcmp (rmethod->object.vtable->klass->name, "MethodBuilder"));
2347
2348         method = rmethod->method;
2349
2350         klass = method->klass;
2351
2352         if (method->is_inflated)
2353                 method = ((MonoMethodInflated *) method)->declaring;
2354
2355         count = mono_method_signature (method)->generic_param_count;
2356         if (count != mono_array_length (types))
2357                 return NULL;
2358
2359         type_argv = g_new0 (MonoType *, count);
2360         for (i = 0; i < count; i++) {
2361                 MonoReflectionType *garg = (MonoReflectionType *)mono_array_get (types, gpointer, i);
2362                 type_argv [i] = mono_reflection_type_get_handle (garg, error);
2363                 if (!is_ok (error)) {
2364                         g_free (type_argv);
2365                         return NULL;
2366                 }
2367         }
2368         ginst = mono_metadata_get_generic_inst (count, type_argv);
2369         g_free (type_argv);
2370
2371         tmp_context.class_inst = mono_class_is_ginst (klass) ? mono_class_get_generic_class (klass)->context.class_inst : NULL;
2372         tmp_context.method_inst = ginst;
2373
2374         inflated = mono_class_inflate_generic_method_checked (method, &tmp_context, error);
2375         mono_error_assert_ok (error);
2376         imethod = (MonoMethodInflated *) inflated;
2377
2378         /*FIXME but I think this is no longer necessary*/
2379         if (image_is_dynamic (method->klass->image)) {
2380                 MonoDynamicImage *image = (MonoDynamicImage*)method->klass->image;
2381                 /*
2382                  * This table maps metadata structures representing inflated methods/fields
2383                  * to the reflection objects representing their generic definitions.
2384                  */
2385                 mono_image_lock ((MonoImage*)image);
2386                 mono_g_hash_table_insert (image->generic_def_objects, imethod, rmethod);
2387                 mono_image_unlock ((MonoImage*)image);
2388         }
2389
2390         if (!mono_verifier_is_method_valid_generic_instantiation (inflated)) {
2391                 mono_error_set_argument (error, "typeArguments", "Invalid generic arguments");
2392                 return NULL;
2393         }
2394         
2395         return mono_method_get_object_checked (mono_object_domain (rmethod), inflated, NULL, error);
2396 }
2397
2398 MonoReflectionMethod*
2399 ves_icall_MonoMethod_MakeGenericMethod_impl (MonoReflectionMethod *rmethod, MonoArray *types)
2400 {
2401         MonoError error;
2402         MonoReflectionMethod *result = reflection_bind_generic_method_parameters (rmethod, types, &error);
2403         mono_error_set_pending_exception (&error);
2404         return result;
2405 }
2406
2407
2408 /* SECURITY_ACTION_* are defined in mono/metadata/tabledefs.h */
2409 const static guint32 declsec_flags_map[] = {
2410         0x00000000,                                     /* empty */
2411         MONO_DECLSEC_FLAG_REQUEST,                      /* SECURITY_ACTION_REQUEST                      (x01) */
2412         MONO_DECLSEC_FLAG_DEMAND,                       /* SECURITY_ACTION_DEMAND                       (x02) */
2413         MONO_DECLSEC_FLAG_ASSERT,                       /* SECURITY_ACTION_ASSERT                       (x03) */
2414         MONO_DECLSEC_FLAG_DENY,                         /* SECURITY_ACTION_DENY                         (x04) */
2415         MONO_DECLSEC_FLAG_PERMITONLY,                   /* SECURITY_ACTION_PERMITONLY                   (x05) */
2416         MONO_DECLSEC_FLAG_LINKDEMAND,                   /* SECURITY_ACTION_LINKDEMAND                   (x06) */
2417         MONO_DECLSEC_FLAG_INHERITANCEDEMAND,            /* SECURITY_ACTION_INHERITANCEDEMAND            (x07) */
2418         MONO_DECLSEC_FLAG_REQUEST_MINIMUM,              /* SECURITY_ACTION_REQUEST_MINIMUM              (x08) */
2419         MONO_DECLSEC_FLAG_REQUEST_OPTIONAL,             /* SECURITY_ACTION_REQUEST_OPTIONAL             (x09) */
2420         MONO_DECLSEC_FLAG_REQUEST_REFUSE,               /* SECURITY_ACTION_REQUEST_REFUSE               (x0A) */
2421         MONO_DECLSEC_FLAG_PREJIT_GRANT,                 /* SECURITY_ACTION_PREJIT_GRANT                 (x0B) */
2422         MONO_DECLSEC_FLAG_PREJIT_DENY,                  /* SECURITY_ACTION_PREJIT_DENY                  (x0C) */
2423         MONO_DECLSEC_FLAG_NONCAS_DEMAND,                /* SECURITY_ACTION_NONCAS_DEMAND                (x0D) */
2424         MONO_DECLSEC_FLAG_NONCAS_LINKDEMAND,            /* SECURITY_ACTION_NONCAS_LINKDEMAND            (x0E) */
2425         MONO_DECLSEC_FLAG_NONCAS_INHERITANCEDEMAND,     /* SECURITY_ACTION_NONCAS_INHERITANCEDEMAND     (x0F) */
2426         MONO_DECLSEC_FLAG_LINKDEMAND_CHOICE,            /* SECURITY_ACTION_LINKDEMAND_CHOICE            (x10) */
2427         MONO_DECLSEC_FLAG_INHERITANCEDEMAND_CHOICE,     /* SECURITY_ACTION_INHERITANCEDEMAND_CHOICE     (x11) */
2428         MONO_DECLSEC_FLAG_DEMAND_CHOICE,                /* SECURITY_ACTION_DEMAND_CHOICE                (x12) */
2429 };
2430
2431 /*
2432  * Returns flags that includes all available security action associated to the handle.
2433  * @token: metadata token (either for a class or a method)
2434  * @image: image where resides the metadata.
2435  */
2436 static guint32
2437 mono_declsec_get_flags (MonoImage *image, guint32 token)
2438 {
2439         int index = mono_metadata_declsec_from_index (image, token);
2440         MonoTableInfo *t = &image->tables [MONO_TABLE_DECLSECURITY];
2441         guint32 result = 0;
2442         guint32 action;
2443         int i;
2444
2445         /* HasSecurity can be present for other, not specially encoded, attributes,
2446            e.g. SuppressUnmanagedCodeSecurityAttribute */
2447         if (index < 0)
2448                 return 0;
2449
2450         for (i = index; i < t->rows; i++) {
2451                 guint32 cols [MONO_DECL_SECURITY_SIZE];
2452
2453                 mono_metadata_decode_row (t, i, cols, MONO_DECL_SECURITY_SIZE);
2454                 if (cols [MONO_DECL_SECURITY_PARENT] != token)
2455                         break;
2456
2457                 action = cols [MONO_DECL_SECURITY_ACTION];
2458                 if ((action >= MONO_DECLSEC_ACTION_MIN) && (action <= MONO_DECLSEC_ACTION_MAX)) {
2459                         result |= declsec_flags_map [action];
2460                 } else {
2461                         g_assert_not_reached ();
2462                 }
2463         }
2464         return result;
2465 }
2466
2467 /*
2468  * Get the security actions (in the form of flags) associated with the specified method.
2469  *
2470  * @method: The method for which we want the declarative security flags.
2471  * Return the declarative security flags for the method (only).
2472  *
2473  * Note: To keep MonoMethod size down we do not cache the declarative security flags
2474  *       (except for the stack modifiers which are kept in the MonoJitInfo structure)
2475  */
2476 guint32
2477 mono_declsec_flags_from_method (MonoMethod *method)
2478 {
2479         if (method->flags & METHOD_ATTRIBUTE_HAS_SECURITY) {
2480                 /* FIXME: No cache (for the moment) */
2481                 guint32 idx = mono_method_get_index (method);
2482                 idx <<= MONO_HAS_DECL_SECURITY_BITS;
2483                 idx |= MONO_HAS_DECL_SECURITY_METHODDEF;
2484                 return mono_declsec_get_flags (method->klass->image, idx);
2485         }
2486         return 0;
2487 }
2488
2489 /*
2490  * Get the security actions (in the form of flags) associated with the specified class.
2491  *
2492  * @klass: The class for which we want the declarative security flags.
2493  * Return the declarative security flags for the class.
2494  *
2495  * Note: We cache the flags inside the MonoClass structure as this will get 
2496  *       called very often (at least for each method).
2497  */
2498 guint32
2499 mono_declsec_flags_from_class (MonoClass *klass)
2500 {
2501         if (mono_class_get_flags (klass) & TYPE_ATTRIBUTE_HAS_SECURITY) {
2502                 guint32 flags = mono_class_get_declsec_flags (klass);
2503
2504                 if (!flags) {
2505                         guint32 idx;
2506
2507                         idx = mono_metadata_token_index (klass->type_token);
2508                         idx <<= MONO_HAS_DECL_SECURITY_BITS;
2509                         idx |= MONO_HAS_DECL_SECURITY_TYPEDEF;
2510                         flags = mono_declsec_get_flags (klass->image, idx);
2511                         /* we cache the flags on classes */
2512                         mono_class_set_declsec_flags (klass, flags);
2513                 }
2514                 return flags;
2515         }
2516         return 0;
2517 }
2518
2519 /*
2520  * Get the security actions (in the form of flags) associated with the specified assembly.
2521  *
2522  * @assembly: The assembly for which we want the declarative security flags.
2523  * Return the declarative security flags for the assembly.
2524  */
2525 guint32
2526 mono_declsec_flags_from_assembly (MonoAssembly *assembly)
2527 {
2528         guint32 idx = 1; /* there is only one assembly */
2529         idx <<= MONO_HAS_DECL_SECURITY_BITS;
2530         idx |= MONO_HAS_DECL_SECURITY_ASSEMBLY;
2531         return mono_declsec_get_flags (assembly->image, idx);
2532 }
2533
2534
2535 /*
2536  * Fill actions for the specific index (which may either be an encoded class token or
2537  * an encoded method token) from the metadata image.
2538  * Returns TRUE if some actions requiring code generation are present, FALSE otherwise.
2539  */
2540 static MonoBoolean
2541 fill_actions_from_index (MonoImage *image, guint32 token, MonoDeclSecurityActions* actions,
2542         guint32 id_std, guint32 id_noncas, guint32 id_choice)
2543 {
2544         MonoBoolean result = FALSE;
2545         MonoTableInfo *t;
2546         guint32 cols [MONO_DECL_SECURITY_SIZE];
2547         int index = mono_metadata_declsec_from_index (image, token);
2548         int i;
2549
2550         t  = &image->tables [MONO_TABLE_DECLSECURITY];
2551         for (i = index; i < t->rows; i++) {
2552                 mono_metadata_decode_row (t, i, cols, MONO_DECL_SECURITY_SIZE);
2553
2554                 if (cols [MONO_DECL_SECURITY_PARENT] != token)
2555                         return result;
2556
2557                 /* if present only replace (class) permissions with method permissions */
2558                 /* if empty accept either class or method permissions */
2559                 if (cols [MONO_DECL_SECURITY_ACTION] == id_std) {
2560                         if (!actions->demand.blob) {
2561                                 const char *blob = mono_metadata_blob_heap (image, cols [MONO_DECL_SECURITY_PERMISSIONSET]);
2562                                 actions->demand.index = cols [MONO_DECL_SECURITY_PERMISSIONSET];
2563                                 actions->demand.blob = (char*) (blob + 2);
2564                                 actions->demand.size = mono_metadata_decode_blob_size (blob, &blob);
2565                                 result = TRUE;
2566                         }
2567                 } else if (cols [MONO_DECL_SECURITY_ACTION] == id_noncas) {
2568                         if (!actions->noncasdemand.blob) {
2569                                 const char *blob = mono_metadata_blob_heap (image, cols [MONO_DECL_SECURITY_PERMISSIONSET]);
2570                                 actions->noncasdemand.index = cols [MONO_DECL_SECURITY_PERMISSIONSET];
2571                                 actions->noncasdemand.blob = (char*) (blob + 2);
2572                                 actions->noncasdemand.size = mono_metadata_decode_blob_size (blob, &blob);
2573                                 result = TRUE;
2574                         }
2575                 } else if (cols [MONO_DECL_SECURITY_ACTION] == id_choice) {
2576                         if (!actions->demandchoice.blob) {
2577                                 const char *blob = mono_metadata_blob_heap (image, cols [MONO_DECL_SECURITY_PERMISSIONSET]);
2578                                 actions->demandchoice.index = cols [MONO_DECL_SECURITY_PERMISSIONSET];
2579                                 actions->demandchoice.blob = (char*) (blob + 2);
2580                                 actions->demandchoice.size = mono_metadata_decode_blob_size (blob, &blob);
2581                                 result = TRUE;
2582                         }
2583                 }
2584         }
2585
2586         return result;
2587 }
2588
2589 static MonoBoolean
2590 mono_declsec_get_class_demands_params (MonoClass *klass, MonoDeclSecurityActions* demands, 
2591         guint32 id_std, guint32 id_noncas, guint32 id_choice)
2592 {
2593         guint32 idx = mono_metadata_token_index (klass->type_token);
2594         idx <<= MONO_HAS_DECL_SECURITY_BITS;
2595         idx |= MONO_HAS_DECL_SECURITY_TYPEDEF;
2596         return fill_actions_from_index (klass->image, idx, demands, id_std, id_noncas, id_choice);
2597 }
2598
2599 static MonoBoolean
2600 mono_declsec_get_method_demands_params (MonoMethod *method, MonoDeclSecurityActions* demands, 
2601         guint32 id_std, guint32 id_noncas, guint32 id_choice)
2602 {
2603         guint32 idx = mono_method_get_index (method);
2604         idx <<= MONO_HAS_DECL_SECURITY_BITS;
2605         idx |= MONO_HAS_DECL_SECURITY_METHODDEF;
2606         return fill_actions_from_index (method->klass->image, idx, demands, id_std, id_noncas, id_choice);
2607 }
2608
2609 /*
2610  * Collect all actions (that requires to generate code in mini) assigned for
2611  * the specified method.
2612  * Note: Don't use the content of actions if the function return FALSE.
2613  */
2614 MonoBoolean
2615 mono_declsec_get_demands (MonoMethod *method, MonoDeclSecurityActions* demands)
2616 {
2617         guint32 mask = MONO_DECLSEC_FLAG_DEMAND | MONO_DECLSEC_FLAG_NONCAS_DEMAND | 
2618                 MONO_DECLSEC_FLAG_DEMAND_CHOICE;
2619         MonoBoolean result = FALSE;
2620         guint32 flags;
2621
2622         /* quick exit if no declarative security is present in the metadata */
2623         if (!method->klass->image->tables [MONO_TABLE_DECLSECURITY].rows)
2624                 return FALSE;
2625
2626         /* we want the original as the wrapper is "free" of the security informations */
2627         if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE || method->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED) {
2628                 method = mono_marshal_method_from_wrapper (method);
2629                 if (!method)
2630                         return FALSE;
2631         }
2632
2633         /* First we look for method-level attributes */
2634         if (method->flags & METHOD_ATTRIBUTE_HAS_SECURITY) {
2635                 mono_class_init (method->klass);
2636                 memset (demands, 0, sizeof (MonoDeclSecurityActions));
2637
2638                 result = mono_declsec_get_method_demands_params (method, demands, 
2639                         SECURITY_ACTION_DEMAND, SECURITY_ACTION_NONCASDEMAND, SECURITY_ACTION_DEMANDCHOICE);
2640         }
2641
2642         /* Here we use (or create) the class declarative cache to look for demands */
2643         flags = mono_declsec_flags_from_class (method->klass);
2644         if (flags & mask) {
2645                 if (!result) {
2646                         mono_class_init (method->klass);
2647                         memset (demands, 0, sizeof (MonoDeclSecurityActions));
2648                 }
2649                 result |= mono_declsec_get_class_demands_params (method->klass, demands, 
2650                         SECURITY_ACTION_DEMAND, SECURITY_ACTION_NONCASDEMAND, SECURITY_ACTION_DEMANDCHOICE);
2651         }
2652
2653         /* The boolean return value is used as a shortcut in case nothing needs to
2654            be generated (e.g. LinkDemand[Choice] and InheritanceDemand[Choice]) */
2655         return result;
2656 }
2657
2658
2659 /*
2660  * Collect all Link actions: LinkDemand, NonCasLinkDemand and LinkDemandChoice (2.0).
2661  *
2662  * Note: Don't use the content of actions if the function return FALSE.
2663  */
2664 MonoBoolean
2665 mono_declsec_get_linkdemands (MonoMethod *method, MonoDeclSecurityActions* klass, MonoDeclSecurityActions *cmethod)
2666 {
2667         MonoBoolean result = FALSE;
2668         guint32 flags;
2669
2670         /* quick exit if no declarative security is present in the metadata */
2671         if (!method->klass->image->tables [MONO_TABLE_DECLSECURITY].rows)
2672                 return FALSE;
2673
2674         /* we want the original as the wrapper is "free" of the security informations */
2675         if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE || method->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED) {
2676                 method = mono_marshal_method_from_wrapper (method);
2677                 if (!method)
2678                         return FALSE;
2679         }
2680
2681         /* results are independant - zeroize both */
2682         memset (cmethod, 0, sizeof (MonoDeclSecurityActions));
2683         memset (klass, 0, sizeof (MonoDeclSecurityActions));
2684
2685         /* First we look for method-level attributes */
2686         if (method->flags & METHOD_ATTRIBUTE_HAS_SECURITY) {
2687                 mono_class_init (method->klass);
2688
2689                 result = mono_declsec_get_method_demands_params (method, cmethod, 
2690                         SECURITY_ACTION_LINKDEMAND, SECURITY_ACTION_NONCASLINKDEMAND, SECURITY_ACTION_LINKDEMANDCHOICE);
2691         }
2692
2693         /* Here we use (or create) the class declarative cache to look for demands */
2694         flags = mono_declsec_flags_from_class (method->klass);
2695         if (flags & (MONO_DECLSEC_FLAG_LINKDEMAND | MONO_DECLSEC_FLAG_NONCAS_LINKDEMAND | MONO_DECLSEC_FLAG_LINKDEMAND_CHOICE)) {
2696                 mono_class_init (method->klass);
2697
2698                 result |= mono_declsec_get_class_demands_params (method->klass, klass, 
2699                         SECURITY_ACTION_LINKDEMAND, SECURITY_ACTION_NONCASLINKDEMAND, SECURITY_ACTION_LINKDEMANDCHOICE);
2700         }
2701
2702         return result;
2703 }
2704
2705 /*
2706  * Collect all Inherit actions: InheritanceDemand, NonCasInheritanceDemand and InheritanceDemandChoice (2.0).
2707  *
2708  * @klass       The inherited class - this is the class that provides the security check (attributes)
2709  * @demans      
2710  * return TRUE if inheritance demands (any kind) are present, FALSE otherwise.
2711  * 
2712  * Note: Don't use the content of actions if the function return FALSE.
2713  */
2714 MonoBoolean
2715 mono_declsec_get_inheritdemands_class (MonoClass *klass, MonoDeclSecurityActions* demands)
2716 {
2717         MonoBoolean result = FALSE;
2718         guint32 flags;
2719
2720         /* quick exit if no declarative security is present in the metadata */
2721         if (!klass->image->tables [MONO_TABLE_DECLSECURITY].rows)
2722                 return FALSE;
2723
2724         /* Here we use (or create) the class declarative cache to look for demands */
2725         flags = mono_declsec_flags_from_class (klass);
2726         if (flags & (MONO_DECLSEC_FLAG_INHERITANCEDEMAND | MONO_DECLSEC_FLAG_NONCAS_INHERITANCEDEMAND | MONO_DECLSEC_FLAG_INHERITANCEDEMAND_CHOICE)) {
2727                 mono_class_init (klass);
2728                 memset (demands, 0, sizeof (MonoDeclSecurityActions));
2729
2730                 result |= mono_declsec_get_class_demands_params (klass, demands, 
2731                         SECURITY_ACTION_INHERITDEMAND, SECURITY_ACTION_NONCASINHERITANCE, SECURITY_ACTION_INHERITDEMANDCHOICE);
2732         }
2733
2734         return result;
2735 }
2736
2737 /*
2738  * Collect all Inherit actions: InheritanceDemand, NonCasInheritanceDemand and InheritanceDemandChoice (2.0).
2739  *
2740  * Note: Don't use the content of actions if the function return FALSE.
2741  */
2742 MonoBoolean
2743 mono_declsec_get_inheritdemands_method (MonoMethod *method, MonoDeclSecurityActions* demands)
2744 {
2745         /* quick exit if no declarative security is present in the metadata */
2746         if (!method->klass->image->tables [MONO_TABLE_DECLSECURITY].rows)
2747                 return FALSE;
2748
2749         /* we want the original as the wrapper is "free" of the security informations */
2750         if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE || method->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED) {
2751                 method = mono_marshal_method_from_wrapper (method);
2752                 if (!method)
2753                         return FALSE;
2754         }
2755
2756         if (method->flags & METHOD_ATTRIBUTE_HAS_SECURITY) {
2757                 mono_class_init (method->klass);
2758                 memset (demands, 0, sizeof (MonoDeclSecurityActions));
2759
2760                 return mono_declsec_get_method_demands_params (method, demands, 
2761                         SECURITY_ACTION_INHERITDEMAND, SECURITY_ACTION_NONCASINHERITANCE, SECURITY_ACTION_INHERITDEMANDCHOICE);
2762         }
2763         return FALSE;
2764 }
2765
2766
2767 static MonoBoolean
2768 get_declsec_action (MonoImage *image, guint32 token, guint32 action, MonoDeclSecurityEntry *entry)
2769 {
2770         guint32 cols [MONO_DECL_SECURITY_SIZE];
2771         MonoTableInfo *t;
2772         int i;
2773
2774         int index = mono_metadata_declsec_from_index (image, token);
2775         if (index == -1)
2776                 return FALSE;
2777
2778         t =  &image->tables [MONO_TABLE_DECLSECURITY];
2779         for (i = index; i < t->rows; i++) {
2780                 mono_metadata_decode_row (t, i, cols, MONO_DECL_SECURITY_SIZE);
2781
2782                 /* shortcut - index are ordered */
2783                 if (token != cols [MONO_DECL_SECURITY_PARENT])
2784                         return FALSE;
2785
2786                 if (cols [MONO_DECL_SECURITY_ACTION] == action) {
2787                         const char *metadata = mono_metadata_blob_heap (image, cols [MONO_DECL_SECURITY_PERMISSIONSET]);
2788                         entry->blob = (char*) (metadata + 2);
2789                         entry->size = mono_metadata_decode_blob_size (metadata, &metadata);
2790                         return TRUE;
2791                 }
2792         }
2793
2794         return FALSE;
2795 }
2796
2797 MonoBoolean
2798 mono_declsec_get_method_action (MonoMethod *method, guint32 action, MonoDeclSecurityEntry *entry)
2799 {
2800         if (method->flags & METHOD_ATTRIBUTE_HAS_SECURITY) {
2801                 guint32 idx = mono_method_get_index (method);
2802                 idx <<= MONO_HAS_DECL_SECURITY_BITS;
2803                 idx |= MONO_HAS_DECL_SECURITY_METHODDEF;
2804                 return get_declsec_action (method->klass->image, idx, action, entry);
2805         }
2806         return FALSE;
2807 }
2808
2809 MonoBoolean
2810 mono_declsec_get_class_action (MonoClass *klass, guint32 action, MonoDeclSecurityEntry *entry)
2811 {
2812         /* use cache */
2813         guint32 flags = mono_declsec_flags_from_class (klass);
2814         if (declsec_flags_map [action] & flags) {
2815                 guint32 idx = mono_metadata_token_index (klass->type_token);
2816                 idx <<= MONO_HAS_DECL_SECURITY_BITS;
2817                 idx |= MONO_HAS_DECL_SECURITY_TYPEDEF;
2818                 return get_declsec_action (klass->image, idx, action, entry);
2819         }
2820         return FALSE;
2821 }
2822
2823 MonoBoolean
2824 mono_declsec_get_assembly_action (MonoAssembly *assembly, guint32 action, MonoDeclSecurityEntry *entry)
2825 {
2826         guint32 idx = 1; /* there is only one assembly */
2827         idx <<= MONO_HAS_DECL_SECURITY_BITS;
2828         idx |= MONO_HAS_DECL_SECURITY_ASSEMBLY;
2829
2830         return get_declsec_action (assembly->image, idx, action, entry);
2831 }
2832
2833 gboolean
2834 mono_reflection_call_is_assignable_to (MonoClass *klass, MonoClass *oklass, MonoError *error)
2835 {
2836         MonoObject *res, *exc;
2837         void *params [1];
2838         static MonoMethod *method = NULL;
2839
2840         mono_error_init (error);
2841
2842         if (method == NULL) {
2843                 method = mono_class_get_method_from_name (mono_class_get_type_builder_class (), "IsAssignableTo", 1);
2844                 g_assert (method);
2845         }
2846
2847         /* 
2848          * The result of mono_type_get_object_checked () might be a System.MonoType but we
2849          * need a TypeBuilder so use mono_class_get_ref_info (klass).
2850          */
2851         g_assert (mono_class_get_ref_info (klass));
2852         g_assert (!strcmp (((MonoObject*)(mono_class_get_ref_info (klass)))->vtable->klass->name, "TypeBuilder"));
2853
2854         params [0] = mono_type_get_object_checked (mono_domain_get (), &oklass->byval_arg, error);
2855         return_val_if_nok (error, FALSE);
2856
2857         MonoError inner_error;
2858         res = mono_runtime_try_invoke (method, (MonoObject*)(mono_class_get_ref_info (klass)), params, &exc, &inner_error);
2859
2860         if (exc || !is_ok (&inner_error)) {
2861                 mono_error_cleanup (&inner_error);
2862                 return FALSE;
2863         } else
2864                 return *(MonoBoolean*)mono_object_unbox (res);
2865 }
2866
2867 /**
2868  * mono_reflection_type_get_type:
2869  * @reftype: the System.Type object
2870  *
2871  * Returns the MonoType* associated with the C# System.Type object @reftype.
2872  */
2873 MonoType*
2874 mono_reflection_type_get_type (MonoReflectionType *reftype)
2875 {
2876         g_assert (reftype);
2877
2878         MonoError error;
2879         MonoType *result = mono_reflection_type_get_handle (reftype, &error);
2880         mono_error_assert_ok (&error);
2881         return result;
2882 }
2883
2884 /**
2885  * mono_reflection_assembly_get_assembly:
2886  * @refassembly: the System.Reflection.Assembly object
2887  *
2888  * Returns the MonoAssembly* associated with the C# System.Reflection.Assembly object @refassembly.
2889  */
2890 MonoAssembly*
2891 mono_reflection_assembly_get_assembly (MonoReflectionAssembly *refassembly)
2892 {
2893         g_assert (refassembly);
2894
2895         return refassembly->assembly;
2896 }
2897
2898 /**
2899  * mono_class_from_mono_type_handle:
2900  * @reftype: the System.Type handle
2901  *
2902  * Returns the MonoClass* corresponding to the given type.
2903  */
2904 MonoClass*
2905 mono_class_from_mono_type_handle (MonoReflectionTypeHandle reftype)
2906 {
2907         return mono_class_from_mono_type (MONO_HANDLE_RAW (reftype)->type);
2908 }