2004-10-08 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/metadata/object.h>
20 #include <mono/metadata/domain-internals.h>
21 #include <mono/metadata/class-internals.h>
22 #include <mono/metadata/assembly.h>
23 #include <mono/metadata/exception.h>
24 #include <mono/metadata/cil-coff.h>
25 #include <mono/metadata/rawbuffer.h>
26 #include <mono/metadata/metadata-internals.h>
27 #include <mono/metadata/mono-debug-debugger.h>
28
29 /* #define DEBUG_DOMAIN_UNLOAD */
30
31 /* we need to use both the Tls* functions and __thread because
32  * the gc needs to see all the appcontext
33  */
34 static guint32 context_thread_id = -1;
35 static guint32 appdomain_thread_id = -1;
36  
37 #ifdef HAVE_KW_THREAD
38 static __thread MonoDomain * tls_appdomain;
39 static __thread MonoAppContext * tls_appcontext;
40 #define GET_APPDOMAIN() tls_appdomain
41 #define SET_APPDOMAIN(x) do { \
42         tls_appdomain = x; \
43         TlsSetValue (appdomain_thread_id, x); \
44 } while (FALSE)
45
46 #define GET_APPCONTEXT() tls_appcontext
47 #define SET_APPCONTEXT(x) do { \
48         tls_appcontext = x; \
49         TlsSetValue (context_thread_id, x); \
50 } while (FALSE)
51
52 #else
53 #define GET_APPDOMAIN() ((MonoDomain *)TlsGetValue (appdomain_thread_id))
54 #define SET_APPDOMAIN(x) TlsSetValue (appdomain_thread_id, x);
55
56 #define GET_APPCONTEXT() ((MonoAppContext *)TlsGetValue (context_thread_id))
57 #define SET_APPCONTEXT(x) TlsSetValue (context_thread_id, x);
58 #endif
59
60 static gint32 appdomain_id_counter = 0;
61
62 static MonoGHashTable * appdomains_list = NULL;
63
64 static CRITICAL_SECTION appdomains_mutex;
65
66 static MonoDomain *mono_root_domain = NULL;
67
68 /* RuntimeInfo: Contains information about versions supported by this runtime */
69 typedef struct  {
70         const char* runtime_version;
71         const char* framework_version;
72 } RuntimeInfo;
73
74 /* AppConfigInfo: Information about runtime versions supported by an 
75  * aplication.
76  */
77 typedef struct {
78         GSList *supported_runtimes;
79         char *required_runtime;
80         int configuration_count;
81         int startup_count;
82 } AppConfigInfo;
83
84 static RuntimeInfo *current_runtime = NULL;
85
86 /* This is the list of runtime versions supported by this JIT.
87  */
88 static RuntimeInfo supported_runtimes[] = {
89         {"v1.0.3705", "1.0"}, {"v1.1.4322", "1.0"}, {"v2.0.40607","2.0"} 
90 };
91
92 /* The stable runtime version */
93 #define DEFAULT_RUNTIME_VERSION "v1.1.4322"
94
95 static RuntimeInfo*     
96 get_runtime_from_exe (const char *exe_file);
97
98 static RuntimeInfo*
99 get_runtime_by_version (const char *version);
100
101 static MonoJitInfoTable *
102 mono_jit_info_table_new (void)
103 {
104         return g_array_new (FALSE, FALSE, sizeof (gpointer));
105 }
106
107 static void
108 mono_jit_info_table_free (MonoJitInfoTable *table)
109 {
110         g_array_free (table, TRUE);
111 }
112
113 static int
114 mono_jit_info_table_index (MonoJitInfoTable *table, char *addr)
115 {
116         int left = 0, right = table->len;
117
118         while (left < right) {
119                 int pos = (left + right) / 2;
120                 MonoJitInfo *ji = g_array_index (table, gpointer, pos);
121                 char *start = ji->code_start;
122                 char *end = start + ji->code_size;
123
124                 if (addr < start)
125                         right = pos;
126                 else if (addr >= end) 
127                         left = pos + 1;
128                 else
129                         return pos;
130         }
131
132         return left;
133 }
134
135 MonoJitInfo *
136 mono_jit_info_table_find (MonoDomain *domain, char *addr)
137 {
138         MonoJitInfoTable *table = domain->jit_info_table;
139         int left = 0, right;
140
141         mono_domain_lock (domain);
142
143         right = table->len;
144         while (left < right) {
145                 int pos = (left + right) / 2;
146                 MonoJitInfo *ji = g_array_index (table, gpointer, pos);
147                 char *start = ji->code_start;
148                 char *end = start + ji->code_size;
149
150                 if (addr < start)
151                         right = pos;
152                 else if (addr >= end) 
153                         left = pos + 1;
154                 else {
155                         mono_domain_unlock (domain);
156                         return ji;
157                 }
158         }
159         mono_domain_unlock (domain);
160
161         /* maybe it is shared code, so we also search in the root domain */
162         if (domain != mono_root_domain)
163                 return mono_jit_info_table_find (mono_root_domain, addr);
164
165         return NULL;
166 }
167
168 void
169 mono_jit_info_table_add (MonoDomain *domain, MonoJitInfo *ji)
170 {
171         MonoJitInfoTable *table = domain->jit_info_table;
172         gpointer start = ji->code_start;
173         int pos;
174
175         mono_domain_lock (domain);
176         pos = mono_jit_info_table_index (table, start);
177
178         g_array_insert_val (table, pos, ji);
179         mono_domain_unlock (domain);
180 }
181
182 void
183 mono_jit_info_table_remove (MonoDomain *domain, MonoJitInfo *ji)
184 {
185         MonoJitInfoTable *table = domain->jit_info_table;
186         gpointer start = ji->code_start;
187         int pos;
188
189         mono_domain_lock (domain);
190         pos = mono_jit_info_table_index (table, start);
191         g_assert (g_array_index (table, gpointer, pos) == ji);
192
193         g_array_remove_index (table, pos);
194         mono_domain_unlock (domain);
195 }       
196
197 static int
198 ldstr_hash (const char* str)
199 {
200         guint len, h;
201         const char *end;
202         len = mono_metadata_decode_blob_size (str, &str) - 1;
203         end = str + len;
204         /* if len == 0 *str will point to the mark byte */
205         h = len? *str: 0;
206         /*
207          * FIXME: The distribution may not be so nice with lots of
208          * null chars in the string.
209          */
210         for (str += 1; str < end; str++)
211                 h = (h << 5) - h + *str;
212         return h;
213 }
214
215 static gboolean
216 ldstr_equal (const char *str1, const char *str2) {
217         int len, len2;
218         if (str1 == str2)
219                 return TRUE;
220         len = mono_metadata_decode_blob_size (str1, NULL) - 1;
221         len2 = mono_metadata_decode_blob_size (str2, NULL) - 1;
222         if (len != len2)
223                 return 0;
224         return memcmp (str1, str2, len) == 0;
225 }
226
227 static gboolean
228 mono_string_equal (MonoString *s1, MonoString *s2)
229 {
230         int l1 = mono_string_length (s1);
231         int l2 = mono_string_length (s2);
232
233         if (l1 != l2)
234                 return FALSE;
235
236         return memcmp (mono_string_chars (s1), mono_string_chars (s2), l1) == 0; 
237 }
238
239 static guint
240 mono_string_hash (MonoString *s)
241 {
242         const guint16 *p = mono_string_chars (s);
243         int i, len = mono_string_length (s);
244         guint h = 0;
245
246         for (i = 0; i < len; i++) {
247                 h = (h << 5) - h + *p;
248                 p++;
249         }
250
251         return h;       
252 }
253
254 #if HAVE_BOEHM_GC
255 static void
256 domain_finalizer (void *obj, void *data) {
257         g_print ("domain finalized\n");
258 }
259 #endif
260
261 MonoDomain *
262 mono_domain_create (void)
263 {
264         MonoDomain *domain;
265
266 #if HAVE_BOEHM_GC
267         domain = GC_MALLOC (sizeof (MonoDomain));
268         GC_REGISTER_FINALIZER (domain, domain_finalizer, NULL, NULL, NULL);
269 #else
270         domain = g_new0 (MonoDomain, 1);
271 #endif
272         domain->domain = NULL;
273         domain->setup = NULL;
274         domain->friendly_name = NULL;
275         domain->search_path = NULL;
276
277         domain->mp = mono_mempool_new ();
278         domain->code_mp = mono_code_manager_new ();
279         domain->env = mono_g_hash_table_new ((GHashFunc)mono_string_hash, (GCompareFunc)mono_string_equal);
280         domain->assemblies_by_name = g_hash_table_new (g_str_hash, g_str_equal);
281         domain->assemblies = NULL;
282         domain->class_vtable_hash = mono_g_hash_table_new (NULL, NULL);
283         domain->proxy_vtable_hash = mono_g_hash_table_new ((GHashFunc)mono_string_hash, (GCompareFunc)mono_string_equal);
284         domain->static_data_hash = mono_g_hash_table_new (NULL, NULL);
285         domain->jit_code_hash = g_hash_table_new (NULL, NULL);
286         domain->ldstr_table = mono_g_hash_table_new ((GHashFunc)ldstr_hash, (GCompareFunc)ldstr_equal);
287         domain->jit_info_table = mono_jit_info_table_new ();
288         domain->class_init_trampoline_hash = mono_g_hash_table_new (NULL, NULL);
289         domain->jump_trampoline_hash = mono_g_hash_table_new (NULL, NULL);
290         domain->finalizable_objects_hash = g_hash_table_new (NULL, NULL);
291         domain->domain_id = InterlockedIncrement (&appdomain_id_counter);
292
293         InitializeCriticalSection (&domain->lock);
294
295         EnterCriticalSection (&appdomains_mutex);
296         mono_g_hash_table_insert(appdomains_list, GINT_TO_POINTER(domain->domain_id), domain);
297         LeaveCriticalSection (&appdomains_mutex);
298
299         return domain;
300 }
301
302 /**
303  * mono_init_internal:
304  * 
305  * Creates the initial application domain and initializes the mono_defaults
306  * structure.
307  * This function is guaranteed to not run any IL code.
308  * If exe_filename is not NULL, the method will determine the required runtime
309  * from the exe configuration file or the version PE field.
310  * If runtime_version is not NULL, that runtime version will be used.
311  * Either exe_filename or runtime_version must be provided.
312  *
313  * Returns: the initial domain.
314  */
315 static MonoDomain *
316 mono_init_internal (const char *filename, const char *exe_filename, const char *runtime_version)
317 {
318         static MonoDomain *domain = NULL;
319         MonoAssembly *ass;
320         MonoImageOpenStatus status = MONO_IMAGE_OK;
321         MonoAssemblyName corlib_aname;
322
323         if (domain)
324                 g_assert_not_reached ();
325
326         MONO_GC_PRE_INIT ();
327
328         appdomain_thread_id = TlsAlloc ();
329         context_thread_id = TlsAlloc ();
330
331         InitializeCriticalSection (&appdomains_mutex);
332
333         mono_metadata_init ();
334         mono_raw_buffer_init ();
335         mono_images_init ();
336         mono_assemblies_init ();
337         mono_loader_init ();
338
339         /* FIXME: When should we release this memory? */
340         MONO_GC_REGISTER_ROOT (appdomains_list);
341         appdomains_list = mono_g_hash_table_new (g_direct_hash, g_direct_equal);
342
343         domain = mono_domain_create ();
344         mono_root_domain = domain;
345
346         SET_APPDOMAIN (domain);
347         
348         if (exe_filename != NULL) {
349                 current_runtime = get_runtime_from_exe (exe_filename);
350         } else if (runtime_version != NULL) {
351                 current_runtime = get_runtime_by_version (runtime_version);
352         }
353
354         if (current_runtime == NULL) {
355                 g_print ("WARNING: The runtime version supported by this application is unavailable.\n");
356                 current_runtime = get_runtime_by_version (DEFAULT_RUNTIME_VERSION);
357                 g_print ("Using default runtime: %s\n", current_runtime->runtime_version);
358         }
359
360         /* find the corlib */
361         corlib_aname.name = "mscorlib";
362         ass = mono_assembly_load (&corlib_aname, NULL, &status);
363         if ((status != MONO_IMAGE_OK) || (ass == NULL)) {
364                 switch (status){
365                 case MONO_IMAGE_ERROR_ERRNO: {
366                         char *corlib_file = g_build_filename (mono_assembly_getrootdir (), "mono", mono_get_framework_version (), "mscorlib.dll", NULL);
367                         g_print ("The assembly mscorlib.dll was not found or could not be loaded.\n");
368                         g_print ("It should have been installed in the `%s' directory.\n", corlib_file);
369                         g_free (corlib_file);
370                         break;
371                 }
372                 case MONO_IMAGE_IMAGE_INVALID:
373                         g_print ("The file %s/mscorlib.dll is an invalid CIL image\n",
374                                  mono_assembly_getrootdir ());
375                         break;
376                 case MONO_IMAGE_MISSING_ASSEMBLYREF:
377                         g_print ("Missing assembly reference in %s/mscorlib.dll\n",
378                                  mono_assembly_getrootdir ());
379                         break;
380                 case MONO_IMAGE_OK:
381                         /* to suppress compiler warning */
382                         break;
383                 }
384                 
385                 exit (1);
386         }
387         mono_defaults.corlib = mono_assembly_get_image (ass);
388
389         mono_defaults.object_class = mono_class_from_name (
390                 mono_defaults.corlib, "System", "Object");
391         g_assert (mono_defaults.object_class != 0);
392
393         mono_defaults.void_class = mono_class_from_name (
394                 mono_defaults.corlib, "System", "Void");
395         g_assert (mono_defaults.void_class != 0);
396
397         mono_defaults.boolean_class = mono_class_from_name (
398                 mono_defaults.corlib, "System", "Boolean");
399         g_assert (mono_defaults.boolean_class != 0);
400
401         mono_defaults.byte_class = mono_class_from_name (
402                 mono_defaults.corlib, "System", "Byte");
403         g_assert (mono_defaults.byte_class != 0);
404
405         mono_defaults.sbyte_class = mono_class_from_name (
406                 mono_defaults.corlib, "System", "SByte");
407         g_assert (mono_defaults.sbyte_class != 0);
408
409         mono_defaults.int16_class = mono_class_from_name (
410                 mono_defaults.corlib, "System", "Int16");
411         g_assert (mono_defaults.int16_class != 0);
412
413         mono_defaults.uint16_class = mono_class_from_name (
414                 mono_defaults.corlib, "System", "UInt16");
415         g_assert (mono_defaults.uint16_class != 0);
416
417         mono_defaults.int32_class = mono_class_from_name (
418                 mono_defaults.corlib, "System", "Int32");
419         g_assert (mono_defaults.int32_class != 0);
420
421         mono_defaults.uint32_class = mono_class_from_name (
422                 mono_defaults.corlib, "System", "UInt32");
423         g_assert (mono_defaults.uint32_class != 0);
424
425         mono_defaults.uint_class = mono_class_from_name (
426                 mono_defaults.corlib, "System", "UIntPtr");
427         g_assert (mono_defaults.uint_class != 0);
428
429         mono_defaults.int_class = mono_class_from_name (
430                 mono_defaults.corlib, "System", "IntPtr");
431         g_assert (mono_defaults.int_class != 0);
432
433         mono_defaults.int64_class = mono_class_from_name (
434                 mono_defaults.corlib, "System", "Int64");
435         g_assert (mono_defaults.int64_class != 0);
436
437         mono_defaults.uint64_class = mono_class_from_name (
438                 mono_defaults.corlib, "System", "UInt64");
439         g_assert (mono_defaults.uint64_class != 0);
440
441         mono_defaults.single_class = mono_class_from_name (
442                 mono_defaults.corlib, "System", "Single");
443         g_assert (mono_defaults.single_class != 0);
444
445         mono_defaults.double_class = mono_class_from_name (
446                 mono_defaults.corlib, "System", "Double");
447         g_assert (mono_defaults.double_class != 0);
448
449         mono_defaults.char_class = mono_class_from_name (
450                 mono_defaults.corlib, "System", "Char");
451         g_assert (mono_defaults.char_class != 0);
452
453         mono_defaults.string_class = mono_class_from_name (
454                 mono_defaults.corlib, "System", "String");
455         g_assert (mono_defaults.string_class != 0);
456
457         mono_defaults.enum_class = mono_class_from_name (
458                 mono_defaults.corlib, "System", "Enum");
459         g_assert (mono_defaults.enum_class != 0);
460
461         mono_defaults.array_class = mono_class_from_name (
462                 mono_defaults.corlib, "System", "Array");
463         g_assert (mono_defaults.array_class != 0);
464
465         mono_defaults.delegate_class = mono_class_from_name (
466                 mono_defaults.corlib, "System", "Delegate");
467         g_assert (mono_defaults.delegate_class != 0 );
468
469         mono_defaults.multicastdelegate_class = mono_class_from_name (
470                 mono_defaults.corlib, "System", "MulticastDelegate");
471         g_assert (mono_defaults.multicastdelegate_class != 0 );
472
473         mono_defaults.asyncresult_class = mono_class_from_name (
474                 mono_defaults.corlib, "System.Runtime.Remoting.Messaging", 
475                 "AsyncResult");
476         g_assert (mono_defaults.asyncresult_class != 0 );
477
478         mono_defaults.waithandle_class = mono_class_from_name (
479                 mono_defaults.corlib, "System.Threading", "WaitHandle");
480         g_assert (mono_defaults.waithandle_class != 0 );
481
482         mono_defaults.typehandle_class = mono_class_from_name (
483                 mono_defaults.corlib, "System", "RuntimeTypeHandle");
484         g_assert (mono_defaults.typehandle_class != 0);
485
486         mono_defaults.methodhandle_class = mono_class_from_name (
487                 mono_defaults.corlib, "System", "RuntimeMethodHandle");
488         g_assert (mono_defaults.methodhandle_class != 0);
489
490         mono_defaults.fieldhandle_class = mono_class_from_name (
491                 mono_defaults.corlib, "System", "RuntimeFieldHandle");
492         g_assert (mono_defaults.fieldhandle_class != 0);
493
494         mono_defaults.monotype_class = mono_class_from_name (
495                 mono_defaults.corlib, "System", "MonoType");
496         g_assert (mono_defaults.monotype_class != 0);
497
498         mono_defaults.exception_class = mono_class_from_name (
499                 mono_defaults.corlib, "System", "Exception");
500         g_assert (mono_defaults.exception_class != 0);
501
502         mono_defaults.threadabortexception_class = mono_class_from_name (
503                 mono_defaults.corlib, "System.Threading", "ThreadAbortException");
504         g_assert (mono_defaults.threadabortexception_class != 0);
505
506         mono_defaults.thread_class = mono_class_from_name (
507                 mono_defaults.corlib, "System.Threading", "Thread");
508         g_assert (mono_defaults.thread_class != 0);
509
510         mono_defaults.appdomain_class = mono_class_from_name (
511                 mono_defaults.corlib, "System", "AppDomain");
512         g_assert (mono_defaults.appdomain_class != 0);
513
514         mono_defaults.transparent_proxy_class = mono_class_from_name (
515                 mono_defaults.corlib, "System.Runtime.Remoting.Proxies", "TransparentProxy");
516         g_assert (mono_defaults.transparent_proxy_class != 0);
517
518         mono_defaults.real_proxy_class = mono_class_from_name (
519                 mono_defaults.corlib, "System.Runtime.Remoting.Proxies", "RealProxy");
520         g_assert (mono_defaults.real_proxy_class != 0);
521
522         mono_defaults.mono_method_message_class = mono_class_from_name (
523                 mono_defaults.corlib, "System.Runtime.Remoting.Messaging", "MonoMethodMessage");
524         g_assert (mono_defaults.mono_method_message_class != 0);
525
526         mono_defaults.field_info_class = mono_class_from_name (
527                 mono_defaults.corlib, "System.Reflection", "FieldInfo");
528         g_assert (mono_defaults.field_info_class != 0);
529
530         mono_defaults.method_info_class = mono_class_from_name (
531                 mono_defaults.corlib, "System.Reflection", "MethodInfo");
532         g_assert (mono_defaults.method_info_class != 0);
533
534         mono_defaults.stringbuilder_class = mono_class_from_name (
535                 mono_defaults.corlib, "System.Text", "StringBuilder");
536         g_assert (mono_defaults.stringbuilder_class != 0);
537
538         mono_defaults.math_class = mono_class_from_name (
539                 mono_defaults.corlib, "System", "Math");
540         g_assert (mono_defaults.math_class != 0);
541
542         mono_defaults.stack_frame_class = mono_class_from_name (
543                 mono_defaults.corlib, "System.Diagnostics", "StackFrame");
544         g_assert (mono_defaults.stack_frame_class != 0);
545
546         mono_defaults.stack_trace_class = mono_class_from_name (
547                 mono_defaults.corlib, "System.Diagnostics", "StackTrace");
548         g_assert (mono_defaults.stack_trace_class != 0);
549
550         mono_defaults.marshal_class = mono_class_from_name (
551                 mono_defaults.corlib, "System.Runtime.InteropServices", "Marshal");
552         g_assert (mono_defaults.marshal_class != 0);
553
554         mono_defaults.iserializeable_class = mono_class_from_name (
555                 mono_defaults.corlib, "System.Runtime.Serialization", "ISerializable");
556         g_assert (mono_defaults.iserializeable_class != 0);
557
558         mono_defaults.serializationinfo_class = mono_class_from_name (
559                 mono_defaults.corlib, "System.Runtime.Serialization", "SerializationInfo");
560         g_assert (mono_defaults.serializationinfo_class != 0);
561
562         mono_defaults.streamingcontext_class = mono_class_from_name (
563                 mono_defaults.corlib, "System.Runtime.Serialization", "StreamingContext");
564         g_assert (mono_defaults.streamingcontext_class != 0);
565
566         mono_defaults.typed_reference_class =  mono_class_from_name (
567                 mono_defaults.corlib, "System", "TypedReference");
568         g_assert (mono_defaults.typed_reference_class != 0);
569
570         mono_defaults.argumenthandle_class =  mono_class_from_name (
571                 mono_defaults.corlib, "System", "RuntimeArgumentHandle");
572         g_assert (mono_defaults.argumenthandle_class != 0);
573
574         mono_defaults.marshalbyrefobject_class =  mono_class_from_name (
575                 mono_defaults.corlib, "System", "MarshalByRefObject");
576         g_assert (mono_defaults.marshalbyrefobject_class != 0);
577
578         mono_defaults.monitor_class =  mono_class_from_name (
579                 mono_defaults.corlib, "System.Threading", "Monitor");
580         g_assert (mono_defaults.monitor_class != 0);
581
582         mono_defaults.iremotingtypeinfo_class = mono_class_from_name (
583                 mono_defaults.corlib, "System.Runtime.Remoting", "IRemotingTypeInfo");
584         g_assert (mono_defaults.iremotingtypeinfo_class != 0);
585
586         domain->friendly_name = g_path_get_basename (filename);
587
588         return domain;
589 }
590
591 /**
592  * mono_init:
593  * 
594  * Creates the initial application domain and initializes the mono_defaults
595  * structure.
596  * This function is guaranteed to not run any IL code.
597  * The runtime is initialized using the default runtime version.
598  *
599  * Returns: the initial domain.
600  */
601 MonoDomain *
602 mono_init (const char *domain_name)
603 {
604         return mono_init_internal (domain_name, NULL, DEFAULT_RUNTIME_VERSION);
605 }
606
607 /**
608  * mono_init_from_assembly:
609  * 
610  * Creates the initial application domain and initializes the mono_defaults
611  * structure.
612  * This function is guaranteed to not run any IL code.
613  * The runtime is initialized using the runtime version required by the
614  * provided executable. The version is determined by looking at the exe 
615  * configuration file and the version PE field)
616  *
617  * Returns: the initial domain.
618  */
619 MonoDomain *
620 mono_init_from_assembly (const char *domain_name, const char *filename)
621 {
622         return mono_init_internal (domain_name, filename, NULL);
623 }
624
625 /**
626  * mono_init_version:
627  * 
628  * Creates the initial application domain and initializes the mono_defaults
629  * structure.
630  * This function is guaranteed to not run any IL code.
631  * The runtime is initialized using the provided rutime version.
632  *
633  * Returns: the initial domain.
634  */
635 MonoDomain *
636 mono_init_version (const char *domain_name, const char *version)
637 {
638         return mono_init_internal (domain_name, NULL, version);
639 }
640
641 MonoDomain*
642 mono_get_root_domain (void)
643 {
644         return mono_root_domain;
645 }
646
647 /**
648  * mono_domain_get:
649  *
650  * Returns the current domain.
651  */
652 inline MonoDomain *
653 mono_domain_get ()
654 {
655         return GET_APPDOMAIN ();
656 }
657
658 /**
659  * mono_domain_set_internal:
660  * @domain: the new domain
661  *
662  * Sets the current domain to @domain.
663  */
664 inline void
665 mono_domain_set_internal (MonoDomain *domain)
666 {
667         SET_APPDOMAIN (domain);
668         SET_APPCONTEXT (domain->default_context);
669 }
670
671 typedef struct {
672         MonoDomainFunc func;
673         gpointer user_data;
674 } DomainInfo;
675
676 static void
677 copy_hash_entry (gpointer key, gpointer data, gpointer user_data)
678 {
679         MonoGHashTable *dest = (MonoGHashTable*)user_data;
680
681         mono_g_hash_table_insert (dest, key, data);
682 }
683
684 static void
685 foreach_domain (gpointer key, gpointer data, gpointer user_data)
686 {
687         DomainInfo *dom_info = user_data;
688
689         dom_info->func ((MonoDomain*)data, dom_info->user_data);
690 }
691
692 void
693 mono_domain_foreach (MonoDomainFunc func, gpointer user_data)
694 {
695         DomainInfo dom_info;
696         MonoGHashTable *copy;
697
698         /*
699          * Create a copy of the hashtable to avoid calling the user callback
700          * inside the lock because that could lead to deadlocks.
701          * We can do this because this function is not perf. critical.
702          */
703         copy = mono_g_hash_table_new (NULL, NULL);
704         EnterCriticalSection (&appdomains_mutex);
705         mono_g_hash_table_foreach (appdomains_list, copy_hash_entry, copy);
706         LeaveCriticalSection (&appdomains_mutex);
707
708         dom_info.func = func;
709         dom_info.user_data = user_data;
710         mono_g_hash_table_foreach (copy, foreach_domain, &dom_info);
711
712         mono_g_hash_table_destroy (copy);
713 }
714
715 /**
716  * mono_domain_assembly_open:
717  * @domain: the application domain
718  * @name: file name of the assembly
719  *
720  * fixme: maybe we should integrate this with mono_assembly_open ??
721  */
722 MonoAssembly *
723 mono_domain_assembly_open (MonoDomain *domain, const char *name)
724 {
725         MonoAssembly *ass;
726
727         mono_domain_lock (domain);
728         if ((ass = g_hash_table_lookup (domain->assemblies_by_name, name))) {
729                 mono_domain_unlock (domain);
730                 return ass;
731         }
732         mono_domain_unlock (domain);
733
734         if (!(ass = mono_assembly_open (name, NULL)))
735                 return NULL;
736
737         return ass;
738 }
739
740 static void
741 remove_assembly (gpointer key, gpointer value, gpointer user_data)
742 {
743         mono_assembly_close ((MonoAssembly *)value);
744 }
745
746 static void
747 delete_jump_list (gpointer key, gpointer value, gpointer user_data)
748 {
749         g_slist_free (value);
750 }
751
752 void
753 mono_domain_free (MonoDomain *domain, gboolean force)
754 {
755         if ((domain == mono_root_domain) && !force) {
756                 g_warning ("cant unload root domain");
757                 return;
758         }
759
760         EnterCriticalSection (&appdomains_mutex);
761         mono_g_hash_table_remove (appdomains_list, GINT_TO_POINTER(domain->domain_id));
762         LeaveCriticalSection (&appdomains_mutex);
763         
764         g_free (domain->friendly_name);
765         g_hash_table_foreach (domain->assemblies_by_name, remove_assembly, NULL);
766
767         mono_g_hash_table_destroy (domain->env);
768         g_hash_table_destroy (domain->assemblies_by_name);
769         g_list_free (domain->assemblies);
770         mono_g_hash_table_destroy (domain->class_vtable_hash);
771         mono_g_hash_table_destroy (domain->proxy_vtable_hash);
772         mono_g_hash_table_destroy (domain->static_data_hash);
773         g_hash_table_destroy (domain->jit_code_hash);
774         mono_g_hash_table_destroy (domain->ldstr_table);
775         mono_jit_info_table_free (domain->jit_info_table);
776 #ifdef DEBUG_DOMAIN_UNLOAD
777         mono_mempool_invalidate (domain->mp);
778         mono_code_manager_invalidate (domain->code_mp);
779 #else
780         mono_mempool_destroy (domain->mp);
781         mono_code_manager_destroy (domain->code_mp);
782 #endif  
783         if (domain->jump_target_hash) {
784                 g_hash_table_foreach (domain->jump_target_hash, delete_jump_list, NULL);
785                 g_hash_table_destroy (domain->jump_target_hash);
786         }
787         mono_g_hash_table_destroy (domain->class_init_trampoline_hash);
788         mono_g_hash_table_destroy (domain->jump_trampoline_hash);
789         g_hash_table_destroy (domain->finalizable_objects_hash);
790         if (domain->special_static_fields)
791                 g_hash_table_destroy (domain->special_static_fields);
792         DeleteCriticalSection (&domain->lock);
793         domain->setup = NULL;
794
795         /* FIXME: anything else required ? */
796
797 #if HAVE_BOEHM_GC
798 #else
799         g_free (domain);
800 #endif
801
802         if ((domain == mono_root_domain))
803                 mono_root_domain = NULL;
804 }
805
806 /**
807  * mono_domain_get_id:
808  *
809  * Returns the a domain for a specific domain id.
810  */
811 MonoDomain * 
812 mono_domain_get_by_id (gint32 domainid) 
813 {
814         MonoDomain * domain;
815
816         EnterCriticalSection (&appdomains_mutex);
817         domain = mono_g_hash_table_lookup (appdomains_list, GINT_TO_POINTER(domainid));
818         LeaveCriticalSection (&appdomains_mutex);
819
820         return domain;
821 }
822
823 gint32
824 mono_domain_get_id (MonoDomain *domain)
825 {
826         return domain->domain_id;
827 }
828
829 void 
830 mono_context_set (MonoAppContext * new_context)
831 {
832         SET_APPCONTEXT (new_context);
833 }
834
835 MonoAppContext * 
836 mono_context_get (void)
837 {
838         return GET_APPCONTEXT ();
839 }
840
841 MonoImage*
842 mono_get_corlib (void)
843 {
844         return mono_defaults.corlib;
845 }
846
847 MonoClass*
848 mono_get_object_class (void)
849 {
850         return mono_defaults.object_class;
851 }
852
853 MonoClass*
854 mono_get_byte_class (void)
855 {
856         return mono_defaults.byte_class;
857 }
858
859 MonoClass*
860 mono_get_void_class (void)
861 {
862         return mono_defaults.void_class;
863 }
864
865 MonoClass*
866 mono_get_boolean_class (void)
867 {
868         return mono_defaults.boolean_class;
869 }
870
871 MonoClass*
872 mono_get_sbyte_class (void)
873 {
874         return mono_defaults.sbyte_class;
875 }
876
877 MonoClass*
878 mono_get_int16_class (void)
879 {
880         return mono_defaults.int16_class;
881 }
882
883 MonoClass*
884 mono_get_uint16_class (void)
885 {
886         return mono_defaults.uint16_class;
887 }
888
889 MonoClass*
890 mono_get_int32_class (void)
891 {
892         return mono_defaults.int32_class;
893 }
894
895 MonoClass*
896 mono_get_uint32_class (void)
897 {
898         return mono_defaults.uint32_class;
899 }
900
901 MonoClass*
902 mono_get_intptr_class (void)
903 {
904         return mono_defaults.int_class;
905 }
906
907 MonoClass*
908 mono_get_uintptr_class (void)
909 {
910         return mono_defaults.uint_class;
911 }
912
913 MonoClass*
914 mono_get_int64_class (void)
915 {
916         return mono_defaults.int64_class;
917 }
918
919 MonoClass*
920 mono_get_uint64_class (void)
921 {
922         return mono_defaults.uint64_class;
923 }
924
925 MonoClass*
926 mono_get_single_class (void)
927 {
928         return mono_defaults.single_class;
929 }
930
931 MonoClass*
932 mono_get_double_class (void)
933 {
934         return mono_defaults.double_class;
935 }
936
937 MonoClass*
938 mono_get_char_class (void)
939 {
940         return mono_defaults.char_class;
941 }
942
943 MonoClass*
944 mono_get_string_class (void)
945 {
946         return mono_defaults.string_class;
947 }
948
949 MonoClass*
950 mono_get_enum_class (void)
951 {
952         return mono_defaults.enum_class;
953 }
954
955 MonoClass*
956 mono_get_array_class (void)
957 {
958         return mono_defaults.array_class;
959 }
960
961 MonoClass*
962 mono_get_thread_class (void)
963 {
964         return mono_defaults.thread_class;
965 }
966
967 MonoClass*
968 mono_get_exception_class (void)
969 {
970         return mono_defaults.exception_class;
971 }
972
973
974 static char* get_attribute_value (const gchar **attribute_names, 
975                                         const gchar **attribute_values, 
976                                         const char *att_name)
977 {
978         int n;
979         for (n=0; attribute_names[n] != NULL; n++) {
980                 if (strcmp (attribute_names[n], att_name) == 0)
981                         return g_strdup (attribute_values[n]);
982         }
983         return NULL;
984 }
985
986 static void start_element (GMarkupParseContext *context, 
987                            const gchar         *element_name,
988                            const gchar        **attribute_names,
989                            const gchar        **attribute_values,
990                            gpointer             user_data,
991                            GError             **error)
992 {
993         AppConfigInfo* app_config = (AppConfigInfo*) user_data;
994         
995         if (strcmp (element_name, "configuration") == 0) {
996                 app_config->configuration_count++;
997                 return;
998         }
999         if (strcmp (element_name, "startup") == 0) {
1000                 app_config->startup_count++;
1001                 return;
1002         }
1003         
1004         if (app_config->configuration_count != 1 || app_config->startup_count != 1)
1005                 return;
1006         
1007         if (strcmp (element_name, "requiredRuntime") == 0) {
1008                 app_config->required_runtime = get_attribute_value (attribute_names, attribute_values, "version");
1009         } else if (strcmp (element_name, "supportedRuntime") == 0) {
1010                 char *version = get_attribute_value (attribute_names, attribute_values, "version");
1011                 app_config->supported_runtimes = g_slist_append (app_config->supported_runtimes, version);
1012         }
1013 }
1014
1015 static void end_element   (GMarkupParseContext *context,
1016                            const gchar         *element_name,
1017                            gpointer             user_data,
1018                            GError             **error)
1019 {
1020         AppConfigInfo* app_config = (AppConfigInfo*) user_data;
1021         
1022         if (strcmp (element_name, "configuration") == 0) {
1023                 app_config->configuration_count--;
1024         } else if (strcmp (element_name, "startup") == 0) {
1025                 app_config->startup_count--;
1026         }
1027 }
1028
1029 static const GMarkupParser 
1030 mono_parser = {
1031         start_element,
1032         end_element,
1033         NULL,
1034         NULL,
1035         NULL
1036 };
1037
1038 static AppConfigInfo *
1039 app_config_parse (const char *filename)
1040 {
1041         AppConfigInfo *app_config;
1042         GMarkupParseContext *context;
1043         char *text;
1044         gsize len;
1045         
1046         struct stat buf;
1047         if (stat (filename, &buf) != 0)
1048                 return NULL;
1049         
1050         app_config = g_new0 (AppConfigInfo, 1);
1051
1052         if (!g_file_get_contents (filename, &text, &len, NULL))
1053                 return NULL;
1054
1055         context = g_markup_parse_context_new (&mono_parser, 0, app_config, NULL);
1056         if (g_markup_parse_context_parse (context, text, len, NULL)) {
1057                 g_markup_parse_context_end_parse (context, NULL);
1058         }
1059         g_markup_parse_context_free (context);
1060         g_free (text);
1061         return app_config;
1062 }
1063
1064 static void 
1065 app_config_free (AppConfigInfo* app_config)
1066 {
1067         char *rt;
1068         GSList *list = app_config->supported_runtimes;
1069         while (list != NULL) {
1070                 rt = (char*)list->data;
1071                 g_free (rt);
1072                 list = g_slist_next (list);
1073         }
1074         g_slist_free (app_config->supported_runtimes);
1075         g_free (app_config->required_runtime);
1076         g_free (app_config);
1077 }
1078
1079
1080 static RuntimeInfo*
1081 get_runtime_by_version (const char *version)
1082 {
1083         int n;
1084         int max = G_N_ELEMENTS (supported_runtimes);
1085         
1086         for (n=0; n<max; n++) {
1087                 if (strcmp (version, supported_runtimes[n].runtime_version) == 0)
1088                         return &supported_runtimes[n];
1089         }
1090         return NULL;
1091 }
1092
1093 static RuntimeInfo*     
1094 get_runtime_from_exe (const char *exe_file)
1095 {
1096         AppConfigInfo* app_config;
1097         char *version;
1098         char *config_name;
1099         RuntimeInfo* runtime = NULL;
1100         MonoImage *image = NULL;
1101         
1102         config_name = g_strconcat (exe_file, ".config", NULL);
1103         app_config = app_config_parse (config_name);
1104         g_free (config_name);
1105         
1106         if (app_config != NULL) {
1107                 /* Check supportedRuntime elements, if none is supported, fail.
1108                  * If there are no such elements, look for a requiredRuntime element.
1109                  */
1110                 if (app_config->supported_runtimes != NULL) {
1111                         GSList *list = app_config->supported_runtimes;
1112                         while (list != NULL && runtime == NULL) {
1113                                 version = (char*) list->data;
1114                                 runtime = get_runtime_by_version (version);
1115                                 list = g_slist_next (list);
1116                         }
1117                         app_config_free (app_config);
1118                         return runtime;
1119                 }
1120                 
1121                 /* Check the requiredRuntime element. This is for 1.0 apps only. */
1122                 if (app_config->required_runtime != NULL) {
1123                         runtime = get_runtime_by_version (app_config->required_runtime);
1124                         app_config_free (app_config);
1125                         return runtime;
1126                 }
1127                 app_config_free (app_config);
1128         }
1129         
1130         /* Look for a runtime with the exact version */
1131         image = mono_image_open (exe_file, NULL);
1132         if (image == NULL) {
1133                 /* The image is wrong or the file was not found. In this case return
1134                  * a default runtime and leave to the initialization method the work of
1135                  * reporting the error.
1136                  */
1137                 return get_runtime_by_version (DEFAULT_RUNTIME_VERSION);
1138         }
1139
1140         runtime = get_runtime_by_version (image->version);
1141         
1142         return runtime;
1143 }
1144
1145 const char*
1146 mono_get_framework_version (void)
1147 {
1148         return current_runtime->framework_version;
1149 }
1150
1151 const char*
1152 mono_get_runtime_version (void)
1153 {
1154         return current_runtime->runtime_version;
1155 }
1156
1157 gchar *
1158 mono_debugger_check_runtime_version (const char *filename)
1159 {
1160         RuntimeInfo *rinfo;
1161
1162         rinfo = get_runtime_from_exe (filename);
1163         if (!rinfo)
1164                 return g_strdup_printf ("Cannot get runtime version from assembly `%s'", filename);
1165
1166         if (rinfo != current_runtime)
1167                 return g_strdup_printf ("The Mono Debugger is currently using the `%s' runtime, but "
1168                                         "the assembly `%s' requires version `%s'", current_runtime->runtime_version,
1169                                         filename, rinfo->runtime_version);
1170
1171         return NULL;
1172 }