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