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