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