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