2007-07-03 Jonathan Chambers <joncham@gmail.com>
[mono.git] / mono / metadata / domain.c
1 /*
2  * domain.c: MonoDomain functions
3  *
4  * Author:
5  *      Dietmar Maurer (dietmar@ximian.com)
6  *      Patrik Torstensson
7  *
8  * (C) 2001 Ximian, Inc.
9  */
10
11 #include <config.h>
12 #include <glib.h>
13 #include <string.h>
14 #include <sys/stat.h>
15
16 #include <mono/os/gc_wrapper.h>
17
18 #include <mono/utils/mono-compiler.h>
19 #include <mono/utils/mono-logger.h>
20 #include <mono/metadata/object.h>
21 #include <mono/metadata/object-internals.h>
22 #include <mono/metadata/domain-internals.h>
23 #include <mono/metadata/class-internals.h>
24 #include <mono/metadata/assembly.h>
25 #include <mono/metadata/exception.h>
26 #include <mono/metadata/cil-coff.h>
27 #include <mono/metadata/rawbuffer.h>
28 #include <mono/metadata/metadata-internals.h>
29 #include <mono/metadata/gc-internal.h>
30 #include <mono/metadata/appdomain.h>
31 #include <mono/metadata/mono-debug-debugger.h>
32 #include <mono/metadata/mono-config.h>
33 #include <metadata/threads.h>
34
35 /* #define DEBUG_DOMAIN_UNLOAD */
36
37 /* we need to use both the Tls* functions and __thread because
38  * some archs may generate faster jit code with one meachanism
39  * or the other (we used to do it because tls slots were GC-tracked,
40  * but we can't depend on this).
41  */
42 static guint32 appdomain_thread_id = -1;
43  
44 #ifdef HAVE_KW_THREAD
45 static __thread MonoDomain * tls_appdomain MONO_TLS_FAST;
46 #define GET_APPDOMAIN() tls_appdomain
47 #define SET_APPDOMAIN(x) do { \
48         tls_appdomain = x; \
49         TlsSetValue (appdomain_thread_id, x); \
50 } while (FALSE)
51
52 #else
53
54 #define GET_APPDOMAIN() ((MonoDomain *)TlsGetValue (appdomain_thread_id))
55 #define SET_APPDOMAIN(x) TlsSetValue (appdomain_thread_id, x);
56
57 #endif
58
59 #define GET_APPCONTEXT() (mono_thread_current ()->current_appcontext)
60 #define SET_APPCONTEXT(x) MONO_OBJECT_SETREF (mono_thread_current (), current_appcontext, (x))
61
62 static guint16 appdomain_list_size = 0;
63 static guint16 appdomain_next = 0;
64 static MonoDomain **appdomains_list = NULL;
65
66 #define mono_appdomains_lock() EnterCriticalSection (&appdomains_mutex)
67 #define mono_appdomains_unlock() LeaveCriticalSection (&appdomains_mutex)
68 static CRITICAL_SECTION appdomains_mutex;
69
70 static MonoDomain *mono_root_domain = NULL;
71
72 /* AppConfigInfo: Information about runtime versions supported by an 
73  * aplication.
74  */
75 typedef struct {
76         GSList *supported_runtimes;
77         char *required_runtime;
78         int configuration_count;
79         int startup_count;
80 } AppConfigInfo;
81
82 /*
83  * AotModuleInfo: Contains information about AOT modules.
84  */
85 typedef struct {
86         MonoImage *image;
87         gpointer start, end;
88 } AotModuleInfo;
89
90 static const MonoRuntimeInfo *current_runtime = NULL;
91
92 static MonoJitInfoFindInAot jit_info_find_in_aot_func = NULL;
93
94 /*
95  * Contains information about AOT loaded code.
96  */
97 static MonoJitInfoTable *aot_modules = NULL;
98
99 /* This is the list of runtime versions supported by this JIT.
100  */
101 static const MonoRuntimeInfo supported_runtimes[] = {
102         {"v1.0.3705", "1.0", { {1,0,5000,0}, {7,0,5000,0} }     },
103         {"v1.1.4322", "1.0", { {1,0,5000,0}, {7,0,5000,0} }     },
104         {"v2.0.50215","2.0", { {2,0,0,0},    {8,0,0,0} }        },
105         {"v2.0.50727","2.0", { {2,0,0,0},    {8,0,0,0} }        }
106 };
107
108
109 /* The stable runtime version */
110 #define DEFAULT_RUNTIME_VERSION "v1.1.4322"
111
112 static void
113 get_runtimes_from_exe (const char *exe_file, const MonoRuntimeInfo** runtimes);
114
115 static const MonoRuntimeInfo*
116 get_runtime_by_version (const char *version);
117
118 static MonoImage*
119 mono_jit_info_find_aot_module (guint8* addr);
120
121 guint32
122 mono_domain_get_tls_key (void)
123 {
124         return appdomain_thread_id;
125 }
126
127 gint32
128 mono_domain_get_tls_offset (void)
129 {
130         int offset = -1;
131         MONO_THREAD_VAR_OFFSET (tls_appdomain, offset);
132 /*      __asm ("jmp 1f; .section writetext, \"awx\"; 1: movl $tls_appdomain@ntpoff, %0; jmp 2f; .previous; 2:" 
133                 : "=r" (offset));*/
134         return offset;
135 }
136
137 static MonoJitInfoTable *
138 mono_jit_info_table_new (void)
139 {
140         return g_array_new (FALSE, FALSE, sizeof (gpointer));
141 }
142
143 static void
144 mono_jit_info_table_free (MonoJitInfoTable *table)
145 {
146         g_array_free (table, TRUE);
147 }
148
149 static int
150 mono_jit_info_table_index (MonoJitInfoTable *table, char *addr)
151 {
152         int left = 0, right = table->len;
153
154         while (left < right) {
155                 int pos = (left + right) / 2;
156                 MonoJitInfo *ji = g_array_index (table, gpointer, pos);
157                 char *start = ji->code_start;
158                 char *end = start + ji->code_size;
159
160                 if (addr < start)
161                         right = pos;
162                 else if (addr >= end) 
163                         left = pos + 1;
164                 else
165                         return pos;
166         }
167
168         return left;
169 }
170
171 MonoJitInfo *
172 mono_jit_info_table_find (MonoDomain *domain, char *addr)
173 {
174         MonoJitInfoTable *table = domain->jit_info_table;
175         MonoJitInfo *ji;
176         guint left = 0, right;
177
178         mono_domain_lock (domain);
179
180         right = table->len;
181         while (left < right) {
182                 guint pos = (left + right) / 2;
183                 ji = g_array_index (table, gpointer, pos);
184
185                 if (addr < (char*)ji->code_start)
186                         right = pos;
187                 else if (addr >= (char*)ji->code_start + ji->code_size) 
188                         left = pos + 1;
189                 else {
190                         mono_domain_unlock (domain);
191                         return ji;
192                 }
193         }
194         mono_domain_unlock (domain);
195
196         /* maybe it is shared code, so we also search in the root domain */
197         ji = NULL;
198         if (domain != mono_root_domain)
199                 ji = mono_jit_info_table_find (mono_root_domain, addr);
200
201         if (ji == NULL) {
202                 /* Maybe its an AOT module */
203                 MonoImage *image = mono_jit_info_find_aot_module ((guint8*)addr);
204                 if (image)
205                         ji = jit_info_find_in_aot_func (domain, image, addr);
206         }
207         
208         return ji;
209 }
210
211 void
212 mono_jit_info_table_add (MonoDomain *domain, MonoJitInfo *ji)
213 {
214         MonoJitInfoTable *table = domain->jit_info_table;
215         gpointer start = ji->code_start;
216         int pos;
217
218         mono_domain_lock (domain);
219         pos = mono_jit_info_table_index (table, start);
220
221         g_array_insert_val (table, pos, ji);
222         mono_domain_unlock (domain);
223 }
224
225 void
226 mono_jit_info_table_remove (MonoDomain *domain, MonoJitInfo *ji)
227 {
228         MonoJitInfoTable *table = domain->jit_info_table;
229         gpointer start = ji->code_start;
230         int pos;
231
232         mono_domain_lock (domain);
233         pos = mono_jit_info_table_index (table, start);
234         if (g_array_index (table, gpointer, pos) != ji) {
235                 MonoJitInfo *ji2 = g_array_index (table, gpointer, pos);
236                 g_assert (ji == ji2);
237         }
238         g_assert (g_array_index (table, gpointer, pos) == ji);
239
240         g_array_remove_index (table, pos);
241         mono_domain_unlock (domain);
242 }       
243
244 static int
245 aot_info_table_index (MonoJitInfoTable *table, char *addr)
246 {
247         int left = 0, right = table->len;
248
249         while (left < right) {
250                 int pos = (left + right) / 2;
251                 AotModuleInfo *ainfo = g_array_index (table, gpointer, pos);
252                 char *start = ainfo->start;
253                 char *end = ainfo->end;
254
255                 if (addr < start)
256                         right = pos;
257                 else if (addr >= end) 
258                         left = pos + 1;
259                 else
260                         return pos;
261         }
262
263         return left;
264 }
265
266 void
267 mono_jit_info_add_aot_module (MonoImage *image, gpointer start, gpointer end)
268 {
269         AotModuleInfo *ainfo = g_new0 (AotModuleInfo, 1);
270         int pos;
271
272         ainfo->image = image;
273         ainfo->start = start;
274         ainfo->end = end;
275
276         mono_appdomains_lock ();
277
278         if (!aot_modules)
279                 aot_modules = mono_jit_info_table_new ();
280
281         pos = aot_info_table_index (aot_modules, start);
282
283         g_array_insert_val (aot_modules, pos, ainfo);
284
285         mono_appdomains_unlock ();
286 }
287
288 static MonoImage*
289 mono_jit_info_find_aot_module (guint8* addr)
290 {
291         guint left = 0, right;
292
293         if (!aot_modules)
294                 return NULL;
295
296         mono_appdomains_lock ();
297
298         right = aot_modules->len;
299         while (left < right) {
300                 guint pos = (left + right) / 2;
301                 AotModuleInfo *ai = g_array_index (aot_modules, gpointer, pos);
302
303                 if (addr < (guint8*)ai->start)
304                         right = pos;
305                 else if (addr >= (guint8*)ai->end)
306                         left = pos + 1;
307                 else {
308                         mono_appdomains_unlock ();
309                         return ai->image;
310                 }
311         }
312
313         mono_appdomains_unlock ();
314
315         return NULL;
316 }
317
318 void
319 mono_install_jit_info_find_in_aot (MonoJitInfoFindInAot func)
320 {
321         jit_info_find_in_aot_func = func;
322 }
323
324 gpointer
325 mono_jit_info_get_code_start (MonoJitInfo* ji)
326 {
327         return ji->code_start;
328 }
329
330 int
331 mono_jit_info_get_code_size (MonoJitInfo* ji)
332 {
333         return ji->code_size;
334 }
335
336 MonoMethod*
337 mono_jit_info_get_method (MonoJitInfo* ji)
338 {
339         return ji->method;
340 }
341
342 static gpointer
343 jit_info_key_extract (gpointer value)
344 {
345         MonoJitInfo *info = (MonoJitInfo*)value;
346
347         return info->method;
348 }
349
350 static gpointer*
351 jit_info_next_value (gpointer value)
352 {
353         MonoJitInfo *info = (MonoJitInfo*)value;
354
355         return (gpointer*)&info->next_jit_code_hash;
356 }
357
358 void
359 mono_jit_code_hash_init (MonoInternalHashTable *jit_code_hash)
360 {
361         mono_internal_hash_table_init (jit_code_hash,
362                                        mono_aligned_addr_hash,
363                                        jit_info_key_extract,
364                                        jit_info_next_value);
365 }
366
367 /**
368  * mono_string_equal:
369  * @s1: First string to compare
370  * @s2: Second string to compare
371  *
372  * Returns FALSE if the strings differ.
373  */
374 gboolean
375 mono_string_equal (MonoString *s1, MonoString *s2)
376 {
377         int l1 = mono_string_length (s1);
378         int l2 = mono_string_length (s2);
379
380         if (s1 == s2)
381                 return TRUE;
382         if (l1 != l2)
383                 return FALSE;
384
385         return memcmp (mono_string_chars (s1), mono_string_chars (s2), l1 * 2) == 0; 
386 }
387
388 /**
389  * mono_string_hash:
390  * @s: the string to hash
391  *
392  * Returns the hash for the string.
393  */
394 guint
395 mono_string_hash (MonoString *s)
396 {
397         const guint16 *p = mono_string_chars (s);
398         int i, len = mono_string_length (s);
399         guint h = 0;
400
401         for (i = 0; i < len; i++) {
402                 h = (h << 5) - h + *p;
403                 p++;
404         }
405
406         return h;       
407 }
408
409 static gboolean
410 mono_ptrarray_equal (gpointer *s1, gpointer *s2)
411 {
412         int len = GPOINTER_TO_INT (s1 [0]);
413         if (len != GPOINTER_TO_INT (s2 [0]))
414                 return FALSE;
415
416         return memcmp (s1 + 1, s2 + 1, len * sizeof(gpointer)) == 0; 
417 }
418
419 static guint
420 mono_ptrarray_hash (gpointer *s)
421 {
422         int i;
423         int len = GPOINTER_TO_INT (s [0]);
424         guint hash = 0;
425         
426         for (i = 1; i < len; i++)
427                 hash += GPOINTER_TO_UINT (s [i]);
428
429         return hash;    
430 }
431
432 /*
433  * Allocate an id for domain and set domain->domain_id.
434  * LOCKING: must be called while holding appdomains_mutex.
435  * We try to assign low numbers to the domain, so it can be used
436  * as an index in data tables to lookup domain-specific info
437  * with minimal memory overhead. We also try not to reuse the
438  * same id too quickly (to help debugging).
439  */
440 static int
441 domain_id_alloc (MonoDomain *domain)
442 {
443         int id = -1, i;
444         if (!appdomains_list) {
445                 appdomain_list_size = 2;
446                 appdomains_list = mono_gc_alloc_fixed (appdomain_list_size * sizeof (void*), NULL);
447         }
448         for (i = appdomain_next; i < appdomain_list_size; ++i) {
449                 if (!appdomains_list [i]) {
450                         id = i;
451                         break;
452                 }
453         }
454         if (id == -1) {
455                 for (i = 0; i < appdomain_next; ++i) {
456                         if (!appdomains_list [i]) {
457                                 id = i;
458                                 break;
459                         }
460                 }
461         }
462         if (id == -1) {
463                 MonoDomain **new_list;
464                 int new_size = appdomain_list_size * 2;
465                 if (new_size >= (1 << 16))
466                         g_assert_not_reached ();
467                 id = appdomain_list_size;
468                 new_list = mono_gc_alloc_fixed (new_size * sizeof (void*), NULL);
469                 memcpy (new_list, appdomains_list, appdomain_list_size * sizeof (void*));
470                 mono_gc_free_fixed (appdomains_list);
471                 appdomains_list = new_list;
472                 appdomain_list_size = new_size;
473         }
474         domain->domain_id = id;
475         appdomains_list [id] = domain;
476         appdomain_next++;
477         if (appdomain_next > appdomain_list_size)
478                 appdomain_next = 0;
479         return id;
480 }
481
482 static guint32 domain_gc_bitmap [sizeof(MonoDomain)/4/32 + 1];
483 static gpointer domain_gc_desc = NULL;
484 static guint32 domain_shadow_serial = 0L;
485
486 MonoDomain *
487 mono_domain_create (void)
488 {
489         MonoDomain *domain;
490         guint32 shadow_serial;
491   
492         mono_appdomains_lock ();
493         shadow_serial = domain_shadow_serial++;
494   
495         if (!domain_gc_desc) {
496                 unsigned int i, bit = 0;
497                 for (i = G_STRUCT_OFFSET (MonoDomain, MONO_DOMAIN_FIRST_OBJECT); i < G_STRUCT_OFFSET (MonoDomain, MONO_DOMAIN_FIRST_GC_TRACKED); i += sizeof (gpointer)) {
498                         bit = i / sizeof (gpointer);
499                         domain_gc_bitmap [bit / 32] |= 1 << (bit % 32);
500                 }
501                 domain_gc_desc = mono_gc_make_descr_from_bitmap (domain_gc_bitmap, bit + 1);
502         }
503         mono_appdomains_unlock ();
504
505         domain = mono_gc_alloc_fixed (sizeof (MonoDomain), domain_gc_desc);
506         domain->shadow_serial = shadow_serial;
507         domain->domain = NULL;
508         domain->setup = NULL;
509         domain->friendly_name = NULL;
510         domain->search_path = NULL;
511
512         domain->mp = mono_mempool_new ();
513         domain->code_mp = mono_code_manager_new ();
514         domain->env = mono_g_hash_table_new_type ((GHashFunc)mono_string_hash, (GCompareFunc)mono_string_equal, MONO_HASH_KEY_VALUE_GC);
515         domain->domain_assemblies = NULL;
516         domain->class_vtable_hash = g_hash_table_new (mono_aligned_addr_hash, NULL);
517         domain->proxy_vtable_hash = g_hash_table_new ((GHashFunc)mono_ptrarray_hash, (GCompareFunc)mono_ptrarray_equal);
518         domain->static_data_array = NULL;
519         mono_jit_code_hash_init (&domain->jit_code_hash);
520         domain->ldstr_table = mono_g_hash_table_new ((GHashFunc)mono_string_hash, (GCompareFunc)mono_string_equal);
521         domain->jit_info_table = mono_jit_info_table_new ();
522         domain->class_init_trampoline_hash = g_hash_table_new (mono_aligned_addr_hash, NULL);
523         domain->jump_trampoline_hash = g_hash_table_new (mono_aligned_addr_hash, NULL);
524         domain->finalizable_objects_hash = g_hash_table_new (mono_aligned_addr_hash, NULL);
525         domain->jit_trampoline_hash = g_hash_table_new (mono_aligned_addr_hash, NULL);
526         domain->delegate_trampoline_hash = g_hash_table_new (mono_aligned_addr_hash, NULL);
527
528         InitializeCriticalSection (&domain->lock);
529         InitializeCriticalSection (&domain->assemblies_lock);
530
531         mono_appdomains_lock ();
532         domain_id_alloc (domain);
533         mono_appdomains_unlock ();
534
535         return domain;
536 }
537
538 /**
539  * mono_init_internal:
540  * 
541  * Creates the initial application domain and initializes the mono_defaults
542  * structure.
543  * This function is guaranteed to not run any IL code.
544  * If exe_filename is not NULL, the method will determine the required runtime
545  * from the exe configuration file or the version PE field.
546  * If runtime_version is not NULL, that runtime version will be used.
547  * Either exe_filename or runtime_version must be provided.
548  *
549  * Returns: the initial domain.
550  */
551 static MonoDomain *
552 mono_init_internal (const char *filename, const char *exe_filename, const char *runtime_version)
553 {
554         static MonoDomain *domain = NULL;
555         MonoAssembly *ass = NULL;
556         MonoImageOpenStatus status = MONO_IMAGE_OK;
557         const MonoRuntimeInfo* runtimes [G_N_ELEMENTS (supported_runtimes) + 1];
558         int n;
559
560         if (domain)
561                 g_assert_not_reached ();
562
563         MONO_GC_PRE_INIT ();
564
565         appdomain_thread_id = TlsAlloc ();
566
567         InitializeCriticalSection (&appdomains_mutex);
568
569         mono_metadata_init ();
570         mono_raw_buffer_init ();
571         mono_images_init ();
572         mono_assemblies_init ();
573         mono_classes_init ();
574         mono_loader_init ();
575         mono_reflection_init ();
576
577         /* FIXME: When should we release this memory? */
578         MONO_GC_REGISTER_ROOT (appdomains_list);
579
580         domain = mono_domain_create ();
581         mono_root_domain = domain;
582
583         SET_APPDOMAIN (domain);
584         
585         /* Get a list of runtimes supported by the exe */
586         if (exe_filename != NULL) {
587                 get_runtimes_from_exe (exe_filename, runtimes);
588         } else if (runtime_version != NULL) {
589                 runtimes [0] = get_runtime_by_version (runtime_version);
590                 runtimes [1] = NULL;
591         }
592
593         if (runtimes [0] == NULL) {
594                 const MonoRuntimeInfo *default_runtime = get_runtime_by_version (DEFAULT_RUNTIME_VERSION);
595                 runtimes [0] = default_runtime;
596                 runtimes [1] = NULL;
597                 g_print ("WARNING: The runtime version supported by this application is unavailable.\n");
598                 g_print ("Using default runtime: %s\n", default_runtime->runtime_version);
599         }
600
601         /* The selected runtime will be the first one for which there is a mscrolib.dll */
602         for (n = 0; runtimes [n] != NULL && ass == NULL; n++) {
603                 current_runtime = runtimes [n];
604                 ass = mono_assembly_load_corlib (current_runtime, &status);
605                 if (status != MONO_IMAGE_OK && status != MONO_IMAGE_ERROR_ERRNO)
606                         break;
607         }
608
609         if ((status != MONO_IMAGE_OK) || (ass == NULL)) {
610                 switch (status){
611                 case MONO_IMAGE_ERROR_ERRNO: {
612                         char *corlib_file = g_build_filename (mono_assembly_getrootdir (), "mono", current_runtime->framework_version, "mscorlib.dll", NULL);
613                         g_print ("The assembly mscorlib.dll was not found or could not be loaded.\n");
614                         g_print ("It should have been installed in the `%s' directory.\n", corlib_file);
615                         g_free (corlib_file);
616                         break;
617                 }
618                 case MONO_IMAGE_IMAGE_INVALID:
619                         g_print ("The file %s/mscorlib.dll is an invalid CIL image\n",
620                                  mono_assembly_getrootdir ());
621                         break;
622                 case MONO_IMAGE_MISSING_ASSEMBLYREF:
623                         g_print ("Missing assembly reference in %s/mscorlib.dll\n",
624                                  mono_assembly_getrootdir ());
625                         break;
626                 case MONO_IMAGE_OK:
627                         /* to suppress compiler warning */
628                         break;
629                 }
630                 
631                 exit (1);
632         }
633         mono_defaults.corlib = mono_assembly_get_image (ass);
634
635         mono_defaults.object_class = mono_class_from_name (
636                 mono_defaults.corlib, "System", "Object");
637         g_assert (mono_defaults.object_class != 0);
638
639         mono_defaults.void_class = mono_class_from_name (
640                 mono_defaults.corlib, "System", "Void");
641         g_assert (mono_defaults.void_class != 0);
642
643         mono_defaults.boolean_class = mono_class_from_name (
644                 mono_defaults.corlib, "System", "Boolean");
645         g_assert (mono_defaults.boolean_class != 0);
646
647         mono_defaults.byte_class = mono_class_from_name (
648                 mono_defaults.corlib, "System", "Byte");
649         g_assert (mono_defaults.byte_class != 0);
650
651         mono_defaults.sbyte_class = mono_class_from_name (
652                 mono_defaults.corlib, "System", "SByte");
653         g_assert (mono_defaults.sbyte_class != 0);
654
655         mono_defaults.int16_class = mono_class_from_name (
656                 mono_defaults.corlib, "System", "Int16");
657         g_assert (mono_defaults.int16_class != 0);
658
659         mono_defaults.uint16_class = mono_class_from_name (
660                 mono_defaults.corlib, "System", "UInt16");
661         g_assert (mono_defaults.uint16_class != 0);
662
663         mono_defaults.int32_class = mono_class_from_name (
664                 mono_defaults.corlib, "System", "Int32");
665         g_assert (mono_defaults.int32_class != 0);
666
667         mono_defaults.uint32_class = mono_class_from_name (
668                 mono_defaults.corlib, "System", "UInt32");
669         g_assert (mono_defaults.uint32_class != 0);
670
671         mono_defaults.uint_class = mono_class_from_name (
672                 mono_defaults.corlib, "System", "UIntPtr");
673         g_assert (mono_defaults.uint_class != 0);
674
675         mono_defaults.int_class = mono_class_from_name (
676                 mono_defaults.corlib, "System", "IntPtr");
677         g_assert (mono_defaults.int_class != 0);
678
679         mono_defaults.int64_class = mono_class_from_name (
680                 mono_defaults.corlib, "System", "Int64");
681         g_assert (mono_defaults.int64_class != 0);
682
683         mono_defaults.uint64_class = mono_class_from_name (
684                 mono_defaults.corlib, "System", "UInt64");
685         g_assert (mono_defaults.uint64_class != 0);
686
687         mono_defaults.single_class = mono_class_from_name (
688                 mono_defaults.corlib, "System", "Single");
689         g_assert (mono_defaults.single_class != 0);
690
691         mono_defaults.double_class = mono_class_from_name (
692                 mono_defaults.corlib, "System", "Double");
693         g_assert (mono_defaults.double_class != 0);
694
695         mono_defaults.char_class = mono_class_from_name (
696                 mono_defaults.corlib, "System", "Char");
697         g_assert (mono_defaults.char_class != 0);
698
699         mono_defaults.string_class = mono_class_from_name (
700                 mono_defaults.corlib, "System", "String");
701         g_assert (mono_defaults.string_class != 0);
702
703         mono_defaults.enum_class = mono_class_from_name (
704                 mono_defaults.corlib, "System", "Enum");
705         g_assert (mono_defaults.enum_class != 0);
706
707         mono_defaults.array_class = mono_class_from_name (
708                 mono_defaults.corlib, "System", "Array");
709         g_assert (mono_defaults.array_class != 0);
710
711         mono_defaults.delegate_class = mono_class_from_name (
712                 mono_defaults.corlib, "System", "Delegate");
713         g_assert (mono_defaults.delegate_class != 0 );
714
715         mono_defaults.multicastdelegate_class = mono_class_from_name (
716                 mono_defaults.corlib, "System", "MulticastDelegate");
717         g_assert (mono_defaults.multicastdelegate_class != 0 );
718
719         mono_defaults.asyncresult_class = mono_class_from_name (
720                 mono_defaults.corlib, "System.Runtime.Remoting.Messaging", 
721                 "AsyncResult");
722         g_assert (mono_defaults.asyncresult_class != 0 );
723
724         mono_defaults.waithandle_class = mono_class_from_name (
725                 mono_defaults.corlib, "System.Threading", "WaitHandle");
726         g_assert (mono_defaults.waithandle_class != 0 );
727
728         mono_defaults.typehandle_class = mono_class_from_name (
729                 mono_defaults.corlib, "System", "RuntimeTypeHandle");
730         g_assert (mono_defaults.typehandle_class != 0);
731
732         mono_defaults.methodhandle_class = mono_class_from_name (
733                 mono_defaults.corlib, "System", "RuntimeMethodHandle");
734         g_assert (mono_defaults.methodhandle_class != 0);
735
736         mono_defaults.fieldhandle_class = mono_class_from_name (
737                 mono_defaults.corlib, "System", "RuntimeFieldHandle");
738         g_assert (mono_defaults.fieldhandle_class != 0);
739
740         mono_defaults.systemtype_class = mono_class_from_name (
741                 mono_defaults.corlib, "System", "Type");
742         g_assert (mono_defaults.systemtype_class != 0);
743
744         mono_defaults.monotype_class = mono_class_from_name (
745                 mono_defaults.corlib, "System", "MonoType");
746         g_assert (mono_defaults.monotype_class != 0);
747
748         mono_defaults.exception_class = mono_class_from_name (
749                 mono_defaults.corlib, "System", "Exception");
750         g_assert (mono_defaults.exception_class != 0);
751
752         mono_defaults.threadabortexception_class = mono_class_from_name (
753                 mono_defaults.corlib, "System.Threading", "ThreadAbortException");
754         g_assert (mono_defaults.threadabortexception_class != 0);
755
756         mono_defaults.thread_class = mono_class_from_name (
757                 mono_defaults.corlib, "System.Threading", "Thread");
758         g_assert (mono_defaults.thread_class != 0);
759
760         mono_defaults.appdomain_class = mono_class_from_name (
761                 mono_defaults.corlib, "System", "AppDomain");
762         g_assert (mono_defaults.appdomain_class != 0);
763
764         mono_defaults.transparent_proxy_class = mono_class_from_name (
765                 mono_defaults.corlib, "System.Runtime.Remoting.Proxies", "TransparentProxy");
766         g_assert (mono_defaults.transparent_proxy_class != 0);
767
768         mono_defaults.real_proxy_class = mono_class_from_name (
769                 mono_defaults.corlib, "System.Runtime.Remoting.Proxies", "RealProxy");
770         g_assert (mono_defaults.real_proxy_class != 0);
771
772         mono_defaults.mono_method_message_class = mono_class_from_name (
773                 mono_defaults.corlib, "System.Runtime.Remoting.Messaging", "MonoMethodMessage");
774         g_assert (mono_defaults.mono_method_message_class != 0);
775
776         mono_defaults.field_info_class = mono_class_from_name (
777                 mono_defaults.corlib, "System.Reflection", "FieldInfo");
778         g_assert (mono_defaults.field_info_class != 0);
779
780         mono_defaults.method_info_class = mono_class_from_name (
781                 mono_defaults.corlib, "System.Reflection", "MethodInfo");
782         g_assert (mono_defaults.method_info_class != 0);
783
784         mono_defaults.stringbuilder_class = mono_class_from_name (
785                 mono_defaults.corlib, "System.Text", "StringBuilder");
786         g_assert (mono_defaults.stringbuilder_class != 0);
787
788         mono_defaults.math_class = mono_class_from_name (
789                 mono_defaults.corlib, "System", "Math");
790         g_assert (mono_defaults.math_class != 0);
791
792         mono_defaults.stack_frame_class = mono_class_from_name (
793                 mono_defaults.corlib, "System.Diagnostics", "StackFrame");
794         g_assert (mono_defaults.stack_frame_class != 0);
795
796         mono_defaults.stack_trace_class = mono_class_from_name (
797                 mono_defaults.corlib, "System.Diagnostics", "StackTrace");
798         g_assert (mono_defaults.stack_trace_class != 0);
799
800         mono_defaults.marshal_class = mono_class_from_name (
801                 mono_defaults.corlib, "System.Runtime.InteropServices", "Marshal");
802         g_assert (mono_defaults.marshal_class != 0);
803
804         mono_defaults.iserializeable_class = mono_class_from_name (
805                 mono_defaults.corlib, "System.Runtime.Serialization", "ISerializable");
806         g_assert (mono_defaults.iserializeable_class != 0);
807
808         mono_defaults.serializationinfo_class = mono_class_from_name (
809                 mono_defaults.corlib, "System.Runtime.Serialization", "SerializationInfo");
810         g_assert (mono_defaults.serializationinfo_class != 0);
811
812         mono_defaults.streamingcontext_class = mono_class_from_name (
813                 mono_defaults.corlib, "System.Runtime.Serialization", "StreamingContext");
814         g_assert (mono_defaults.streamingcontext_class != 0);
815
816         mono_defaults.typed_reference_class =  mono_class_from_name (
817                 mono_defaults.corlib, "System", "TypedReference");
818         g_assert (mono_defaults.typed_reference_class != 0);
819
820         mono_defaults.argumenthandle_class =  mono_class_from_name (
821                 mono_defaults.corlib, "System", "RuntimeArgumentHandle");
822         g_assert (mono_defaults.argumenthandle_class != 0);
823
824         mono_defaults.marshalbyrefobject_class =  mono_class_from_name (
825                 mono_defaults.corlib, "System", "MarshalByRefObject");
826         g_assert (mono_defaults.marshalbyrefobject_class != 0);
827
828         mono_defaults.monitor_class =  mono_class_from_name (
829                 mono_defaults.corlib, "System.Threading", "Monitor");
830         g_assert (mono_defaults.monitor_class != 0);
831
832         mono_defaults.iremotingtypeinfo_class = mono_class_from_name (
833                 mono_defaults.corlib, "System.Runtime.Remoting", "IRemotingTypeInfo");
834         g_assert (mono_defaults.iremotingtypeinfo_class != 0);
835
836         mono_defaults.runtimesecurityframe_class = mono_class_from_name (
837                 mono_defaults.corlib, "System.Security", "RuntimeSecurityFrame");
838
839         mono_defaults.executioncontext_class = mono_class_from_name (
840                 mono_defaults.corlib, "System.Threading", "ExecutionContext");
841
842         mono_defaults.internals_visible_class = mono_class_from_name (
843                 mono_defaults.corlib, "System.Runtime.CompilerServices", "InternalsVisibleToAttribute");
844
845         mono_defaults.safehandle_class = mono_class_from_name (
846                 mono_defaults.corlib, "System.Runtime.InteropServices", "SafeHandle");
847
848         mono_defaults.handleref_class = mono_class_from_name (
849                 mono_defaults.corlib, "System.Runtime.InteropServices", "HandleRef");
850
851         mono_defaults.attribute_class = mono_class_from_name (
852                 mono_defaults.corlib, "System", "Attribute");
853
854         mono_defaults.customattribute_data_class = mono_class_from_name (
855                 mono_defaults.corlib, "System.Reflection", "CustomAttributeData");
856
857         /* these are initialized lazily when COM features are used */
858         mono_defaults.variant_class = NULL;
859         mono_defaults.com_object_class = NULL;
860         mono_defaults.com_interop_proxy_class = NULL;
861         mono_defaults.iunknown_class = NULL;
862         mono_defaults.idispatch_class = NULL;
863
864         /*
865          * Note that mono_defaults.generic_*_class is only non-NULL if we're
866          * using the 2.0 corlib.
867          */
868         mono_class_init (mono_defaults.array_class);
869         mono_defaults.generic_nullable_class = mono_class_from_name (
870                 mono_defaults.corlib, "System", "Nullable`1");
871         mono_defaults.generic_ilist_class = mono_class_from_name (
872                 mono_defaults.corlib, "System.Collections.Generic", "IList`1");
873
874         domain->friendly_name = g_path_get_basename (filename);
875
876         return domain;
877 }
878
879 /**
880  * mono_init:
881  * 
882  * Creates the initial application domain and initializes the mono_defaults
883  * structure.
884  * This function is guaranteed to not run any IL code.
885  * The runtime is initialized using the default runtime version.
886  *
887  * Returns: the initial domain.
888  */
889 MonoDomain *
890 mono_init (const char *domain_name)
891 {
892         return mono_init_internal (domain_name, NULL, DEFAULT_RUNTIME_VERSION);
893 }
894
895 /**
896  * mono_init_from_assembly:
897  * 
898  * Creates the initial application domain and initializes the mono_defaults
899  * structure.
900  * This function is guaranteed to not run any IL code.
901  * The runtime is initialized using the runtime version required by the
902  * provided executable. The version is determined by looking at the exe 
903  * configuration file and the version PE field)
904  *
905  * Returns: the initial domain.
906  */
907 MonoDomain *
908 mono_init_from_assembly (const char *domain_name, const char *filename)
909 {
910         return mono_init_internal (domain_name, filename, NULL);
911 }
912
913 /**
914  * mono_init_version:
915  * 
916  * Creates the initial application domain and initializes the mono_defaults
917  * structure.
918  * This function is guaranteed to not run any IL code.
919  * The runtime is initialized using the provided rutime version.
920  *
921  * Returns: the initial domain.
922  */
923 MonoDomain *
924 mono_init_version (const char *domain_name, const char *version)
925 {
926         return mono_init_internal (domain_name, NULL, version);
927 }
928
929 /**
930  * mono_init_com_types:
931  *
932  * Initializes all types needed for COM Interop in mono_defaults structure. 
933  */
934 void 
935 mono_init_com_types (void)
936 {
937         static gboolean initialized = FALSE;
938
939         if (initialized)
940                 return;
941         
942         /* FIXME: do I need some threading protection here */
943
944         g_assert (mono_defaults.corlib);
945
946         mono_defaults.variant_class = mono_class_from_name (
947                 mono_defaults.corlib, "System", "Variant");
948         g_assert (mono_defaults.variant_class != 0);
949
950         mono_defaults.com_object_class = mono_class_from_name (
951                 mono_defaults.corlib, "System", "__ComObject");
952         g_assert (mono_defaults.com_object_class != 0);
953
954         mono_defaults.com_interop_proxy_class = mono_class_from_name (
955                 mono_defaults.corlib, "Mono.Interop", "ComInteropProxy");
956         g_assert (mono_defaults.com_interop_proxy_class != 0);
957
958         mono_defaults.iunknown_class = mono_class_from_name (
959                 mono_defaults.corlib, "Mono.Interop", "IUnknown");
960         g_assert (mono_defaults.iunknown_class != 0);
961
962         mono_defaults.idispatch_class = mono_class_from_name (
963                 mono_defaults.corlib, "Mono.Interop", "IDispatch");
964         g_assert (mono_defaults.idispatch_class != 0);
965
966         initialized = TRUE;
967 }
968
969 /**
970  * mono_cleanup:
971  *
972  * Cleans up all metadata modules. 
973  */
974 void
975 mono_cleanup (void)
976 {
977         mono_loader_cleanup ();
978         mono_classes_cleanup ();
979         mono_assemblies_cleanup ();
980         mono_images_cleanup ();
981         mono_raw_buffer_cleanup ();
982         mono_metadata_cleanup ();
983
984         TlsFree (appdomain_thread_id);
985         DeleteCriticalSection (&appdomains_mutex);
986 }
987
988 /**
989  * mono_get_root_domain:
990  *
991  * The root AppDomain is the initial domain created by the runtime when it is
992  * initialized.  Programs execute on this AppDomain, but can create new ones
993  * later.   Currently there is no unmanaged API to create new AppDomains, this
994  * must be done from managed code.
995  *
996  * Returns: the root appdomain, to obtain the current domain, use mono_domain_get ()
997  */
998 MonoDomain*
999 mono_get_root_domain (void)
1000 {
1001         return mono_root_domain;
1002 }
1003
1004 /**
1005  * mono_domain_get:
1006  *
1007  * Returns: the current domain, to obtain the root domain use
1008  * mono_get_root_domain().
1009  */
1010 MonoDomain *
1011 mono_domain_get ()
1012 {
1013         return GET_APPDOMAIN ();
1014 }
1015
1016 /**
1017  * mono_domain_set_internal:
1018  * @domain: the new domain
1019  *
1020  * Sets the current domain to @domain.
1021  */
1022 void
1023 mono_domain_set_internal (MonoDomain *domain)
1024 {
1025         SET_APPDOMAIN (domain);
1026         SET_APPCONTEXT (domain->default_context);
1027 }
1028
1029 void
1030 mono_domain_foreach (MonoDomainFunc func, gpointer user_data)
1031 {
1032         int i, size;
1033         MonoDomain **copy;
1034
1035         /*
1036          * Create a copy of the data to avoid calling the user callback
1037          * inside the lock because that could lead to deadlocks.
1038          * We can do this because this function is not perf. critical.
1039          */
1040         mono_appdomains_lock ();
1041         size = appdomain_list_size;
1042         copy = mono_gc_alloc_fixed (appdomain_list_size * sizeof (void*), NULL);
1043         memcpy (copy, appdomains_list, appdomain_list_size * sizeof (void*));
1044         mono_appdomains_unlock ();
1045
1046         for (i = 0; i < size; ++i) {
1047                 if (copy [i])
1048                         func (copy [i], user_data);
1049         }
1050
1051         mono_gc_free_fixed (copy);
1052 }
1053
1054 /**
1055  * mono_domain_assembly_open:
1056  * @domain: the application domain
1057  * @name: file name of the assembly
1058  *
1059  * fixme: maybe we should integrate this with mono_assembly_open ??
1060  */
1061 MonoAssembly *
1062 mono_domain_assembly_open (MonoDomain *domain, const char *name)
1063 {
1064         MonoAssembly *ass;
1065         GSList *tmp;
1066
1067         mono_domain_assemblies_lock (domain);
1068         for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
1069                 ass = tmp->data;
1070                 if (strcmp (name, ass->aname.name) == 0) {
1071                         mono_domain_assemblies_unlock (domain);
1072                         return ass;
1073                 }
1074         }
1075         mono_domain_assemblies_unlock (domain);
1076
1077         if (!(ass = mono_assembly_open (name, NULL)))
1078                 return NULL;
1079
1080         return ass;
1081 }
1082
1083 static void
1084 dynamic_method_info_free (gpointer key, gpointer value, gpointer user_data)
1085 {
1086         MonoJitDynamicMethodInfo *di = value;
1087         mono_code_manager_destroy (di->code_mp);
1088         g_free (di);
1089 }
1090
1091 static void
1092 delete_jump_list (gpointer key, gpointer value, gpointer user_data)
1093 {
1094         g_slist_free (value);
1095 }
1096
1097 void
1098 mono_domain_free (MonoDomain *domain, gboolean force)
1099 {
1100         GSList *tmp;
1101         if ((domain == mono_root_domain) && !force) {
1102                 g_warning ("cant unload root domain");
1103                 return;
1104         }
1105
1106         mono_appdomains_lock ();
1107         appdomains_list [domain->domain_id] = NULL;
1108         mono_appdomains_unlock ();
1109
1110         /* FIXME: free delegate_hash_table when it's used */
1111         if (domain->search_path) {
1112                 g_strfreev (domain->search_path);
1113                 domain->search_path = NULL;
1114         }
1115         domain->create_proxy_for_type_method = NULL;
1116         domain->private_invoke_method = NULL;
1117         domain->default_context = NULL;
1118         domain->out_of_memory_ex = NULL;
1119         domain->null_reference_ex = NULL;
1120         domain->stack_overflow_ex = NULL;
1121         domain->entry_assembly = NULL;
1122         for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
1123                 MonoAssembly *ass = tmp->data;
1124                 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_ASSEMBLY, "Unloading domain %s %p, assembly %s %p, refcount=%d\n", domain->friendly_name, domain, ass->aname.name, ass, ass->ref_count);
1125                 mono_assembly_close (ass);
1126         }
1127         g_slist_free (domain->domain_assemblies);
1128         domain->domain_assemblies = NULL;
1129
1130         g_free (domain->friendly_name);
1131         domain->friendly_name = NULL;
1132         mono_g_hash_table_destroy (domain->env);
1133         domain->env = NULL;
1134         g_hash_table_destroy (domain->class_vtable_hash);
1135         domain->class_vtable_hash = NULL;
1136         g_hash_table_destroy (domain->proxy_vtable_hash);
1137         domain->proxy_vtable_hash = NULL;
1138         if (domain->static_data_array) {
1139                 mono_gc_free_fixed (domain->static_data_array);
1140                 domain->static_data_array = NULL;
1141         }
1142         mono_internal_hash_table_destroy (&domain->jit_code_hash);
1143         if (domain->dynamic_code_hash) {
1144                 g_hash_table_foreach (domain->dynamic_code_hash, dynamic_method_info_free, NULL);
1145                 g_hash_table_destroy (domain->dynamic_code_hash);
1146                 domain->dynamic_code_hash = NULL;
1147         }
1148         mono_g_hash_table_destroy (domain->ldstr_table);
1149         domain->ldstr_table = NULL;
1150         mono_jit_info_table_free (domain->jit_info_table);
1151         domain->jit_info_table = NULL;
1152 #ifdef DEBUG_DOMAIN_UNLOAD
1153         mono_mempool_invalidate (domain->mp);
1154         mono_code_manager_invalidate (domain->code_mp);
1155 #else
1156         mono_mempool_destroy (domain->mp);
1157         domain->mp = NULL;
1158         mono_code_manager_destroy (domain->code_mp);
1159         domain->code_mp = NULL;
1160 #endif  
1161         if (domain->jump_target_hash) {
1162                 g_hash_table_foreach (domain->jump_target_hash, delete_jump_list, NULL);
1163                 g_hash_table_destroy (domain->jump_target_hash);
1164                 domain->jump_target_hash = NULL;
1165         }
1166         if (domain->type_hash) {
1167                 mono_g_hash_table_destroy (domain->type_hash);
1168                 domain->type_hash = NULL;
1169         }
1170         if (domain->refobject_hash) {
1171                 mono_g_hash_table_destroy (domain->refobject_hash);
1172                 domain->refobject_hash = NULL;
1173         }
1174         if (domain->type_init_exception_hash) {
1175                 mono_g_hash_table_destroy (domain->type_init_exception_hash);
1176                 domain->type_init_exception_hash = NULL;
1177         }
1178         g_hash_table_destroy (domain->class_init_trampoline_hash);
1179         domain->class_init_trampoline_hash = NULL;
1180         g_hash_table_destroy (domain->jump_trampoline_hash);
1181         domain->jump_trampoline_hash = NULL;
1182         g_hash_table_destroy (domain->finalizable_objects_hash);
1183         domain->finalizable_objects_hash = NULL;
1184         g_hash_table_destroy (domain->jit_trampoline_hash);
1185         domain->jit_trampoline_hash = NULL;
1186         g_hash_table_destroy (domain->delegate_trampoline_hash);
1187         domain->delegate_trampoline_hash = NULL;
1188         if (domain->delegate_invoke_impl_with_target_hash) {
1189                 g_hash_table_destroy (domain->delegate_invoke_impl_with_target_hash);
1190                 domain->delegate_invoke_impl_with_target_hash = NULL;
1191         }
1192         if (domain->delegate_invoke_impl_no_target_hash) {
1193                 g_hash_table_destroy (domain->delegate_invoke_impl_no_target_hash);
1194                 domain->delegate_invoke_impl_no_target_hash = NULL;
1195         }
1196         if (domain->special_static_fields) {
1197                 g_hash_table_destroy (domain->special_static_fields);
1198                 domain->special_static_fields = NULL;
1199         }
1200         DeleteCriticalSection (&domain->assemblies_lock);
1201         DeleteCriticalSection (&domain->lock);
1202         domain->setup = NULL;
1203
1204         /* FIXME: anything else required ? */
1205
1206         mono_gc_free_fixed (domain);
1207
1208         if ((domain == mono_root_domain))
1209                 mono_root_domain = NULL;
1210 }
1211
1212 /**
1213  * mono_domain_get_id:
1214  * @domainid: the ID
1215  *
1216  * Returns: the a domain for a specific domain id.
1217  */
1218 MonoDomain * 
1219 mono_domain_get_by_id (gint32 domainid) 
1220 {
1221         MonoDomain * domain;
1222
1223         mono_appdomains_lock ();
1224         if (domainid < appdomain_list_size)
1225                 domain = appdomains_list [domainid];
1226         else
1227                 domain = NULL;
1228         mono_appdomains_unlock ();
1229
1230         return domain;
1231 }
1232
1233 gint32
1234 mono_domain_get_id (MonoDomain *domain)
1235 {
1236         return domain->domain_id;
1237 }
1238
1239 void 
1240 mono_context_set (MonoAppContext * new_context)
1241 {
1242         SET_APPCONTEXT (new_context);
1243 }
1244
1245 MonoAppContext * 
1246 mono_context_get (void)
1247 {
1248         return GET_APPCONTEXT ();
1249 }
1250
1251 /* LOCKING: the caller holds the lock for this domain */
1252 void
1253 mono_domain_add_class_static_data (MonoDomain *domain, MonoClass *klass, gpointer data, guint32 *bitmap)
1254 {
1255         /* The first entry in the array is the index of the next free slot
1256          * and the total size of the array
1257          */
1258         int next;
1259         if (domain->static_data_array) {
1260                 int size = GPOINTER_TO_INT (domain->static_data_array [1]);
1261                 next = GPOINTER_TO_INT (domain->static_data_array [0]);
1262                 if (next >= size) {
1263                         gpointer *new_array = mono_gc_alloc_fixed (sizeof (gpointer) * (size * 2), NULL);
1264                         memcpy (new_array, domain->static_data_array, sizeof (gpointer) * size);
1265                         size *= 2;
1266                         new_array [1] = GINT_TO_POINTER (size);
1267                         mono_gc_free_fixed (domain->static_data_array);
1268                         domain->static_data_array = new_array;
1269                 }
1270         } else {
1271                 int size = 32;
1272                 gpointer *new_array = mono_gc_alloc_fixed (sizeof (gpointer) * size, NULL);
1273                 next = 2;
1274                 new_array [0] = GINT_TO_POINTER (next);
1275                 new_array [1] = GINT_TO_POINTER (size);
1276                 domain->static_data_array = new_array;
1277         }
1278         domain->static_data_array [next++] = data;
1279         domain->static_data_array [0] = GINT_TO_POINTER (next);
1280 }
1281
1282 MonoImage*
1283 mono_get_corlib (void)
1284 {
1285         return mono_defaults.corlib;
1286 }
1287
1288 MonoClass*
1289 mono_get_object_class (void)
1290 {
1291         return mono_defaults.object_class;
1292 }
1293
1294 MonoClass*
1295 mono_get_byte_class (void)
1296 {
1297         return mono_defaults.byte_class;
1298 }
1299
1300 MonoClass*
1301 mono_get_void_class (void)
1302 {
1303         return mono_defaults.void_class;
1304 }
1305
1306 MonoClass*
1307 mono_get_boolean_class (void)
1308 {
1309         return mono_defaults.boolean_class;
1310 }
1311
1312 MonoClass*
1313 mono_get_sbyte_class (void)
1314 {
1315         return mono_defaults.sbyte_class;
1316 }
1317
1318 MonoClass*
1319 mono_get_int16_class (void)
1320 {
1321         return mono_defaults.int16_class;
1322 }
1323
1324 MonoClass*
1325 mono_get_uint16_class (void)
1326 {
1327         return mono_defaults.uint16_class;
1328 }
1329
1330 MonoClass*
1331 mono_get_int32_class (void)
1332 {
1333         return mono_defaults.int32_class;
1334 }
1335
1336 MonoClass*
1337 mono_get_uint32_class (void)
1338 {
1339         return mono_defaults.uint32_class;
1340 }
1341
1342 MonoClass*
1343 mono_get_intptr_class (void)
1344 {
1345         return mono_defaults.int_class;
1346 }
1347
1348 MonoClass*
1349 mono_get_uintptr_class (void)
1350 {
1351         return mono_defaults.uint_class;
1352 }
1353
1354 MonoClass*
1355 mono_get_int64_class (void)
1356 {
1357         return mono_defaults.int64_class;
1358 }
1359
1360 MonoClass*
1361 mono_get_uint64_class (void)
1362 {
1363         return mono_defaults.uint64_class;
1364 }
1365
1366 MonoClass*
1367 mono_get_single_class (void)
1368 {
1369         return mono_defaults.single_class;
1370 }
1371
1372 MonoClass*
1373 mono_get_double_class (void)
1374 {
1375         return mono_defaults.double_class;
1376 }
1377
1378 MonoClass*
1379 mono_get_char_class (void)
1380 {
1381         return mono_defaults.char_class;
1382 }
1383
1384 MonoClass*
1385 mono_get_string_class (void)
1386 {
1387         return mono_defaults.string_class;
1388 }
1389
1390 MonoClass*
1391 mono_get_enum_class (void)
1392 {
1393         return mono_defaults.enum_class;
1394 }
1395
1396 MonoClass*
1397 mono_get_array_class (void)
1398 {
1399         return mono_defaults.array_class;
1400 }
1401
1402 MonoClass*
1403 mono_get_thread_class (void)
1404 {
1405         return mono_defaults.thread_class;
1406 }
1407
1408 MonoClass*
1409 mono_get_exception_class (void)
1410 {
1411         return mono_defaults.exception_class;
1412 }
1413
1414
1415 static char* get_attribute_value (const gchar **attribute_names, 
1416                                         const gchar **attribute_values, 
1417                                         const char *att_name)
1418 {
1419         int n;
1420         for (n=0; attribute_names[n] != NULL; n++) {
1421                 if (strcmp (attribute_names[n], att_name) == 0)
1422                         return g_strdup (attribute_values[n]);
1423         }
1424         return NULL;
1425 }
1426
1427 static void start_element (GMarkupParseContext *context, 
1428                            const gchar         *element_name,
1429                            const gchar        **attribute_names,
1430                            const gchar        **attribute_values,
1431                            gpointer             user_data,
1432                            GError             **error)
1433 {
1434         AppConfigInfo* app_config = (AppConfigInfo*) user_data;
1435         
1436         if (strcmp (element_name, "configuration") == 0) {
1437                 app_config->configuration_count++;
1438                 return;
1439         }
1440         if (strcmp (element_name, "startup") == 0) {
1441                 app_config->startup_count++;
1442                 return;
1443         }
1444         
1445         if (app_config->configuration_count != 1 || app_config->startup_count != 1)
1446                 return;
1447         
1448         if (strcmp (element_name, "requiredRuntime") == 0) {
1449                 app_config->required_runtime = get_attribute_value (attribute_names, attribute_values, "version");
1450         } else if (strcmp (element_name, "supportedRuntime") == 0) {
1451                 char *version = get_attribute_value (attribute_names, attribute_values, "version");
1452                 app_config->supported_runtimes = g_slist_append (app_config->supported_runtimes, version);
1453         }
1454 }
1455
1456 static void end_element   (GMarkupParseContext *context,
1457                            const gchar         *element_name,
1458                            gpointer             user_data,
1459                            GError             **error)
1460 {
1461         AppConfigInfo* app_config = (AppConfigInfo*) user_data;
1462         
1463         if (strcmp (element_name, "configuration") == 0) {
1464                 app_config->configuration_count--;
1465         } else if (strcmp (element_name, "startup") == 0) {
1466                 app_config->startup_count--;
1467         }
1468 }
1469
1470 static const GMarkupParser 
1471 mono_parser = {
1472         start_element,
1473         end_element,
1474         NULL,
1475         NULL,
1476         NULL
1477 };
1478
1479 static AppConfigInfo *
1480 app_config_parse (const char *exe_filename)
1481 {
1482         AppConfigInfo *app_config;
1483         GMarkupParseContext *context;
1484         char *text;
1485         gsize len;
1486         struct stat buf;
1487         const char *bundled_config;
1488         char *config_filename;
1489
1490         bundled_config = mono_config_string_for_assembly_file (exe_filename);
1491
1492         if (bundled_config) {
1493                 text = g_strdup (bundled_config);
1494                 len = strlen (text);
1495         } else {
1496                 config_filename = g_strconcat (exe_filename, ".config", NULL);
1497
1498                 if (stat (config_filename, &buf) != 0) {
1499                         g_free (config_filename);
1500                         return NULL;
1501                 }
1502         
1503                 if (!g_file_get_contents (config_filename, &text, &len, NULL)) {
1504                         g_free (config_filename);
1505                         return NULL;
1506                 }
1507                 g_free (config_filename);
1508         }
1509
1510         app_config = g_new0 (AppConfigInfo, 1);
1511
1512         context = g_markup_parse_context_new (&mono_parser, 0, app_config, NULL);
1513         if (g_markup_parse_context_parse (context, text, len, NULL)) {
1514                 g_markup_parse_context_end_parse (context, NULL);
1515         }
1516         g_markup_parse_context_free (context);
1517         g_free (text);
1518         return app_config;
1519 }
1520
1521 static void 
1522 app_config_free (AppConfigInfo* app_config)
1523 {
1524         char *rt;
1525         GSList *list = app_config->supported_runtimes;
1526         while (list != NULL) {
1527                 rt = (char*)list->data;
1528                 g_free (rt);
1529                 list = g_slist_next (list);
1530         }
1531         g_slist_free (app_config->supported_runtimes);
1532         g_free (app_config->required_runtime);
1533         g_free (app_config);
1534 }
1535
1536
1537 static const MonoRuntimeInfo*
1538 get_runtime_by_version (const char *version)
1539 {
1540         int n;
1541         int max = G_N_ELEMENTS (supported_runtimes);
1542         
1543         for (n=0; n<max; n++) {
1544                 if (strcmp (version, supported_runtimes[n].runtime_version) == 0)
1545                         return &supported_runtimes[n];
1546         }
1547         return NULL;
1548 }
1549
1550 static void
1551 get_runtimes_from_exe (const char *exe_file, const MonoRuntimeInfo** runtimes)
1552 {
1553         AppConfigInfo* app_config;
1554         char *version;
1555         const MonoRuntimeInfo* runtime = NULL;
1556         MonoImage *image = NULL;
1557         
1558         app_config = app_config_parse (exe_file);
1559         
1560         if (app_config != NULL) {
1561                 /* Check supportedRuntime elements, if none is supported, fail.
1562                  * If there are no such elements, look for a requiredRuntime element.
1563                  */
1564                 if (app_config->supported_runtimes != NULL) {
1565                         int n = 0;
1566                         GSList *list = app_config->supported_runtimes;
1567                         while (list != NULL) {
1568                                 version = (char*) list->data;
1569                                 runtime = get_runtime_by_version (version);
1570                                 if (runtime != NULL)
1571                                         runtimes [n++] = runtime;
1572                                 list = g_slist_next (list);
1573                         }
1574                         runtimes [n] = NULL;
1575                         app_config_free (app_config);
1576                         return;
1577                 }
1578                 
1579                 /* Check the requiredRuntime element. This is for 1.0 apps only. */
1580                 if (app_config->required_runtime != NULL) {
1581                         runtimes [0] = get_runtime_by_version (app_config->required_runtime);
1582                         runtimes [1] = NULL;
1583                         app_config_free (app_config);
1584                         return;
1585                 }
1586                 app_config_free (app_config);
1587         }
1588         
1589         /* Look for a runtime with the exact version */
1590         image = mono_assembly_open_from_bundle (exe_file, NULL, FALSE);
1591
1592         if (image == NULL)
1593                 image = mono_image_open (exe_file, NULL);
1594
1595         if (image == NULL) {
1596                 /* The image is wrong or the file was not found. In this case return
1597                  * a default runtime and leave to the initialization method the work of
1598                  * reporting the error.
1599                  */
1600                 runtimes [0] = get_runtime_by_version (DEFAULT_RUNTIME_VERSION);
1601                 runtimes [1] = NULL;
1602                 return;
1603         }
1604
1605         /* 
1606          * FIXME: This would cause us to unload the image, and it will be loaded again later.
1607          * Disabling it will mean the initial exe will not be unloaded on shutdown.
1608          */
1609         //mono_image_close (image);
1610
1611         runtimes [0] = get_runtime_by_version (image->version);
1612         runtimes [1] = NULL;
1613 }
1614
1615
1616 /**
1617  * mono_get_runtime_info:
1618  *
1619  * Returns: the version of the current runtime instance.
1620  */
1621 const MonoRuntimeInfo*
1622 mono_get_runtime_info (void)
1623 {
1624         return current_runtime;
1625 }
1626
1627 gchar *
1628 mono_debugger_check_runtime_version (const char *filename)
1629 {
1630         const MonoRuntimeInfo* runtimes [G_N_ELEMENTS (supported_runtimes) + 1];
1631         const MonoRuntimeInfo *rinfo;
1632
1633         get_runtimes_from_exe (filename, runtimes);
1634         rinfo = runtimes [0];
1635
1636         if (!rinfo)
1637                 return g_strdup_printf ("Cannot get runtime version from assembly `%s'", filename);
1638
1639         if (rinfo != current_runtime)
1640                 return g_strdup_printf ("The Mono Debugger is currently using the `%s' runtime, but "
1641                                         "the assembly `%s' requires version `%s'", current_runtime->runtime_version,
1642                                         filename, rinfo->runtime_version);
1643
1644         return NULL;
1645 }