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