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