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