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