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