33a5da2c3d22cf2656fc6558da3ae22bc49a5270
[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 gboolean
342 mono_string_equal (MonoString *s1, MonoString *s2)
343 {
344         int l1 = mono_string_length (s1);
345         int l2 = mono_string_length (s2);
346
347         if (s1 == s2)
348                 return TRUE;
349         if (l1 != l2)
350                 return FALSE;
351
352         return memcmp (mono_string_chars (s1), mono_string_chars (s2), l1 * 2) == 0; 
353 }
354
355 guint
356 mono_string_hash (MonoString *s)
357 {
358         const guint16 *p = mono_string_chars (s);
359         int i, len = mono_string_length (s);
360         guint h = 0;
361
362         for (i = 0; i < len; i++) {
363                 h = (h << 5) - h + *p;
364                 p++;
365         }
366
367         return h;       
368 }
369
370 static gboolean
371 mono_ptrarray_equal (gpointer *s1, gpointer *s2)
372 {
373         int len = GPOINTER_TO_INT (s1 [0]);
374         if (len != GPOINTER_TO_INT (s2 [0]))
375                 return FALSE;
376
377         return memcmp (s1 + 1, s2 + 1, len * sizeof(gpointer)) == 0; 
378 }
379
380 static guint
381 mono_ptrarray_hash (gpointer *s)
382 {
383         int i;
384         int len = GPOINTER_TO_INT (s [0]);
385         guint hash = 0;
386         
387         for (i = 1; i < len; i++)
388                 hash += GPOINTER_TO_UINT (s [i]);
389
390         return hash;    
391 }
392
393 /*
394  * Allocate an id for domain and set domain->domain_id.
395  * LOCKING: must be called while holding appdomains_mutex.
396  * We try to assign low numbers to the domain, so it can be used
397  * as an index in data tables to lookup domain-specific info
398  * with minimal memory overhead. We also try not to reuse the
399  * same id too quickly (to help debugging).
400  */
401 static int
402 domain_id_alloc (MonoDomain *domain)
403 {
404         int id = -1, i;
405         if (!appdomains_list) {
406                 appdomain_list_size = 2;
407                 appdomains_list = mono_gc_alloc_fixed (appdomain_list_size * sizeof (void*), NULL);
408         }
409         for (i = appdomain_next; i < appdomain_list_size; ++i) {
410                 if (!appdomains_list [i]) {
411                         id = i;
412                         break;
413                 }
414         }
415         if (id == -1) {
416                 for (i = 0; i < appdomain_next; ++i) {
417                         if (!appdomains_list [i]) {
418                                 id = i;
419                                 break;
420                         }
421                 }
422         }
423         if (id == -1) {
424                 MonoDomain **new_list;
425                 int new_size = appdomain_list_size * 2;
426                 if (new_size >= (1 << 16))
427                         g_assert_not_reached ();
428                 id = appdomain_list_size;
429                 new_list = mono_gc_alloc_fixed (new_size * sizeof (void*), NULL);
430                 memcpy (new_list, appdomains_list, appdomain_list_size * sizeof (void*));
431                 mono_gc_free_fixed (appdomains_list);
432                 appdomains_list = new_list;
433                 appdomain_list_size = new_size;
434         }
435         domain->domain_id = id;
436         appdomains_list [id] = domain;
437         appdomain_next++;
438         if (appdomain_next > appdomain_list_size)
439                 appdomain_next = 0;
440         return id;
441 }
442
443 static guint32 domain_gc_bitmap [sizeof(MonoDomain)/4/32 + 1];
444 static gpointer domain_gc_desc = NULL;
445
446 MonoDomain *
447 mono_domain_create (void)
448 {
449         MonoDomain *domain;
450
451         mono_appdomains_lock ();
452         if (!domain_gc_desc) {
453                 unsigned int i, bit = 0;
454                 for (i = G_STRUCT_OFFSET (MonoDomain, MONO_DOMAIN_FIRST_OBJECT); i < G_STRUCT_OFFSET (MonoDomain, MONO_DOMAIN_FIRST_GC_TRACKED); i += sizeof (gpointer)) {
455                         bit = i / sizeof (gpointer);
456                         domain_gc_bitmap [bit / 32] |= 1 << (bit % 32);
457                 }
458                 domain_gc_desc = mono_gc_make_descr_from_bitmap (domain_gc_bitmap, bit + 1);
459         }
460         mono_appdomains_unlock ();
461
462         domain = mono_gc_alloc_fixed (sizeof (MonoDomain), domain_gc_desc);
463         domain->domain = NULL;
464         domain->setup = NULL;
465         domain->friendly_name = NULL;
466         domain->search_path = NULL;
467
468         domain->mp = mono_mempool_new ();
469         domain->code_mp = mono_code_manager_new ();
470         domain->env = mono_g_hash_table_new_type ((GHashFunc)mono_string_hash, (GCompareFunc)mono_string_equal, MONO_HASH_KEY_VALUE_GC);
471         domain->domain_assemblies = NULL;
472         domain->class_vtable_hash = g_hash_table_new (mono_aligned_addr_hash, NULL);
473         domain->proxy_vtable_hash = g_hash_table_new ((GHashFunc)mono_ptrarray_hash, (GCompareFunc)mono_ptrarray_equal);
474         domain->static_data_array = NULL;
475         domain->jit_code_hash = g_hash_table_new (mono_aligned_addr_hash, NULL);
476         domain->ldstr_table = mono_g_hash_table_new ((GHashFunc)mono_string_hash, (GCompareFunc)mono_string_equal);
477         domain->jit_info_table = mono_jit_info_table_new ();
478         domain->class_init_trampoline_hash = g_hash_table_new (mono_aligned_addr_hash, NULL);
479         domain->jump_trampoline_hash = g_hash_table_new (mono_aligned_addr_hash, NULL);
480         domain->finalizable_objects_hash = g_hash_table_new (mono_aligned_addr_hash, NULL);
481         domain->jit_trampoline_hash = g_hash_table_new (mono_aligned_addr_hash, NULL);
482         domain->delegate_trampoline_hash = g_hash_table_new (mono_aligned_addr_hash, NULL);
483
484         InitializeCriticalSection (&domain->lock);
485         InitializeCriticalSection (&domain->assemblies_lock);
486
487         mono_appdomains_lock ();
488         domain_id_alloc (domain);
489         mono_appdomains_unlock ();
490
491         return domain;
492 }
493
494 /**
495  * mono_init_internal:
496  * 
497  * Creates the initial application domain and initializes the mono_defaults
498  * structure.
499  * This function is guaranteed to not run any IL code.
500  * If exe_filename is not NULL, the method will determine the required runtime
501  * from the exe configuration file or the version PE field.
502  * If runtime_version is not NULL, that runtime version will be used.
503  * Either exe_filename or runtime_version must be provided.
504  *
505  * Returns: the initial domain.
506  */
507 static MonoDomain *
508 mono_init_internal (const char *filename, const char *exe_filename, const char *runtime_version)
509 {
510         static MonoDomain *domain = NULL;
511         MonoAssembly *ass = NULL;
512         MonoImageOpenStatus status = MONO_IMAGE_OK;
513         const MonoRuntimeInfo* runtimes [G_N_ELEMENTS (supported_runtimes) + 1];
514         int n;
515
516         if (domain)
517                 g_assert_not_reached ();
518
519         MONO_GC_PRE_INIT ();
520
521         appdomain_thread_id = TlsAlloc ();
522
523         InitializeCriticalSection (&appdomains_mutex);
524
525         mono_metadata_init ();
526         mono_raw_buffer_init ();
527         mono_images_init ();
528         mono_assemblies_init ();
529         mono_classes_init ();
530         mono_loader_init ();
531
532         /* FIXME: When should we release this memory? */
533         MONO_GC_REGISTER_ROOT (appdomains_list);
534
535         domain = mono_domain_create ();
536         mono_root_domain = domain;
537
538         SET_APPDOMAIN (domain);
539         
540         /* Get a list of runtimes supported by the exe */
541         if (exe_filename != NULL) {
542                 get_runtimes_from_exe (exe_filename, runtimes);
543         } else if (runtime_version != NULL) {
544                 runtimes [0] = get_runtime_by_version (runtime_version);
545                 runtimes [1] = NULL;
546         }
547
548         if (runtimes [0] == NULL) {
549                 const MonoRuntimeInfo *default_runtime = get_runtime_by_version (DEFAULT_RUNTIME_VERSION);
550                 runtimes [0] = default_runtime;
551                 runtimes [1] = NULL;
552                 g_print ("WARNING: The runtime version supported by this application is unavailable.\n");
553                 g_print ("Using default runtime: %s\n", default_runtime->runtime_version);
554         }
555
556         /* The selected runtime will be the first one for which there is a mscrolib.dll */
557         for (n = 0; runtimes [n] != NULL && ass == NULL; n++) {
558                 current_runtime = runtimes [n];
559                 ass = mono_assembly_load_corlib (current_runtime, &status);
560                 if (status != MONO_IMAGE_OK && status != MONO_IMAGE_ERROR_ERRNO)
561                         break;
562         }
563
564         if ((status != MONO_IMAGE_OK) || (ass == NULL)) {
565                 switch (status){
566                 case MONO_IMAGE_ERROR_ERRNO: {
567                         char *corlib_file = g_build_filename (mono_assembly_getrootdir (), "mono", current_runtime->framework_version, "mscorlib.dll", NULL);
568                         g_print ("The assembly mscorlib.dll was not found or could not be loaded.\n");
569                         g_print ("It should have been installed in the `%s' directory.\n", corlib_file);
570                         g_free (corlib_file);
571                         break;
572                 }
573                 case MONO_IMAGE_IMAGE_INVALID:
574                         g_print ("The file %s/mscorlib.dll is an invalid CIL image\n",
575                                  mono_assembly_getrootdir ());
576                         break;
577                 case MONO_IMAGE_MISSING_ASSEMBLYREF:
578                         g_print ("Missing assembly reference in %s/mscorlib.dll\n",
579                                  mono_assembly_getrootdir ());
580                         break;
581                 case MONO_IMAGE_OK:
582                         /* to suppress compiler warning */
583                         break;
584                 }
585                 
586                 exit (1);
587         }
588         mono_defaults.corlib = mono_assembly_get_image (ass);
589
590         mono_defaults.object_class = mono_class_from_name (
591                 mono_defaults.corlib, "System", "Object");
592         g_assert (mono_defaults.object_class != 0);
593
594         mono_defaults.void_class = mono_class_from_name (
595                 mono_defaults.corlib, "System", "Void");
596         g_assert (mono_defaults.void_class != 0);
597
598         mono_defaults.boolean_class = mono_class_from_name (
599                 mono_defaults.corlib, "System", "Boolean");
600         g_assert (mono_defaults.boolean_class != 0);
601
602         mono_defaults.byte_class = mono_class_from_name (
603                 mono_defaults.corlib, "System", "Byte");
604         g_assert (mono_defaults.byte_class != 0);
605
606         mono_defaults.sbyte_class = mono_class_from_name (
607                 mono_defaults.corlib, "System", "SByte");
608         g_assert (mono_defaults.sbyte_class != 0);
609
610         mono_defaults.int16_class = mono_class_from_name (
611                 mono_defaults.corlib, "System", "Int16");
612         g_assert (mono_defaults.int16_class != 0);
613
614         mono_defaults.uint16_class = mono_class_from_name (
615                 mono_defaults.corlib, "System", "UInt16");
616         g_assert (mono_defaults.uint16_class != 0);
617
618         mono_defaults.int32_class = mono_class_from_name (
619                 mono_defaults.corlib, "System", "Int32");
620         g_assert (mono_defaults.int32_class != 0);
621
622         mono_defaults.uint32_class = mono_class_from_name (
623                 mono_defaults.corlib, "System", "UInt32");
624         g_assert (mono_defaults.uint32_class != 0);
625
626         mono_defaults.uint_class = mono_class_from_name (
627                 mono_defaults.corlib, "System", "UIntPtr");
628         g_assert (mono_defaults.uint_class != 0);
629
630         mono_defaults.int_class = mono_class_from_name (
631                 mono_defaults.corlib, "System", "IntPtr");
632         g_assert (mono_defaults.int_class != 0);
633
634         mono_defaults.int64_class = mono_class_from_name (
635                 mono_defaults.corlib, "System", "Int64");
636         g_assert (mono_defaults.int64_class != 0);
637
638         mono_defaults.uint64_class = mono_class_from_name (
639                 mono_defaults.corlib, "System", "UInt64");
640         g_assert (mono_defaults.uint64_class != 0);
641
642         mono_defaults.single_class = mono_class_from_name (
643                 mono_defaults.corlib, "System", "Single");
644         g_assert (mono_defaults.single_class != 0);
645
646         mono_defaults.double_class = mono_class_from_name (
647                 mono_defaults.corlib, "System", "Double");
648         g_assert (mono_defaults.double_class != 0);
649
650         mono_defaults.char_class = mono_class_from_name (
651                 mono_defaults.corlib, "System", "Char");
652         g_assert (mono_defaults.char_class != 0);
653
654         mono_defaults.string_class = mono_class_from_name (
655                 mono_defaults.corlib, "System", "String");
656         g_assert (mono_defaults.string_class != 0);
657
658         mono_defaults.enum_class = mono_class_from_name (
659                 mono_defaults.corlib, "System", "Enum");
660         g_assert (mono_defaults.enum_class != 0);
661
662         mono_defaults.array_class = mono_class_from_name (
663                 mono_defaults.corlib, "System", "Array");
664         g_assert (mono_defaults.array_class != 0);
665
666         mono_defaults.delegate_class = mono_class_from_name (
667                 mono_defaults.corlib, "System", "Delegate");
668         g_assert (mono_defaults.delegate_class != 0 );
669
670         mono_defaults.multicastdelegate_class = mono_class_from_name (
671                 mono_defaults.corlib, "System", "MulticastDelegate");
672         g_assert (mono_defaults.multicastdelegate_class != 0 );
673
674         mono_defaults.asyncresult_class = mono_class_from_name (
675                 mono_defaults.corlib, "System.Runtime.Remoting.Messaging", 
676                 "AsyncResult");
677         g_assert (mono_defaults.asyncresult_class != 0 );
678
679         mono_defaults.waithandle_class = mono_class_from_name (
680                 mono_defaults.corlib, "System.Threading", "WaitHandle");
681         g_assert (mono_defaults.waithandle_class != 0 );
682
683         mono_defaults.typehandle_class = mono_class_from_name (
684                 mono_defaults.corlib, "System", "RuntimeTypeHandle");
685         g_assert (mono_defaults.typehandle_class != 0);
686
687         mono_defaults.methodhandle_class = mono_class_from_name (
688                 mono_defaults.corlib, "System", "RuntimeMethodHandle");
689         g_assert (mono_defaults.methodhandle_class != 0);
690
691         mono_defaults.fieldhandle_class = mono_class_from_name (
692                 mono_defaults.corlib, "System", "RuntimeFieldHandle");
693         g_assert (mono_defaults.fieldhandle_class != 0);
694
695         mono_defaults.systemtype_class = mono_class_from_name (
696                 mono_defaults.corlib, "System", "Type");
697         g_assert (mono_defaults.systemtype_class != 0);
698
699         mono_defaults.monotype_class = mono_class_from_name (
700                 mono_defaults.corlib, "System", "MonoType");
701         g_assert (mono_defaults.monotype_class != 0);
702
703         mono_defaults.exception_class = mono_class_from_name (
704                 mono_defaults.corlib, "System", "Exception");
705         g_assert (mono_defaults.exception_class != 0);
706
707         mono_defaults.threadabortexception_class = mono_class_from_name (
708                 mono_defaults.corlib, "System.Threading", "ThreadAbortException");
709         g_assert (mono_defaults.threadabortexception_class != 0);
710
711         mono_defaults.thread_class = mono_class_from_name (
712                 mono_defaults.corlib, "System.Threading", "Thread");
713         g_assert (mono_defaults.thread_class != 0);
714
715         mono_defaults.appdomain_class = mono_class_from_name (
716                 mono_defaults.corlib, "System", "AppDomain");
717         g_assert (mono_defaults.appdomain_class != 0);
718
719         mono_defaults.transparent_proxy_class = mono_class_from_name (
720                 mono_defaults.corlib, "System.Runtime.Remoting.Proxies", "TransparentProxy");
721         g_assert (mono_defaults.transparent_proxy_class != 0);
722
723         mono_defaults.real_proxy_class = mono_class_from_name (
724                 mono_defaults.corlib, "System.Runtime.Remoting.Proxies", "RealProxy");
725         g_assert (mono_defaults.real_proxy_class != 0);
726
727         mono_defaults.mono_method_message_class = mono_class_from_name (
728                 mono_defaults.corlib, "System.Runtime.Remoting.Messaging", "MonoMethodMessage");
729         g_assert (mono_defaults.mono_method_message_class != 0);
730
731         mono_defaults.field_info_class = mono_class_from_name (
732                 mono_defaults.corlib, "System.Reflection", "FieldInfo");
733         g_assert (mono_defaults.field_info_class != 0);
734
735         mono_defaults.method_info_class = mono_class_from_name (
736                 mono_defaults.corlib, "System.Reflection", "MethodInfo");
737         g_assert (mono_defaults.method_info_class != 0);
738
739         mono_defaults.stringbuilder_class = mono_class_from_name (
740                 mono_defaults.corlib, "System.Text", "StringBuilder");
741         g_assert (mono_defaults.stringbuilder_class != 0);
742
743         mono_defaults.math_class = mono_class_from_name (
744                 mono_defaults.corlib, "System", "Math");
745         g_assert (mono_defaults.math_class != 0);
746
747         mono_defaults.stack_frame_class = mono_class_from_name (
748                 mono_defaults.corlib, "System.Diagnostics", "StackFrame");
749         g_assert (mono_defaults.stack_frame_class != 0);
750
751         mono_defaults.stack_trace_class = mono_class_from_name (
752                 mono_defaults.corlib, "System.Diagnostics", "StackTrace");
753         g_assert (mono_defaults.stack_trace_class != 0);
754
755         mono_defaults.marshal_class = mono_class_from_name (
756                 mono_defaults.corlib, "System.Runtime.InteropServices", "Marshal");
757         g_assert (mono_defaults.marshal_class != 0);
758
759         mono_defaults.iserializeable_class = mono_class_from_name (
760                 mono_defaults.corlib, "System.Runtime.Serialization", "ISerializable");
761         g_assert (mono_defaults.iserializeable_class != 0);
762
763         mono_defaults.serializationinfo_class = mono_class_from_name (
764                 mono_defaults.corlib, "System.Runtime.Serialization", "SerializationInfo");
765         g_assert (mono_defaults.serializationinfo_class != 0);
766
767         mono_defaults.streamingcontext_class = mono_class_from_name (
768                 mono_defaults.corlib, "System.Runtime.Serialization", "StreamingContext");
769         g_assert (mono_defaults.streamingcontext_class != 0);
770
771         mono_defaults.typed_reference_class =  mono_class_from_name (
772                 mono_defaults.corlib, "System", "TypedReference");
773         g_assert (mono_defaults.typed_reference_class != 0);
774
775         mono_defaults.argumenthandle_class =  mono_class_from_name (
776                 mono_defaults.corlib, "System", "RuntimeArgumentHandle");
777         g_assert (mono_defaults.argumenthandle_class != 0);
778
779         mono_defaults.marshalbyrefobject_class =  mono_class_from_name (
780                 mono_defaults.corlib, "System", "MarshalByRefObject");
781         g_assert (mono_defaults.marshalbyrefobject_class != 0);
782
783         mono_defaults.monitor_class =  mono_class_from_name (
784                 mono_defaults.corlib, "System.Threading", "Monitor");
785         g_assert (mono_defaults.monitor_class != 0);
786
787         mono_defaults.iremotingtypeinfo_class = mono_class_from_name (
788                 mono_defaults.corlib, "System.Runtime.Remoting", "IRemotingTypeInfo");
789         g_assert (mono_defaults.iremotingtypeinfo_class != 0);
790
791         mono_defaults.runtimesecurityframe_class = mono_class_from_name (
792                 mono_defaults.corlib, "System.Security", "RuntimeSecurityFrame");
793
794         mono_defaults.executioncontext_class = mono_class_from_name (
795                 mono_defaults.corlib, "System.Threading", "ExecutionContext");
796
797         mono_defaults.internals_visible_class = mono_class_from_name (
798                 mono_defaults.corlib, "System.Runtime.CompilerServices", "InternalsVisibleToAttribute");
799
800         mono_defaults.variant_class = mono_class_from_name (
801                 mono_defaults.corlib, "System", "Variant");
802
803         /*
804          * Note that mono_defaults.generic_*_class is only non-NULL if we're
805          * using the 2.0 corlib.
806          */
807         mono_class_init (mono_defaults.array_class);
808         mono_defaults.generic_array_class = mono_class_from_name (
809                 mono_defaults.corlib, "System", "Array/InternalArray`1");
810         mono_defaults.generic_nullable_class = mono_class_from_name (
811                 mono_defaults.corlib, "System", "Nullable`1");
812
813         domain->friendly_name = g_path_get_basename (filename);
814
815         return domain;
816 }
817
818 /**
819  * mono_init:
820  * 
821  * Creates the initial application domain and initializes the mono_defaults
822  * structure.
823  * This function is guaranteed to not run any IL code.
824  * The runtime is initialized using the default runtime version.
825  *
826  * Returns: the initial domain.
827  */
828 MonoDomain *
829 mono_init (const char *domain_name)
830 {
831         return mono_init_internal (domain_name, NULL, DEFAULT_RUNTIME_VERSION);
832 }
833
834 /**
835  * mono_init_from_assembly:
836  * 
837  * Creates the initial application domain and initializes the mono_defaults
838  * structure.
839  * This function is guaranteed to not run any IL code.
840  * The runtime is initialized using the runtime version required by the
841  * provided executable. The version is determined by looking at the exe 
842  * configuration file and the version PE field)
843  *
844  * Returns: the initial domain.
845  */
846 MonoDomain *
847 mono_init_from_assembly (const char *domain_name, const char *filename)
848 {
849         return mono_init_internal (domain_name, filename, NULL);
850 }
851
852 /**
853  * mono_init_version:
854  * 
855  * Creates the initial application domain and initializes the mono_defaults
856  * structure.
857  * This function is guaranteed to not run any IL code.
858  * The runtime is initialized using the provided rutime version.
859  *
860  * Returns: the initial domain.
861  */
862 MonoDomain *
863 mono_init_version (const char *domain_name, const char *version)
864 {
865         return mono_init_internal (domain_name, NULL, version);
866 }
867
868 /**
869  * mono_cleanup:
870  *
871  * Cleans up all metadata modules. 
872  */
873 void
874 mono_cleanup (void)
875 {
876         mono_loader_cleanup ();
877         mono_classes_cleanup ();
878         mono_assemblies_cleanup ();
879         mono_images_cleanup ();
880         mono_raw_buffer_cleanup ();
881         mono_metadata_cleanup ();
882
883         TlsFree (appdomain_thread_id);
884         DeleteCriticalSection (&appdomains_mutex);
885 }
886
887 /**
888  * mono_get_root_domain:
889  *
890  * Returns: the root appdomain.
891  */
892 MonoDomain*
893 mono_get_root_domain (void)
894 {
895         return mono_root_domain;
896 }
897
898 /**
899  * mono_domain_get:
900  *
901  * Returns: the current domain.
902  */
903 MonoDomain *
904 mono_domain_get ()
905 {
906         return GET_APPDOMAIN ();
907 }
908
909 /**
910  * mono_domain_set_internal:
911  * @domain: the new domain
912  *
913  * Sets the current domain to @domain.
914  */
915 void
916 mono_domain_set_internal (MonoDomain *domain)
917 {
918         SET_APPDOMAIN (domain);
919         SET_APPCONTEXT (domain->default_context);
920 }
921
922 void
923 mono_domain_foreach (MonoDomainFunc func, gpointer user_data)
924 {
925         int i, size;
926         MonoDomain **copy;
927
928         /*
929          * Create a copy of the data to avoid calling the user callback
930          * inside the lock because that could lead to deadlocks.
931          * We can do this because this function is not perf. critical.
932          */
933         mono_appdomains_lock ();
934         size = appdomain_list_size;
935         copy = mono_gc_alloc_fixed (appdomain_list_size * sizeof (void*), NULL);
936         memcpy (copy, appdomains_list, appdomain_list_size * sizeof (void*));
937         mono_appdomains_unlock ();
938
939         for (i = 0; i < size; ++i) {
940                 if (copy [i])
941                         func (copy [i], user_data);
942         }
943
944         mono_gc_free_fixed (copy);
945 }
946
947 /**
948  * mono_domain_assembly_open:
949  * @domain: the application domain
950  * @name: file name of the assembly
951  *
952  * fixme: maybe we should integrate this with mono_assembly_open ??
953  */
954 MonoAssembly *
955 mono_domain_assembly_open (MonoDomain *domain, const char *name)
956 {
957         MonoAssembly *ass;
958         GSList *tmp;
959
960         mono_domain_assemblies_lock (domain);
961         for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
962                 ass = tmp->data;
963                 if (strcmp (name, ass->aname.name) == 0) {
964                         mono_domain_assemblies_unlock (domain);
965                         return ass;
966                 }
967         }
968         mono_domain_assemblies_unlock (domain);
969
970         if (!(ass = mono_assembly_open (name, NULL)))
971                 return NULL;
972
973         return ass;
974 }
975
976 static void
977 dynamic_method_info_free (gpointer key, gpointer value, gpointer user_data)
978 {
979         MonoJitDynamicMethodInfo *di = value;
980         mono_code_manager_destroy (di->code_mp);
981         g_free (di);
982 }
983
984 static void
985 delete_jump_list (gpointer key, gpointer value, gpointer user_data)
986 {
987         g_slist_free (value);
988 }
989
990 void
991 mono_domain_free (MonoDomain *domain, gboolean force)
992 {
993         GSList *tmp;
994         if ((domain == mono_root_domain) && !force) {
995                 g_warning ("cant unload root domain");
996                 return;
997         }
998
999         mono_appdomains_lock ();
1000         appdomains_list [domain->domain_id] = NULL;
1001         mono_appdomains_unlock ();
1002
1003         /* FIXME: free delegate_hash_table when it's used */
1004         if (domain->search_path) {
1005                 g_strfreev (domain->search_path);
1006                 domain->search_path = NULL;
1007         }
1008         domain->create_proxy_for_type_method = NULL;
1009         domain->private_invoke_method = NULL;
1010         domain->default_context = NULL;
1011         domain->out_of_memory_ex = NULL;
1012         domain->null_reference_ex = NULL;
1013         domain->stack_overflow_ex = NULL;
1014         domain->entry_assembly = NULL;
1015         for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
1016                 MonoAssembly *ass = tmp->data;
1017                 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);
1018                 mono_assembly_close (ass);
1019         }
1020         g_slist_free (domain->domain_assemblies);
1021         domain->domain_assemblies = NULL;
1022
1023         g_free (domain->friendly_name);
1024         domain->friendly_name = NULL;
1025         mono_g_hash_table_destroy (domain->env);
1026         domain->env = NULL;
1027         g_hash_table_destroy (domain->class_vtable_hash);
1028         domain->class_vtable_hash = NULL;
1029         g_hash_table_destroy (domain->proxy_vtable_hash);
1030         domain->proxy_vtable_hash = NULL;
1031         if (domain->static_data_array) {
1032                 mono_gc_free_fixed (domain->static_data_array);
1033                 domain->static_data_array = NULL;
1034         }
1035         g_hash_table_destroy (domain->jit_code_hash);
1036         domain->jit_code_hash = NULL;
1037         if (domain->dynamic_code_hash) {
1038                 g_hash_table_foreach (domain->dynamic_code_hash, dynamic_method_info_free, NULL);
1039                 g_hash_table_destroy (domain->dynamic_code_hash);
1040                 domain->dynamic_code_hash = NULL;
1041         }
1042         mono_g_hash_table_destroy (domain->ldstr_table);
1043         domain->ldstr_table = NULL;
1044         mono_jit_info_table_free (domain->jit_info_table);
1045         domain->jit_info_table = NULL;
1046 #ifdef DEBUG_DOMAIN_UNLOAD
1047         mono_mempool_invalidate (domain->mp);
1048         mono_code_manager_invalidate (domain->code_mp);
1049 #else
1050         mono_mempool_destroy (domain->mp);
1051         domain->mp = NULL;
1052         mono_code_manager_destroy (domain->code_mp);
1053         domain->code_mp = NULL;
1054 #endif  
1055         if (domain->jump_target_hash) {
1056                 g_hash_table_foreach (domain->jump_target_hash, delete_jump_list, NULL);
1057                 g_hash_table_destroy (domain->jump_target_hash);
1058                 domain->jump_target_hash = NULL;
1059         }
1060         if (domain->type_hash) {
1061                 mono_g_hash_table_destroy (domain->type_hash);
1062                 domain->type_hash = NULL;
1063         }
1064         if (domain->refobject_hash) {
1065                 mono_g_hash_table_destroy (domain->refobject_hash);
1066                 domain->refobject_hash = NULL;
1067         }
1068         g_hash_table_destroy (domain->class_init_trampoline_hash);
1069         domain->class_init_trampoline_hash = NULL;
1070         g_hash_table_destroy (domain->jump_trampoline_hash);
1071         domain->jump_trampoline_hash = NULL;
1072         g_hash_table_destroy (domain->finalizable_objects_hash);
1073         domain->finalizable_objects_hash = NULL;
1074         g_hash_table_destroy (domain->jit_trampoline_hash);
1075         domain->jit_trampoline_hash = NULL;
1076         g_hash_table_destroy (domain->delegate_trampoline_hash);
1077         domain->delegate_trampoline_hash = NULL;
1078         if (domain->special_static_fields) {
1079                 g_hash_table_destroy (domain->special_static_fields);
1080                 domain->special_static_fields = NULL;
1081         }
1082         DeleteCriticalSection (&domain->assemblies_lock);
1083         DeleteCriticalSection (&domain->lock);
1084         domain->setup = NULL;
1085
1086         /* FIXME: anything else required ? */
1087
1088         mono_gc_free_fixed (domain);
1089
1090         if ((domain == mono_root_domain))
1091                 mono_root_domain = NULL;
1092 }
1093
1094 /**
1095  * mono_domain_get_id:
1096  *
1097  * Returns: the a domain for a specific domain id.
1098  */
1099 MonoDomain * 
1100 mono_domain_get_by_id (gint32 domainid) 
1101 {
1102         MonoDomain * domain;
1103
1104         mono_appdomains_lock ();
1105         if (domainid < appdomain_list_size)
1106                 domain = appdomains_list [domainid];
1107         else
1108                 domain = NULL;
1109         mono_appdomains_unlock ();
1110
1111         return domain;
1112 }
1113
1114 gint32
1115 mono_domain_get_id (MonoDomain *domain)
1116 {
1117         return domain->domain_id;
1118 }
1119
1120 void 
1121 mono_context_set (MonoAppContext * new_context)
1122 {
1123         SET_APPCONTEXT (new_context);
1124 }
1125
1126 MonoAppContext * 
1127 mono_context_get (void)
1128 {
1129         return GET_APPCONTEXT ();
1130 }
1131
1132 /* LOCKING: the caller holds the lock for this domain */
1133 void
1134 mono_domain_add_class_static_data (MonoDomain *domain, MonoClass *klass, gpointer data, guint32 *bitmap)
1135 {
1136         /* The first entry in the array is the index of the next free slot
1137          * and the total size of the array
1138          */
1139         int next;
1140         if (domain->static_data_array) {
1141                 int size = GPOINTER_TO_INT (domain->static_data_array [1]);
1142                 next = GPOINTER_TO_INT (domain->static_data_array [0]);
1143                 if (next >= size) {
1144                         gpointer *new_array = mono_gc_alloc_fixed (sizeof (gpointer) * (size * 2), NULL);
1145                         memcpy (new_array, domain->static_data_array, sizeof (gpointer) * size);
1146                         size *= 2;
1147                         new_array [1] = GINT_TO_POINTER (size);
1148                         mono_gc_free_fixed (domain->static_data_array);
1149                         domain->static_data_array = new_array;
1150                 }
1151         } else {
1152                 int size = 32;
1153                 gpointer *new_array = mono_gc_alloc_fixed (sizeof (gpointer) * size, NULL);
1154                 next = 2;
1155                 new_array [0] = GINT_TO_POINTER (next);
1156                 new_array [1] = GINT_TO_POINTER (size);
1157                 domain->static_data_array = new_array;
1158         }
1159         domain->static_data_array [next++] = data;
1160         domain->static_data_array [0] = GINT_TO_POINTER (next);
1161 }
1162
1163 MonoImage*
1164 mono_get_corlib (void)
1165 {
1166         return mono_defaults.corlib;
1167 }
1168
1169 MonoClass*
1170 mono_get_object_class (void)
1171 {
1172         return mono_defaults.object_class;
1173 }
1174
1175 MonoClass*
1176 mono_get_byte_class (void)
1177 {
1178         return mono_defaults.byte_class;
1179 }
1180
1181 MonoClass*
1182 mono_get_void_class (void)
1183 {
1184         return mono_defaults.void_class;
1185 }
1186
1187 MonoClass*
1188 mono_get_boolean_class (void)
1189 {
1190         return mono_defaults.boolean_class;
1191 }
1192
1193 MonoClass*
1194 mono_get_sbyte_class (void)
1195 {
1196         return mono_defaults.sbyte_class;
1197 }
1198
1199 MonoClass*
1200 mono_get_int16_class (void)
1201 {
1202         return mono_defaults.int16_class;
1203 }
1204
1205 MonoClass*
1206 mono_get_uint16_class (void)
1207 {
1208         return mono_defaults.uint16_class;
1209 }
1210
1211 MonoClass*
1212 mono_get_int32_class (void)
1213 {
1214         return mono_defaults.int32_class;
1215 }
1216
1217 MonoClass*
1218 mono_get_uint32_class (void)
1219 {
1220         return mono_defaults.uint32_class;
1221 }
1222
1223 MonoClass*
1224 mono_get_intptr_class (void)
1225 {
1226         return mono_defaults.int_class;
1227 }
1228
1229 MonoClass*
1230 mono_get_uintptr_class (void)
1231 {
1232         return mono_defaults.uint_class;
1233 }
1234
1235 MonoClass*
1236 mono_get_int64_class (void)
1237 {
1238         return mono_defaults.int64_class;
1239 }
1240
1241 MonoClass*
1242 mono_get_uint64_class (void)
1243 {
1244         return mono_defaults.uint64_class;
1245 }
1246
1247 MonoClass*
1248 mono_get_single_class (void)
1249 {
1250         return mono_defaults.single_class;
1251 }
1252
1253 MonoClass*
1254 mono_get_double_class (void)
1255 {
1256         return mono_defaults.double_class;
1257 }
1258
1259 MonoClass*
1260 mono_get_char_class (void)
1261 {
1262         return mono_defaults.char_class;
1263 }
1264
1265 MonoClass*
1266 mono_get_string_class (void)
1267 {
1268         return mono_defaults.string_class;
1269 }
1270
1271 MonoClass*
1272 mono_get_enum_class (void)
1273 {
1274         return mono_defaults.enum_class;
1275 }
1276
1277 MonoClass*
1278 mono_get_array_class (void)
1279 {
1280         return mono_defaults.array_class;
1281 }
1282
1283 MonoClass*
1284 mono_get_thread_class (void)
1285 {
1286         return mono_defaults.thread_class;
1287 }
1288
1289 MonoClass*
1290 mono_get_exception_class (void)
1291 {
1292         return mono_defaults.exception_class;
1293 }
1294
1295
1296 static char* get_attribute_value (const gchar **attribute_names, 
1297                                         const gchar **attribute_values, 
1298                                         const char *att_name)
1299 {
1300         int n;
1301         for (n=0; attribute_names[n] != NULL; n++) {
1302                 if (strcmp (attribute_names[n], att_name) == 0)
1303                         return g_strdup (attribute_values[n]);
1304         }
1305         return NULL;
1306 }
1307
1308 static void start_element (GMarkupParseContext *context, 
1309                            const gchar         *element_name,
1310                            const gchar        **attribute_names,
1311                            const gchar        **attribute_values,
1312                            gpointer             user_data,
1313                            GError             **error)
1314 {
1315         AppConfigInfo* app_config = (AppConfigInfo*) user_data;
1316         
1317         if (strcmp (element_name, "configuration") == 0) {
1318                 app_config->configuration_count++;
1319                 return;
1320         }
1321         if (strcmp (element_name, "startup") == 0) {
1322                 app_config->startup_count++;
1323                 return;
1324         }
1325         
1326         if (app_config->configuration_count != 1 || app_config->startup_count != 1)
1327                 return;
1328         
1329         if (strcmp (element_name, "requiredRuntime") == 0) {
1330                 app_config->required_runtime = get_attribute_value (attribute_names, attribute_values, "version");
1331         } else if (strcmp (element_name, "supportedRuntime") == 0) {
1332                 char *version = get_attribute_value (attribute_names, attribute_values, "version");
1333                 app_config->supported_runtimes = g_slist_append (app_config->supported_runtimes, version);
1334         }
1335 }
1336
1337 static void end_element   (GMarkupParseContext *context,
1338                            const gchar         *element_name,
1339                            gpointer             user_data,
1340                            GError             **error)
1341 {
1342         AppConfigInfo* app_config = (AppConfigInfo*) user_data;
1343         
1344         if (strcmp (element_name, "configuration") == 0) {
1345                 app_config->configuration_count--;
1346         } else if (strcmp (element_name, "startup") == 0) {
1347                 app_config->startup_count--;
1348         }
1349 }
1350
1351 static const GMarkupParser 
1352 mono_parser = {
1353         start_element,
1354         end_element,
1355         NULL,
1356         NULL,
1357         NULL
1358 };
1359
1360 static AppConfigInfo *
1361 app_config_parse (const char *filename)
1362 {
1363         AppConfigInfo *app_config;
1364         GMarkupParseContext *context;
1365         char *text;
1366         gsize len;
1367         
1368         struct stat buf;
1369         if (stat (filename, &buf) != 0)
1370                 return NULL;
1371         
1372         app_config = g_new0 (AppConfigInfo, 1);
1373
1374         if (!g_file_get_contents (filename, &text, &len, NULL))
1375                 return NULL;
1376
1377         context = g_markup_parse_context_new (&mono_parser, 0, app_config, NULL);
1378         if (g_markup_parse_context_parse (context, text, len, NULL)) {
1379                 g_markup_parse_context_end_parse (context, NULL);
1380         }
1381         g_markup_parse_context_free (context);
1382         g_free (text);
1383         return app_config;
1384 }
1385
1386 static void 
1387 app_config_free (AppConfigInfo* app_config)
1388 {
1389         char *rt;
1390         GSList *list = app_config->supported_runtimes;
1391         while (list != NULL) {
1392                 rt = (char*)list->data;
1393                 g_free (rt);
1394                 list = g_slist_next (list);
1395         }
1396         g_slist_free (app_config->supported_runtimes);
1397         g_free (app_config->required_runtime);
1398         g_free (app_config);
1399 }
1400
1401
1402 static const MonoRuntimeInfo*
1403 get_runtime_by_version (const char *version)
1404 {
1405         int n;
1406         int max = G_N_ELEMENTS (supported_runtimes);
1407         
1408         for (n=0; n<max; n++) {
1409                 if (strcmp (version, supported_runtimes[n].runtime_version) == 0)
1410                         return &supported_runtimes[n];
1411         }
1412         return NULL;
1413 }
1414
1415 static void
1416 get_runtimes_from_exe (const char *exe_file, const MonoRuntimeInfo** runtimes)
1417 {
1418         AppConfigInfo* app_config;
1419         char *version;
1420         char *config_name;
1421         const MonoRuntimeInfo* runtime = NULL;
1422         MonoImage *image = NULL;
1423         
1424         config_name = g_strconcat (exe_file, ".config", NULL);
1425         app_config = app_config_parse (config_name);
1426         g_free (config_name);
1427         
1428         if (app_config != NULL) {
1429                 /* Check supportedRuntime elements, if none is supported, fail.
1430                  * If there are no such elements, look for a requiredRuntime element.
1431                  */
1432                 if (app_config->supported_runtimes != NULL) {
1433                         int n = 0;
1434                         GSList *list = app_config->supported_runtimes;
1435                         while (list != NULL) {
1436                                 version = (char*) list->data;
1437                                 runtime = get_runtime_by_version (version);
1438                                 if (runtime != NULL)
1439                                         runtimes [n++] = runtime;
1440                                 list = g_slist_next (list);
1441                         }
1442                         runtimes [n] = NULL;
1443                         app_config_free (app_config);
1444                         return;
1445                 }
1446                 
1447                 /* Check the requiredRuntime element. This is for 1.0 apps only. */
1448                 if (app_config->required_runtime != NULL) {
1449                         runtimes [0] = get_runtime_by_version (app_config->required_runtime);
1450                         runtimes [1] = NULL;
1451                         app_config_free (app_config);
1452                         return;
1453                 }
1454                 app_config_free (app_config);
1455         }
1456         
1457         /* Look for a runtime with the exact version */
1458         image = mono_image_open (exe_file, NULL);
1459         if (image == NULL) {
1460                 /* The image is wrong or the file was not found. In this case return
1461                  * a default runtime and leave to the initialization method the work of
1462                  * reporting the error.
1463                  */
1464                 runtimes [0] = get_runtime_by_version (DEFAULT_RUNTIME_VERSION);
1465                 runtimes [1] = NULL;
1466                 return;
1467         }
1468
1469         /* 
1470          * FIXME: This would cause us to unload the image, and it will be loaded again later.
1471          * Disabling it will mean the initial exe will not be unloaded on shutdown.
1472          */
1473         //mono_image_close (image);
1474
1475         runtimes [0] = get_runtime_by_version (image->version);
1476         runtimes [1] = NULL;
1477 }
1478
1479
1480 /**
1481  * mono_get_runtime_info:
1482  *
1483  * Returns: the version of the current runtime instance.
1484  */
1485 const MonoRuntimeInfo*
1486 mono_get_runtime_info (void)
1487 {
1488         return current_runtime;
1489 }
1490
1491 gchar *
1492 mono_debugger_check_runtime_version (const char *filename)
1493 {
1494         const MonoRuntimeInfo* runtimes [G_N_ELEMENTS (supported_runtimes) + 1];
1495         const MonoRuntimeInfo *rinfo;
1496
1497         get_runtimes_from_exe (filename, runtimes);
1498         rinfo = runtimes [0];
1499
1500         if (!rinfo)
1501                 return g_strdup_printf ("Cannot get runtime version from assembly `%s'", filename);
1502
1503         if (rinfo != current_runtime)
1504                 return g_strdup_printf ("The Mono Debugger is currently using the `%s' runtime, but "
1505                                         "the assembly `%s' requires version `%s'", current_runtime->runtime_version,
1506                                         filename, rinfo->runtime_version);
1507
1508         return NULL;
1509 }