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