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