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