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