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