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