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