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