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